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

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

Introduction

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

Prototype

IMethod getMethod(String name, String[] parameterTypeSignatures);

Source Link

Document

Returns the method with the specified name and parameter types in this type (for example, "foo", {"I", "QString;"}).

Usage

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 v  a 2  s.  c om*/
                }
                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:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

/**
 * @param scope//from ww  w  .  j  a v  a2  s .com
 * @param monitor
 * @param classSignature
 * @param methodName
 * @param signature
 * @return
 * @throws CoreException
 * @throws InterruptedException
 */
public static IJavaElement searchForMethod(IJavaSearchScope scope, IProgressMonitor monitor,
        String classSignature, String methodName, String signature) throws CoreException, InterruptedException {

    SubProgressMonitor typeMonitor = new SubProgressMonitor(monitor, 100);
    SubProgressMonitor hierarchyMonitor = new SubProgressMonitor(monitor, 100);
    IType foundType = (IType) searchForType(classSignature, scope, typeMonitor);
    if (foundType == null)
        return null;
    boolean isConstructor = false;
    if (methodName.startsWith("<init")) {
        isConstructor = true;
        boolean i = isConstructor;
        boolean isAnonymous = false;
        if (!foundType.exists()) {
            //check anonymity using the dollar sign
            String elementName = foundType.getElementName();
            if (elementName.length() > 0 && Character.isDigit(elementName.charAt(0))) {
                isAnonymous = true;
            }
        } else {
            isAnonymous = foundType.isAnonymous();
        }
        if (isAnonymous) {
            methodName = "";
        } else {
            methodName = foundType.getElementName();
        }
    }
    String[] methodParamTypes = Signature.getParameterTypes(signature);
    IMethod searchMethod = foundType.getMethod(methodName, methodParamTypes);
    IMethod[] methods = foundType.getMethods();
    for (IMethod checkMethod : methods) {
        if (isSimilar(searchMethod, checkMethod)) {
            return checkMethod;
        }
    }
    return searchMethod;
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

/**
 * Searches the given thread for activations that match the given java method.
 * @param thread the thread to search.//from www  .j  a  v a 2 s .co  m
 * @param method the method to check.
 * @param monitor this is a long-running process, and should be done inside a monitor.
 * @return a list of found activations
 * @throws CoreException if an error occurred during retrieval of the activations
 */
public static List<IActivation> findActivationsForMethod(IThread thread, IMethod element,
        IProgressMonitor monitor) throws CoreException {
    DBProgramSketch sketch = (DBProgramSketch) SketchPlugin.getDefault().getSketch(thread);
    ArrayList<IActivation> activations = new ArrayList<IActivation>();
    if (sketch == null) {
        return activations;
    }
    Exception ex = null;
    monitor.beginTask("Searching for matching activations", IProgressMonitor.UNKNOWN);
    try {
        PreparedStatement methodStatement = sketch.getPortal().prepareStatement(METHOD_QUERY);
        IType methodType = element.getDeclaringType();
        String qualifiedName = methodType.getFullyQualifiedName();
        String methodName = element.getElementName();
        methodStatement.setString(1, qualifiedName);
        methodStatement.setString(2, methodName);
        methodStatement.setLong(3, ((ThreadImpl) thread).getModelID());
        ResultSet results = methodStatement.executeQuery();

        while (results.next()) {
            if (monitor.isCanceled())
                break;
            String signature = results.getString(1);
            //try to find a method that matches in the declaring type
            IMethod matchMethod = methodType.getMethod(methodName, Signature.getParameterTypes(signature));
            if (element.isSimilar(matchMethod)) {
                long model_id = results.getLong("model_id");
                IActivation a = ((ThreadImpl) thread).getByModelID(model_id);
                if (a != null) {
                    activations.add(a);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        ex = e;
    } catch (SQLException e) {
        ex = e;
    }
    monitor.done();
    if (ex != null) {
        throw new CoreException(SketchPlugin.getDefault().createStatus(ex));
    }
    return activations;
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

public static ITraceClassMethod findSimilarMethod(ITrace trace, IMethod method) {
    IType declaringType = method.getDeclaringType();
    IProgramSketch sketch = SketchPlugin.getDefault().getSketch(trace);
    if (sketch != null) {
        ITraceClass tc = findSimilarType(trace, declaringType);
        if (tc != null) {
            try {
                PreparedStatement statement = sketch.getPortal().prepareStatement(
                        "SELECT method_signature FROM Method WHERE type_name=? AND method_name=?");
                statement.setString(1, tc.getName());
                statement.setString(2, method.getElementName());
                ResultSet results = statement.executeQuery();
                while (results.next()) {
                    String signature = results.getString(1);
                    IMethod compareMethod = declaringType.getMethod(method.getElementName(),
                            Signature.getParameterTypes(signature));
                    if (method.isSimilar(compareMethod)) {
                        return tc.findMethod(method.getElementName(), signature);
                    }/*w ww .  j  a  v  a2 s.c om*/
                }
            } catch (IllegalArgumentException e) {
            } catch (SQLException e) {
            } catch (CoreException e) {
            }
        }
    }
    return null;
}

From source file:cn.ieclipse.adt.ext.jdt.SourceGenerator.java

License:Apache License

public static void merge(IType type, String authority, String dbName, List<String> tableCreators,
        List<String> tables) throws Exception {
    type.createField("public static final String AUTH=\"" + authority + "\";", null, true, null);
    type.createField("public static final Uri URI=Uri.parse(\"content://\" + AUTH);", null, true, null);

    type.createField("private SQLiteOpenHelper mOpenHelper;", null, true, null);

    type.createField("private static Session session;", null, true, null);

    type.createMethod("public static Session getSession(){" + "return session;" + "}", null, true, null);
    IMethod onCreate = type.getMethod("onCreate", null);
    // String doc = onCreate.getAttachedJavadoc(null);
    StringBuilder sb = new StringBuilder(onCreate.getSource());
    int start = sb.indexOf("{") + 1;
    int end = sb.indexOf("}");
    sb.delete(start, end);/*from   w w w.j  a  v a  2  s .co m*/

    StringBuilder sb2 = new StringBuilder();
    sb2.append("mOpenHelper=new SQLiteOpenHelper(this.getContext(),\"");
    sb2.append(dbName);
    sb2.append("\",null,1){");
    sb2.append("public void onCreate(SQLiteDatabase db){");
    //        sb2.append(" String sql=\"\";");
    //        for (String creator : tableCreators) {
    //            String[] lines = creator.split(SourceAnalysis.LF);
    //            for (int i = 0; i < lines.length; i++) {
    //                if (i == 0) {
    //                    sb2.append("sql=\"");
    //                } else {
    //                    sb2.append("sql+=\"");
    //                }
    //                sb2.append(lines[i]);
    //                sb2.append("\";");
    //            }
    //            sb2.append("db.execSQL(sql);");
    //        }
    for (String table : tables) {
        sb2.append(table);
    }
    sb2.append("}");
    sb2.append("public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){");
    sb2.append("");
    sb2.append("}};");
    sb2.append("session = new Session(mOpenHelper, getContext().getContentResolver());");
    sb2.append("return true;");
    sb.insert(start, sb2);

    onCreate.delete(true, null);
    type.createMethod(sb.toString(), null, true, null);

}

From source file:cn.ieclipse.aorm.eclipse.jdt.SourceGenerator.java

License:Apache License

public static void merge(IType type, String authority, String dbName, List<String> tableCreators)
        throws Exception {
    type.createField("public static final String AUTH=\"" + authority + "\";", null, true, null);
    type.createField("public static final Uri URI=Uri.parse(\"content://\" + AUTH);", null, true, null);

    type.createField("private SQLiteOpenHelper mOpenHelper;", null, true, null);

    type.createField("private static Session session;", null, true, null);

    type.createMethod("public static Session getSession(){" + "return session;" + "}", null, true, null);
    IMethod onCreate = type.getMethod("onCreate", null);
    // String doc = onCreate.getAttachedJavadoc(null);
    StringBuilder sb = new StringBuilder(onCreate.getSource());
    int start = sb.indexOf("{") + 1;
    int end = sb.indexOf("}");
    sb.delete(start, end);/* w  w  w  .j av a2s.  c  om*/

    StringBuilder sb2 = new StringBuilder();
    sb2.append("mOpenHelper=new SQLiteOpenHelper(this.getContext(),\"");
    sb2.append(dbName);
    sb2.append("\",null,1){");
    sb2.append("public void onCreate(SQLiteDatabase db){");
    sb2.append(" String sql=\"\";");
    for (String creator : tableCreators) {
        String[] lines = creator.split(SourceAnalysis.LF);
        for (int i = 0; i < lines.length; i++) {
            if (i == 0) {
                sb2.append("sql=\"");
            } else {
                sb2.append("sql+=\"");
            }
            sb2.append(lines[i]);
            sb2.append("\";");
        }
        sb2.append("db.execSQL(sql);");
    }
    sb2.append("}");
    sb2.append("public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){");
    sb2.append("");
    sb2.append("}};");
    sb2.append("session = new Session(mOpenHelper, getContext().getContentResolver());");
    sb2.append("return true;");
    sb.insert(start, sb2);

    onCreate.delete(true, null);
    type.createMethod(sb.toString(), null, true, null);

}

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;//  w w w . j ava2 s  . c  om
    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>//from ww w .j a v  a  2s .c o m
 * 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/>//from w  w w .j a va  2  s.c  om
 * 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   www .  j a va2s . c  o  m*/
 * 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;
}