Example usage for org.eclipse.jdt.core IMethod exists

List of usage examples for org.eclipse.jdt.core IMethod exists

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

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;/* w w w .j  ava 2  s  .com*/
    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   w ww  . j a va2  s  . 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.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a method. Considers the M_* flags.
 *
 * @param method the element to render/*from  w  w  w.j a va  2s  . c  o  m*/
 * @param flags the rendering flags. Flags with names starting with 'M_' are considered.
 */
public void appendMethodLabel(IMethod method, long flags) {
    try {
        BindingKey resolvedKey = getFlag(flags, JavaElementLabels.USE_RESOLVED) && method.isResolved()
                ? new BindingKey(method.getKey())
                : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;

        // type parameters
        if (getFlag(flags, JavaElementLabels.M_PRE_TYPE_PARAMETERS)) {
            if (resolvedKey != null) {
                if (resolvedKey.isParameterizedMethod()) {
                    String[] typeArgRefs = resolvedKey.getTypeArguments();
                    if (typeArgRefs.length > 0) {
                        appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags);
                        fBuffer.append(' ');
                    }
                } else {
                    String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                    if (typeParameterSigs.length > 0) {
                        appendTypeParameterSignaturesLabel(typeParameterSigs, flags);
                        fBuffer.append(' ');
                    }
                }
            } else if (method.exists()) {
                ITypeParameter[] typeParameters = method.getTypeParameters();
                if (typeParameters.length > 0) {
                    appendTypeParametersLabels(typeParameters, flags);
                    fBuffer.append(' ');
                }
            }
        }

        // return type
        if (getFlag(flags, JavaElementLabels.M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
            fBuffer.append(' ');
        }

        // qualification
        if (getFlag(flags, JavaElementLabels.M_FULLY_QUALIFIED)) {
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }

        fBuffer.append(getElementName(method));

        // constructor type arguments
        if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS) && method.exists() && method.isConstructor()) {
            if (resolvedSig != null && resolvedKey.isParameterizedType()) {
                BindingKey declaringType = resolvedKey.getDeclaringType();
                if (declaringType != null) {
                    String[] declaringTypeArguments = declaringType.getTypeArguments();
                    appendTypeArgumentSignaturesLabel(method, declaringTypeArguments, flags);
                }
            }
        }

        // parameters
        fBuffer.append('(');
        String[] declaredParameterTypes = method.getParameterTypes();
        if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) {
            String[] types = null;
            int nParams = 0;
            boolean renderVarargs = false;
            boolean isPolymorphic = false;
            if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES)) {
                if (resolvedSig != null) {
                    types = Signature.getParameterTypes(resolvedSig);
                } else {
                    types = declaredParameterTypes;
                }
                nParams = types.length;
                renderVarargs = method.exists() && Flags.isVarargs(method.getFlags());
                if (renderVarargs && resolvedSig != null && declaredParameterTypes.length == 1
                        && JavaModelUtil.isPolymorphicSignature(method)) {
                    renderVarargs = false;
                    isPolymorphic = true;
                }
            }
            String[] names = null;
            if (getFlag(flags, JavaElementLabels.M_PARAMETER_NAMES) && method.exists()) {
                names = method.getParameterNames();
                if (isPolymorphic) {
                    // handled specially below
                } else if (types == null) {
                    nParams = names.length;
                } else { // types != null
                    if (nParams != names.length) {
                        if (resolvedSig != null && types.length > names.length) {
                            // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137
                            nParams = names.length;
                            String[] typesWithoutSyntheticParams = new String[nParams];
                            System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0,
                                    nParams);
                            types = typesWithoutSyntheticParams;
                        } else {
                            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029
                            // JavaPlugin.logErrorMessage("JavaElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                            names = null; // no names rendered
                        }
                    }
                }
            }

            ILocalVariable[] annotatedParameters = null;
            if (nParams > 0 && getFlag(flags, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) {
                annotatedParameters = method.getParameters();
            }

            for (int i = 0; i < nParams; i++) {
                if (i > 0) {
                    fBuffer.append(JavaElementLabels.COMMA_STRING);
                }
                if (annotatedParameters != null && i < annotatedParameters.length) {
                    appendAnnotationLabels(annotatedParameters[i].getAnnotations(), flags);
                }

                if (types != null) {
                    String paramSig = types[i];
                    if (renderVarargs && (i == nParams - 1)) {
                        int newDim = Signature.getArrayCount(paramSig) - 1;
                        appendTypeSignatureLabel(method, Signature.getElementType(paramSig), flags);
                        for (int k = 0; k < newDim; k++) {
                            fBuffer.append('[').append(']');
                        }
                        fBuffer.append(JavaElementLabels.ELLIPSIS_STRING);
                    } else {
                        appendTypeSignatureLabel(method, paramSig, flags);
                    }
                }
                if (names != null) {
                    if (types != null) {
                        fBuffer.append(' ');
                    }
                    if (isPolymorphic) {
                        fBuffer.append(names[0] + i);
                    } else {
                        fBuffer.append(names[i]);
                    }
                }
            }
        } else {
            if (declaredParameterTypes.length > 0) {
                fBuffer.append(JavaElementLabels.ELLIPSIS_STRING);
            }
        }
        fBuffer.append(')');

        if (getFlag(flags, JavaElementLabels.M_EXCEPTIONS)) {
            String[] types;
            if (resolvedKey != null) {
                types = resolvedKey.getThrownExceptions();
            } else {
                types = method.exists() ? method.getExceptionTypes() : new String[0];
            }
            if (types.length > 0) {
                fBuffer.append(" throws "); //$NON-NLS-1$
                for (int i = 0; i < types.length; i++) {
                    if (i > 0) {
                        fBuffer.append(JavaElementLabels.COMMA_STRING);
                    }
                    appendTypeSignatureLabel(method, types[i], flags);
                }
            }
        }

        if (getFlag(flags, JavaElementLabels.M_APP_TYPE_PARAMETERS)) {
            int offset = fBuffer.length();
            if (resolvedKey != null) {
                if (resolvedKey.isParameterizedMethod()) {
                    String[] typeArgRefs = resolvedKey.getTypeArguments();
                    if (typeArgRefs.length > 0) {
                        fBuffer.append(' ');
                        appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags);
                    }
                } else {
                    String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                    if (typeParameterSigs.length > 0) {
                        fBuffer.append(' ');
                        appendTypeParameterSignaturesLabel(typeParameterSigs, flags);
                    }
                }
            } else if (method.exists()) {
                ITypeParameter[] typeParameters = method.getTypeParameters();
                if (typeParameters.length > 0) {
                    fBuffer.append(' ');
                    appendTypeParametersLabels(typeParameters, flags);
                }
            }
            //            if (getFlag(flags, JavaElementLabels.COLORIZE) && offset != fBuffer.length()) {
            //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            //            }
        }

        if (getFlag(flags, JavaElementLabels.M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.DECL_STRING);
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
            //            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            //            }
        }

        // category
        if (getFlag(flags, JavaElementLabels.M_CATEGORY) && method.exists())
            appendCategoryLabel(method, flags);

        // post qualification
        if (getFlag(flags, JavaElementLabels.M_POST_QUALIFIED)) {
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            //            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
            //               fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
            //            }
        }

    } catch (JavaModelException e) {
        //TODO
        e.printStackTrace();
    }
}

From source file:com.amashchenko.eclipse.strutsclipse.ProjectUtil.java

License:Apache License

public static IMethod findClassParameterlessMethod(final IType clazz, final String methodName) {
    IMethod result = null;/*from www . ja v a 2 s  .  c o  m*/
    try {
        if (clazz != null) {
            IMethod method = clazz.getMethod(methodName, null);
            if (method != null && method.exists()) {
                result = method;
            } else {
                // try super classes
                IType[] superClasses = clazz.newSupertypeHierarchy(null).getAllSuperclasses(clazz);
                for (IType superType : superClasses) {
                    method = superType.getMethod(methodName, null);
                    if (method != null && method.exists()) {
                        result = method;
                        break;
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return result;
}

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

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>// ww w.j  a  v a 2  s  .c  om
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            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();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

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

                IType activityType = javaProject.findType(CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.java

License:Open Source License

/**
 * Tests that a class name is valid for usage in the manifest.
 * <p/>// w ww .j  av  a  2s.  c  o m
 * This tests the class existence, that it can be instantiated (ie it must not be abstract,
 * nor non static if enclosed), and that it extends the proper super class (not necessarily
 * directly)
 * @param javaProject the {@link IJavaProject} containing the class.
 * @param className the fully qualified name of the class to test.
 * @param superClassName the fully qualified name of the expected super class.
 * @param testVisibility if <code>true</code>, the method will check the visibility of the class
 * or of its constructors.
 * @return {@link #TEST_CLASS_OK} or an error message.
 */
public final static String testClassForManifest(IJavaProject javaProject, String className,
        String superClassName, boolean testVisibility) {
    try {
        // replace $ by .
        String javaClassName = className.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$

        // look for the IType object for this class
        IType type = javaProject.findType(javaClassName);
        if (type != null && type.exists()) {
            // test that the class is not abstract
            int flags = type.getFlags();
            if (Flags.isAbstract(flags)) {
                return String.format("%1$s is abstract", className);
            }

            // test whether the class is public or not.
            if (testVisibility && Flags.isPublic(flags) == false) {
                // if its not public, it may have a public default constructor,
                // which would then be fine.
                IMethod basicConstructor = type.getMethod(type.getElementName(), new String[0]);
                if (basicConstructor != null && basicConstructor.exists()) {
                    int constructFlags = basicConstructor.getFlags();
                    if (Flags.isPublic(constructFlags) == false) {
                        return String.format(
                                "%1$s or its default constructor must be public for the system to be able to instantiate it",
                                className);
                    }
                } else {
                    return String.format(
                            "%1$s must be public, or the system will not be able to instantiate it.",
                            className);
                }
            }

            // If it's enclosed, test that it's static. If its declaring class is enclosed
            // as well, test that it is also static, and public.
            IType declaringType = type;
            do {
                IType tmpType = declaringType.getDeclaringType();
                if (tmpType != null) {
                    if (tmpType.exists()) {
                        flags = declaringType.getFlags();
                        if (Flags.isStatic(flags) == false) {
                            return String.format("%1$s is enclosed, but not static",
                                    declaringType.getFullyQualifiedName());
                        }

                        flags = tmpType.getFlags();
                        if (testVisibility && Flags.isPublic(flags) == false) {
                            return String.format("%1$s is not public", tmpType.getFullyQualifiedName());
                        }
                    } else {
                        // if it doesn't exist, we need to exit so we may as well mark it null.
                        tmpType = null;
                    }
                }
                declaringType = tmpType;
            } while (declaringType != null);

            // test the class inherit from the specified super class.
            // get the type hierarchy
            ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());

            // if the super class is not the reference class, it may inherit from
            // it so we get its supertype. At some point it will be null and we
            // will stop
            IType superType = type;
            boolean foundProperSuperClass = false;
            while ((superType = hierarchy.getSuperclass(superType)) != null && superType.exists()) {
                if (superClassName.equals(superType.getFullyQualifiedName())) {
                    foundProperSuperClass = true;
                }
            }

            // didn't find the proper superclass? return false.
            if (foundProperSuperClass == false) {
                return String.format("%1$s does not extend %2$s", className, superClassName);
            }

            return TEST_CLASS_OK;
        } else {
            return String.format("Class %1$s does not exist", className);
        }
    } catch (JavaModelException e) {
        return String.format("%1$s: %2$s", className, e.getMessage());
    }
}

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

License:Open Source License

/**
 * Returns the activity associated with the given layout file.
 * <p>/*from   w w w  . j  av  a 2  s.com*/
 * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
 * guessActivity simply looks for references to "R.layout.foo", this method searches
 * for all usages of Activity#setContentView(int), and for each match it looks up the
 * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
 * a regexp to pull out "foo" from this, and stores the association that layout "foo"
 * is associated with the activity class that contained the setContentView call.
 * <p>
 * This has two potential advantages:
 * <ol>
 * <li>It can be faster. We do the reference search -once-, and we've built a map of
 * all the layout-to-activity mappings which we can then immediately look up other
 * layouts for, which is particularly useful at startup when we have to compute the
 * layout activity associations to populate the theme choosers.
 * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
 * field doesn't mean it's setting it as a content view.
 * </ol>
 * However, this second advantage is also its chief problem. There are some common
 * code constructs which means that the associated layout is not explicitly referenced
 * in a direct setContentView call; on a couple of sample projects I tested I found
 * patterns like for example "setContentView(v)" where "v" had been computed earlier.
 * Therefore, for now we're going to stick with the more general approach of just
 * looking up each field when needed. We're keeping the code around, though statically
 * compiled out with the "if (false)" construct below in case we revisit this.
 *
 * @param layoutFile the layout whose activity we want to look up
 * @return the activity name
 */
@SuppressWarnings("all")
@Nullable
public String guessActivityBySetContentView(String layoutName) {
    if (false) {
        // These should be fields
        final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
        Map<String, String> mUsages = null;

        sync();
        if (mUsages == null) {
            final Map<String, String> usages = new HashMap<String, String>();
            mUsages = usages;
            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();
                        IDocumentProvider provider = new TextFileDocumentProvider();
                        IResource resource = match.getResource();
                        try {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            if (document != null) {
                                String matchText = document.get(match.getOffset(), match.getLength());
                                Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
                                if (matcher.find()) {
                                    usages.put(matcher.group(1), fqcn);
                                }
                            }
                        } catch (Exception e) {
                            AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName());
                        } finally {
                            provider.disconnect(resource);
                        }
                    }
                }
            };
            try {
                IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
                if (javaProject == null) {
                    return null;
                }

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

                IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
                if (activityType != null) {
                    IMethod method = activityType.getMethod("setContentView", new String[] { "I" }); //$NON-NLS-1$ //$NON-NLS-2$
                    if (method.exists()) {
                        SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES);
                        search(requestor, javaProject, pattern);
                    }
                }
            } catch (CoreException e) {
                AdtPlugin.log(e, null);
            }
        }

        return mUsages.get(layoutName);
    }

    return null;
}

From source file:com.codenvy.ide.ext.java.server.javadoc.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a method. Considers the M_* flags.
 *
 * @param method the element to render/*from w  w w . jav  a  2s.c  o  m*/
 * @param flags the rendering flags. Flags with names starting with 'M_' are considered.
 */
public void appendMethodLabel(IMethod method, long flags) {
    try {
        BindingKey resolvedKey = getFlag(flags, JavaElementLabels.USE_RESOLVED) && method.isResolved()
                ? new BindingKey(method.getKey())
                : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;

        // type parameters
        if (getFlag(flags, JavaElementLabels.M_PRE_TYPE_PARAMETERS)) {
            if (resolvedKey != null) {
                if (resolvedKey.isParameterizedMethod()) {
                    String[] typeArgRefs = resolvedKey.getTypeArguments();
                    if (typeArgRefs.length > 0) {
                        appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags);
                        fBuffer.append(' ');
                    }
                } else {
                    String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                    if (typeParameterSigs.length > 0) {
                        appendTypeParameterSignaturesLabel(typeParameterSigs, flags);
                        fBuffer.append(' ');
                    }
                }
            } else if (method.exists()) {
                ITypeParameter[] typeParameters = method.getTypeParameters();
                if (typeParameters.length > 0) {
                    appendTypeParametersLabels(typeParameters, flags);
                    fBuffer.append(' ');
                }
            }
        }

        // return type
        if (getFlag(flags, JavaElementLabels.M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
            fBuffer.append(' ');
        }

        // qualification
        if (getFlag(flags, JavaElementLabels.M_FULLY_QUALIFIED)) {
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }

        fBuffer.append(getElementName(method));

        // constructor type arguments
        if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS) && method.exists() && method.isConstructor()) {
            if (resolvedSig != null && resolvedKey.isParameterizedType()) {
                BindingKey declaringType = resolvedKey.getDeclaringType();
                if (declaringType != null) {
                    String[] declaringTypeArguments = declaringType.getTypeArguments();
                    appendTypeArgumentSignaturesLabel(method, declaringTypeArguments, flags);
                }
            }
        }

        // parameters
        fBuffer.append('(');
        String[] declaredParameterTypes = method.getParameterTypes();
        if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES)) {
            String[] types = null;
            int nParams = 0;
            boolean renderVarargs = false;
            boolean isPolymorphic = false;
            if (getFlag(flags, JavaElementLabels.M_PARAMETER_TYPES)) {
                if (resolvedSig != null) {
                    types = Signature.getParameterTypes(resolvedSig);
                } else {
                    types = declaredParameterTypes;
                }
                nParams = types.length;
                renderVarargs = method.exists() && Flags.isVarargs(method.getFlags());
                if (renderVarargs && resolvedSig != null && declaredParameterTypes.length == 1
                        && JavaModelUtil.isPolymorphicSignature(method)) {
                    renderVarargs = false;
                    isPolymorphic = true;
                }
            }
            String[] names = null;
            if (getFlag(flags, JavaElementLabels.M_PARAMETER_NAMES) && method.exists()) {
                names = method.getParameterNames();
                if (isPolymorphic) {
                    // handled specially below
                } else if (types == null) {
                    nParams = names.length;
                } else { // types != null
                    if (nParams != names.length) {
                        if (resolvedSig != null && types.length > names.length) {
                            // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=99137
                            nParams = names.length;
                            String[] typesWithoutSyntheticParams = new String[nParams];
                            System.arraycopy(types, types.length - nParams, typesWithoutSyntheticParams, 0,
                                    nParams);
                            types = typesWithoutSyntheticParams;
                        } else {
                            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=101029
                            // JavaPlugin.logErrorMessage("JavaElementLabels: Number of param types(" + nParams + ") != number of names(" + names.length + "): " + method.getElementName());   //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                            names = null; // no names rendered
                        }
                    }
                }
            }

            ILocalVariable[] annotatedParameters = null;
            if (nParams > 0 && getFlag(flags, JavaElementLabels.M_PARAMETER_ANNOTATIONS)) {
                annotatedParameters = method.getParameters();
            }

            for (int i = 0; i < nParams; i++) {
                if (i > 0) {
                    fBuffer.append(JavaElementLabels.COMMA_STRING);
                }
                if (annotatedParameters != null && i < annotatedParameters.length) {
                    appendAnnotationLabels(annotatedParameters[i].getAnnotations(), flags);
                }

                if (types != null) {
                    String paramSig = types[i];
                    if (renderVarargs && (i == nParams - 1)) {
                        int newDim = Signature.getArrayCount(paramSig) - 1;
                        appendTypeSignatureLabel(method, Signature.getElementType(paramSig), flags);
                        for (int k = 0; k < newDim; k++) {
                            fBuffer.append('[').append(']');
                        }
                        fBuffer.append(JavaElementLabels.ELLIPSIS_STRING);
                    } else {
                        appendTypeSignatureLabel(method, paramSig, flags);
                    }
                }
                if (names != null) {
                    if (types != null) {
                        fBuffer.append(' ');
                    }
                    if (isPolymorphic) {
                        fBuffer.append(names[0] + i);
                    } else {
                        fBuffer.append(names[i]);
                    }
                }
            }
        } else {
            if (declaredParameterTypes.length > 0) {
                fBuffer.append(JavaElementLabels.ELLIPSIS_STRING);
            }
        }
        fBuffer.append(')');

        if (getFlag(flags, JavaElementLabels.M_EXCEPTIONS)) {
            String[] types;
            if (resolvedKey != null) {
                types = resolvedKey.getThrownExceptions();
            } else {
                types = method.exists() ? method.getExceptionTypes() : new String[0];
            }
            if (types.length > 0) {
                fBuffer.append(" throws "); //$NON-NLS-1$
                for (int i = 0; i < types.length; i++) {
                    if (i > 0) {
                        fBuffer.append(JavaElementLabels.COMMA_STRING);
                    }
                    appendTypeSignatureLabel(method, types[i], flags);
                }
            }
        }

        if (getFlag(flags, JavaElementLabels.M_APP_TYPE_PARAMETERS)) {
            int offset = fBuffer.length();
            if (resolvedKey != null) {
                if (resolvedKey.isParameterizedMethod()) {
                    String[] typeArgRefs = resolvedKey.getTypeArguments();
                    if (typeArgRefs.length > 0) {
                        fBuffer.append(' ');
                        appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags);
                    }
                } else {
                    String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                    if (typeParameterSigs.length > 0) {
                        fBuffer.append(' ');
                        appendTypeParameterSignaturesLabel(typeParameterSigs, flags);
                    }
                }
            } else if (method.exists()) {
                ITypeParameter[] typeParameters = method.getTypeParameters();
                if (typeParameters.length > 0) {
                    fBuffer.append(' ');
                    appendTypeParametersLabels(typeParameters, flags);
                }
            }
            if (getFlag(flags, JavaElementLabels.COLORIZE) && offset != fBuffer.length()) {
                //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            }
        }

        if (getFlag(flags, JavaElementLabels.M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.DECL_STRING);
            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, flags);
            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
                //               fBuffer.setStyle(offset, fBuffer.length() - offset, DECORATIONS_STYLE);
            }
        }

        // category
        if (getFlag(flags, JavaElementLabels.M_CATEGORY) && method.exists())
            appendCategoryLabel(method, flags);

        // post qualification
        if (getFlag(flags, JavaElementLabels.M_POST_QUALIFIED)) {
            int offset = fBuffer.length();
            fBuffer.append(JavaElementLabels.CONCAT_STRING);
            appendTypeLabel(method.getDeclaringType(),
                    JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            if (getFlag(flags, JavaElementLabels.COLORIZE)) {
                //               fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
            }
        }

    } catch (JavaModelException e) {
        LOG.error(e.getMessage(), e); // NotExistsException will not reach this point
    }
}

From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java

License:Open Source License

private void generateType(IType type, StringBuilder builder, String indent) throws JavaModelException {
    int flags = 0;

    appendAnnotationLabels(type.getAnnotations(), flags, builder, indent.substring(TAB.length()));
    builder.append(indent.substring(TAB.length()));
    builder.append(getModifiers(type.getFlags(), type.getFlags())).append(' ').append(getJavaType(type))
            .append(' ').append(type.getElementName());

    if (type.isResolved()) {
        BindingKey key = new BindingKey(type.getKey());
        if (key.isParameterizedType()) {
            String[] typeArguments = key.getTypeArguments();
            appendTypeArgumentSignaturesLabel(type, typeArguments, flags, builder);
        } else {//w  w w .j  av  a 2 s .  c o m
            String[] typeParameters = Signature.getTypeParameters(key.toSignature());
            appendTypeParameterSignaturesLabel(typeParameters, builder);
        }
    } else {
        appendTypeParametersLabels(type.getTypeParameters(), flags, builder);
    }

    if (!"java.lang.Object".equals(type.getSuperclassName())
            && !"java.lang.Enum".equals(type.getSuperclassName())) {

        builder.append(" extends ");
        if (type.getSuperclassTypeSignature() != null) {
            //                appendTypeSignatureLabel(type, type.getSuperclassTypeSignature(), flags, builder);
            builder.append(Signature.toString(type.getSuperclassTypeSignature()));
        } else {
            builder.append(type.getSuperclassName());
        }
    }
    if (!type.isAnnotation()) {
        if (type.getSuperInterfaceNames().length != 0) {
            builder.append(" implements ");
            String[] signatures = type.getSuperInterfaceTypeSignatures();
            if (signatures.length == 0) {
                signatures = type.getSuperInterfaceNames();
            }
            for (String interfaceFqn : signatures) {
                builder.append(Signature.toString(interfaceFqn)).append(", ");
            }
            builder.delete(builder.length() - 2, builder.length());
        }
    }
    builder.append(" {\n");

    List<IField> fields = new ArrayList<>();
    if (type.isEnum()) {
        builder.append(indent);
        for (IField field : type.getFields()) {
            if (field.isEnumConstant()) {
                builder.append(field.getElementName()).append(", ");
            } else {
                fields.add(field);
            }
        }
        if (", ".equals(builder.substring(builder.length() - 2))) {
            builder.delete(builder.length() - 2, builder.length());
        }
        builder.append(";\n");

    } else {
        fields.addAll(Arrays.asList(type.getFields()));
    }

    for (IField field : fields) {
        if (Flags.isSynthetic(field.getFlags())) {
            continue;
        }
        appendAnnotationLabels(field.getAnnotations(), flags, builder, indent);
        builder.append(indent).append(getModifiers(field.getFlags(), type.getFlags()));
        if (builder.charAt(builder.length() - 1) != ' ') {
            builder.append(' ');
        }

        builder.append(Signature.toCharArray(field.getTypeSignature().toCharArray())).append(' ')
                .append(field.getElementName());
        if (field.getConstant() != null) {
            builder.append(" = ");
            if (field.getConstant() instanceof String) {
                builder.append('"').append(field.getConstant()).append('"');
            } else {
                builder.append(field.getConstant());
            }
        }
        builder.append(";\n");
    }
    builder.append('\n');

    for (IMethod method : type.getMethods()) {
        if (method.getElementName().equals("<clinit>") || Flags.isSynthetic(method.getFlags())) {
            continue;
        }
        appendAnnotationLabels(method.getAnnotations(), flags, builder, indent);
        BindingKey resolvedKey = method.isResolved() ? new BindingKey(method.getKey()) : null;
        String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null;
        builder.append(indent).append(getModifiers(method.getFlags(), type.getFlags()));

        if (builder.charAt(builder.length() - 1) != ' ') {
            builder.append(' ');
        }
        if (resolvedKey != null) {
            if (resolvedKey.isParameterizedMethod()) {
                String[] typeArgRefs = resolvedKey.getTypeArguments();
                if (typeArgRefs.length > 0) {
                    appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags, builder);
                    builder.append(' ');
                }
            } else {
                String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig);
                if (typeParameterSigs.length > 0) {
                    appendTypeParameterSignaturesLabel(typeParameterSigs, builder);
                    builder.append(' ');
                }
            }
        } else if (method.exists()) {
            ITypeParameter[] typeParameters = method.getTypeParameters();
            if (typeParameters.length > 0) {
                appendTypeParametersLabels(typeParameters, flags, builder);
                builder.append(' ');
            }
        }

        if (!method.isConstructor()) {

            String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig)
                    : method.getReturnType();
            appendTypeSignatureLabel(method, returnTypeSig, 0, builder);
            builder.append(' ');
            //                builder.append(Signature.toCharArray(method.getReturnType().toCharArray())).append(' ');
        }
        builder.append(method.getElementName());
        builder.append('(');
        for (ILocalVariable variable : method.getParameters()) {
            builder.append(Signature.toString(variable.getTypeSignature()));
            builder.append(' ').append(variable.getElementName()).append(", ");

        }

        if (builder.charAt(builder.length() - 1) == ' ') {
            builder.delete(builder.length() - 2, builder.length());
        }
        builder.append(')');
        String[] exceptionTypes = method.getExceptionTypes();
        if (exceptionTypes != null && exceptionTypes.length != 0) {
            builder.append(' ').append("throws ");
            for (String exceptionType : exceptionTypes) {
                builder.append(Signature.toCharArray(exceptionType.toCharArray())).append(", ");
            }
            builder.delete(builder.length() - 2, builder.length());
        }
        if (type.isInterface() || type.isAnnotation()) {
            builder.append(";\n\n");
        } else {
            builder.append(" {").append(METHOD_BODY).append("}\n\n");
        }
    }
    for (IType iType : type.getTypes()) {
        generateType(iType, builder, indent + indent);
    }
    builder.append(indent.substring(TAB.length()));
    builder.append("}\n");
}

From source file:com.github.rotty3000.baseline.linter.builder.DiffMarker.java

License:Open Source License

public void doMethod(IFile file, Diff diff, Diff parentDiff, Info info) throws Exception {

    if ((parentDiff.getDelta() == Delta.ADDED) || (diff.getDelta() != Delta.ADDED)) {

        return;/*  w w w .  j  av  a  2 s. com*/
    }

    IType type = javaProject.findType(parentDiff.getName());

    String methodName = diff.getName();
    String[] parts = methodName.substring(0, methodName.length() - 1).split("\\(", 2);
    String[] args = parts[1].split(",");

    if ((args.length == 1) && (args[0].length() == 0)) {
        args = new String[0];
    }

    IMethod method = type.getMethod(parts[0], args);

    if (!method.exists()) {
        return;
    }

    ISourceRange nameRange = method.getNameRange();
    int lineNumber = getLineNumber(type, nameRange.getOffset());

    IResource resource = type.getResource();

    addRangeMarker(
            (IFile) resource, "Method " + diff.getDelta().toString().toLowerCase()
                    + "! Change package version to " + info.suggestedVersion,
            nameRange, lineNumber, IMarker.SEVERITY_ERROR);
}