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

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

Introduction

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

Prototype

int METHOD

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

Click Source Link

Document

Constant representing a method or constructor.

Usage

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Executes the search./*from   w ww  .  jav a  2  s .c om*/
 *
 * @param commandLine The command line for the search.
 * @return The search results.
 */
public List<SearchMatch> executeSearch(CommandLine commandLine) throws Exception {
    int context = -1;
    if (commandLine.hasOption(Options.CONTEXT_OPTION)) {
        context = getContext(commandLine.getValue(Options.CONTEXT_OPTION));
    }
    String project = commandLine.getValue(Options.NAME_OPTION);
    String scope = commandLine.getValue(Options.SCOPE_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String offset = commandLine.getValue(Options.OFFSET_OPTION);
    String length = commandLine.getValue(Options.LENGTH_OPTION);
    String pat = commandLine.getValue(Options.PATTERN_OPTION);

    SearchPattern pattern = null;
    IJavaProject javaProject = project != null ? JavaUtils.getJavaProject(project) : null;

    SearchRequestor requestor = new SearchRequestor();

    // element search
    if (file != null && offset != null && length != null) {
        int charOffset = getOffset(commandLine);
        IJavaElement element = getElement(javaProject, file, charOffset, Integer.parseInt(length));
        if (element != null) {
            // user requested a contextual search.
            if (context == -1) {
                context = getElementContextualContext(element);

                // jdt search doesn't support implementors for method searches, so
                // switch to declarations.
            } else if (context == IJavaSearchConstants.IMPLEMENTORS
                    && element.getElementType() == IJavaElement.METHOD) {
                context = IJavaSearchConstants.DECLARATIONS;
                requestor = new ImplementorsSearchRequestor();
            }
            pattern = SearchPattern.createPattern(element, context);
        }

        // pattern search
    } else if (pat != null) {
        if (context == -1) {
            context = IJavaSearchConstants.DECLARATIONS;
        }

        int matchType = SearchPattern.R_EXACT_MATCH;

        // wild card character supplied, use pattern matching.
        if (pat.indexOf('*') != -1 || pat.indexOf('?') != -1) {
            matchType = SearchPattern.R_PATTERN_MATCH;

            // all upper case, add camel case support.
        } else if (pat.equals(pat.toUpperCase())) {
            matchType |= SearchPattern.R_CAMELCASE_MATCH;
        }

        boolean caseSensitive = !commandLine.hasOption(Options.CASE_INSENSITIVE_OPTION);
        if (caseSensitive) {
            matchType |= SearchPattern.R_CASE_SENSITIVE;
        }

        int type = getType(commandLine.getValue(Options.TYPE_OPTION));

        // jdt search doesn't support implementors for method searches, so switch
        // to declarations.
        if (type == IJavaSearchConstants.METHOD && context == IJavaSearchConstants.IMPLEMENTORS) {
            context = IJavaSearchConstants.DECLARATIONS;
            requestor = new ImplementorsSearchRequestor();
        }

        // hack for inner classes
        Matcher matcher = INNER_CLASS.matcher(pat);
        if (matcher.matches()) {
            // pattern search doesn't support org.test.Type$Inner or
            // org.test.Type.Inner, so convert it to org.test.*Inner, then filter
            // the results.
            pattern = SearchPattern.createPattern(matcher.replaceFirst("$1*$3"), type, context, matchType);
            Pattern toMatch = Pattern.compile(pat.replace(".", "\\.").replace("$", "\\$").replace("(", "\\(")
                    .replace(")", "\\)").replace("*", ".*").replace("?", "."));
            List<SearchMatch> matches = search(pattern, getScope(scope, javaProject));
            Iterator<SearchMatch> iterator = matches.iterator();
            while (iterator.hasNext()) {
                SearchMatch match = iterator.next();
                String name = JavaUtils.getFullyQualifiedName((IJavaElement) match.getElement()).replace("#",
                        ".");
                if (!toMatch.matcher(name).matches()) {
                    iterator.remove();
                }
            }
            return matches;
        }

        pattern = SearchPattern.createPattern(pat, type, context, matchType);

        // bad search request
    } else {
        throw new IllegalArgumentException(Services.getMessage("java_search.indeterminate"));
    }

    List<SearchMatch> matches = search(pattern, getScope(scope, javaProject), requestor);
    return matches;
}

From source file:org.eclim.plugin.jdt.command.src.JavaCommand.java

License:Open Source License

private String findMainClass(IJavaProject javaProject) throws Exception {
    final String projectPath = ProjectUtils.getPath(javaProject.getProject());
    final ArrayList<IMethod> methods = new ArrayList<IMethod>();
    int context = IJavaSearchConstants.DECLARATIONS;
    int type = IJavaSearchConstants.METHOD;
    int matchType = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    SearchPattern pattern = SearchPattern.createPattern("main(String[])", type, context, matchType);
    SearchRequestor requestor = new SearchRequestor() {
        public void acceptSearchMatch(SearchMatch match) {
            if (match.getAccuracy() != SearchMatch.A_ACCURATE) {
                return;
            }/*w  w w.  j  a  va 2 s. co  m*/

            IPath location = match.getResource().getRawLocation();
            if (location == null) {
                return;
            }

            String path = location.toOSString().replace('\\', '/');
            if (!path.toLowerCase().startsWith(projectPath.toLowerCase())) {
                return;
            }

            IJavaElement element = (IJavaElement) match.getElement();
            if (element.getElementType() != IJavaElement.METHOD) {
                return;
            }

            IMethod method = (IMethod) element;
            String[] params = method.getParameterTypes();
            if (params.length != 1) {
                return;
            }
            methods.add(method);
        }
    };

    if (pattern != null) {
        SearchEngine engine = new SearchEngine();
        SearchParticipant[] participants = new SearchParticipant[] {
                SearchEngine.getDefaultSearchParticipant() };
        engine.search(pattern, participants, scope, requestor, null);

        // if we found only 1 result, we can use it.
        if (methods.size() == 1) {
            IMethod method = methods.get(0);
            ICompilationUnit cu = method.getCompilationUnit();
            IPackageDeclaration[] packages = cu.getPackageDeclarations();
            if (packages != null && packages.length > 0) {
                return packages[0].getElementName() + "." + cu.getElementName();
            }
            return cu.getElementName();
        }
    }
    return null;
}

From source file:org.eclim.plugin.jdt.util.ASTUtils.java

License:Open Source License

/**
 * Finds the node at the specified offset that matches up with the supplied
 * IJavaElement./*from w w  w . j  av  a2 s .c  o  m*/
 *
 * @param cu The CompilationUnit.
 * @param offset The node offset in the compilation unit.
 * @param element The IJavaElement to match.
 * @return The node at the specified offset.
 */
public static ASTNode findNode(CompilationUnit cu, int offset, IJavaElement element) throws Exception {
    ASTNode node = findNode(cu, offset);
    if (node == null) {
        return null;
    }

    if (element.getElementType() == IJavaElement.TYPE_PARAMETER) {
        element = element.getParent();
    }

    switch (element.getElementType()) {
    case IJavaElement.PACKAGE_DECLARATION:
        node = resolveNode(node, PackageDeclaration.class);
        break;
    case IJavaElement.IMPORT_DECLARATION:
        node = resolveNode(node, ImportDeclaration.class);
        break;
    case IJavaElement.TYPE:
        node = resolveNode(node, AbstractTypeDeclaration.class);
        break;
    case IJavaElement.INITIALIZER:
        node = resolveNode(node, Initializer.class);
        break;
    case IJavaElement.FIELD:
        node = resolveNode(node, FieldDeclaration.class);
        break;
    case IJavaElement.METHOD:
        node = resolveNode(node, MethodDeclaration.class);
        break;
    default:
        logger.info("findNode(CompilationUnit,int,IJavaElement) - " + "unrecognized element type "
                + element.getElementType());
    }
    return node;
}

From source file:org.eclim.plugin.jdt.util.JavaUtils.java

License:Open Source License

/**
 * Gets the fully qualified name of the supplied java element.
 * <p/>/* w w w . j a  v a 2  s.  c  o m*/
 * NOTE: For easy of determining fields and method segments, they are appended
 * with a javadoc style '#' instead of the normal '.'.
 *
 * @param element The IJavaElement.
 *
 * @return The fully qualified name.
 */
public static String getFullyQualifiedName(IJavaElement element) {
    IJavaElement parent = element;
    while (parent.getElementType() != IJavaElement.COMPILATION_UNIT
            && parent.getElementType() != IJavaElement.CLASS_FILE) {
        parent = parent.getParent();
    }

    StringBuffer elementName = new StringBuffer().append(parent.getParent().getElementName()).append('.')
            .append(FileUtils.getFileName(parent.getElementName()));

    switch (element.getElementType()) {
    case IJavaElement.FIELD:
        IField field = (IField) element;
        elementName.append('#').append(field.getElementName());
        break;
    case IJavaElement.METHOD:
        IMethod method = (IMethod) element;
        elementName.append('#').append(method.getElementName()).append('(');
        String[] parameters = method.getParameterTypes();
        for (int ii = 0; ii < parameters.length; ii++) {
            if (ii != 0) {
                elementName.append(", ");
            }
            elementName.append(Signature.toString(parameters[ii]).replace('/', '.'));
        }
        elementName.append(')');
        break;
    }

    return elementName.toString();
}

From source file:org.eclipse.acceleo.internal.ide.ui.launching.AcceleoApplicationLaunchShortcut.java

License:Open Source License

/**
 * Returns the smallest enclosing <code>IType</code> if the specified object is a main method, or
 * <code>null</code>./*from w ww.j ava2s.c o  m*/
 * 
 * @param o
 *            the object to inspect
 * @return the smallest enclosing <code>IType</code> of the specified object if it is a main method or
 *         <code>null</code> if it is not
 */
private IType isMainMethod(Object o) {
    if (o instanceof IAdaptable) {
        IAdaptable adapt = (IAdaptable) o;
        IJavaElement element = (IJavaElement) adapt.getAdapter(IJavaElement.class);
        if (element != null && element.getElementType() == IJavaElement.METHOD) {
            try {
                IMethod method = (IMethod) element;
                if (method.isMainMethod()) {
                    return method.getDeclaringType();
                }
            } catch (JavaModelException e) {
                AcceleoUIActivator.getDefault().getLog().log(e.getStatus());
            }
        }
    }
    return null;
}

From source file:org.eclipse.ajdt.core.javaelements.ITDAwareSourceTypeInfo.java

License:Open Source License

private List<IJavaElement> getITDs(SourceType type) throws JavaModelException {
    AJProjectModelFacade model = AJProjectModelFactory.getInstance().getModelForJavaElement(type);
    if (model.hasModel()) {
        List<IJavaElement> itds = new ArrayList<IJavaElement>();
        List<IJavaElement> rels = model.getRelationshipsForElement(type,
                AJRelationshipManager.ASPECT_DECLARATIONS);

        List<IMethod> childMethods = null;

        for (IJavaElement ije : rels) {
            if (ije instanceof IntertypeElement) {
                IntertypeElement elt = (IntertypeElement) ije;
                IMember member = elt.createMockDeclaration(type);
                // null if the ITD doesn't exist in the AspectJ hierarchy
                // will happen if the Java side has partial compilation 
                // and aspectj side does not
                if (member != null) {

                    // should not add this ITD if it is a duplicate
                    // of another ITD
                    if (!isAlreadyAnITD(itds, member)) {
                        continue;
                    }//  ww  w  .  j  a  va  2 s.c om

                    itds.add(member);

                    // additional processing for interfaces
                    if (handle.isInterface()) {

                        if (member.getElementType() == IJavaElement.FIELD) {
                            // Bug 262969
                            // Interfaces can't have fields, so ignore
                            // Reconciling errors occur if an ITD field is
                            // referenced outside of the aspect that declares them, 
                            // but only if the declared type of the object is an interface.
                            itds.remove(member);
                        } else if (member.getElementType() == IJavaElement.METHOD) {
                            // now look to see if this ITD a method that provides
                            // a default implementation for an interface method
                            // use IMethod.isSimilar
                            if (childMethods == null) {
                                childMethods = (List<IMethod>) type.getChildrenOfType(IJavaElement.METHOD);
                            }
                            for (IMethod method : childMethods) {
                                if (method.isSimilar((IMethod) member)) {
                                    itds.remove(member);
                                    break;
                                }
                            }
                        }
                    }
                }
            } else if (ije instanceof DeclareElement) {
                DeclareElement elt = (DeclareElement) ije;

                // use createElementInfo, not getElementInfo because 
                // we don't want it cached
                DeclareElementInfo info = (DeclareElementInfo) elt.createElementInfo();
                if (info == null || info.getAJKind() != Kind.DECLARE_PARENTS) {
                    continue;
                }

                char[][] newSupers = info.getTypes();
                augmentHierarchy(newSupers);
            } else if (ije instanceof AspectElement || ije instanceof BinaryAspectElement) {
                // likely a declare parents instantiated in a concrete aspect, but declared in a super aspect
                IProgramElement ipe = model.javaElementToProgramElement(ije);
                Map<String, List<String>> declareParentsMap = ipe.getDeclareParentsMap();
                if (declareParentsMap != null) {
                    augmentHierarchy(declareParentsMap.get(type.getFullyQualifiedName()));
                }
            } else if (ije instanceof IType) {
                // an ITIT
                itds.add(new ITIT(type, (IType) ije, model.javaElementToProgramElement(ije)));
            }
        }
        return itds;
    }
    return new LinkedList<IJavaElement>();
}

From source file:org.eclipse.ajdt.core.javaelements.ITDAwareSourceTypeInfo.java

License:Open Source License

private boolean isAlreadyAnITD(List<IJavaElement> itds, IMember member) {
    boolean shouldAdd = true;

    if (member.getElementType() == IJavaElement.FIELD) {
        for (IJavaElement itdElt : itds) {
            if (itdElt instanceof IField) {
                IField itdField = (IField) itdElt;
                if (member.getElementName().equals(itdField.getElementName())) {
                    // may not be same type, but we want to avoid conflicts, so remove
                    shouldAdd = false;//from  w  w w .  j av  a2s . c om
                    break;
                }
            }
        }
    } else if (member.getElementType() == IJavaElement.METHOD) {
        for (IJavaElement itdElt : itds) {
            if (itdElt instanceof IMethod) {
                IMethod itdMethod = (IMethod) itdElt;
                if (itdMethod.isSimilar((IMethod) member)) {
                    shouldAdd = false;
                    break;
                }
            }
        }
    }
    return shouldAdd;
}

From source file:org.eclipse.ajdt.core.model.AJModelChecker.java

License:Open Source License

private static List<String> itdsNotOnType(IRelationship rel, AJProjectModelFacade model) {
    List<String> problems = new ArrayList<String>();
    if (rel.getKind() == IRelationship.Kind.DECLARE_INTER_TYPE) {

        IJavaElement elt = model.programElementToJavaElement(rel.getSourceHandle());
        if (!elt.exists()) {
            problems.add("Java Element does not exist: " + rel.getSourceHandle()
                    + "\n\tIt is the source relationship of " + toRelString(rel)
                    + "\n\tThis may not actually be a problem if compiling broken code.");
        }//from   w ww .  j  a va2  s. c o m
        if (elt != AJProjectModelFacade.ERROR_JAVA_ELEMENT
                && (elt.getElementType() == IJavaElement.FIELD || elt.getElementType() == IJavaElement.METHOD
                        || elt.getElementType() == IJavaElement.LOCAL_VARIABLE
                        || elt.getElementType() == IJavaElement.INITIALIZER
                        || elt.getElementType() == IJavaElement.COMPILATION_UNIT
                        || elt.getElementType() == IJavaElement.CLASS_FILE)
                && !(elt instanceof IntertypeElement || elt instanceof DeclareElement)) {
            problems.add(
                    "Java Element is wrong type (ITD relationships should only contain types and intertype elements): "
                            + rel.getSourceHandle() + "\n\tIt is the source relationship of "
                            + toRelString(rel));
        }

        for (Iterator<String> targetIter = rel.getTargets().iterator(); targetIter.hasNext();) {
            String target = targetIter.next();
            elt = model.programElementToJavaElement(target);
            if (!elt.exists()) {
                problems.add("Java Element does not exist: " + target + "\n\tIt is the source relationship of "
                        + toRelString(rel)
                        + "\n\tThis may not actually be a problem if compiling broken code.");
            }
            if (elt != AJProjectModelFacade.ERROR_JAVA_ELEMENT
                    && (elt.getElementType() == IJavaElement.FIELD
                            || elt.getElementType() == IJavaElement.METHOD
                            || elt.getElementType() == IJavaElement.LOCAL_VARIABLE
                            || elt.getElementType() == IJavaElement.INITIALIZER
                            || elt.getElementType() == IJavaElement.COMPILATION_UNIT
                            || elt.getElementType() == IJavaElement.CLASS_FILE)
                    && !(elt instanceof IntertypeElement || elt instanceof DeclareElement)) {
                problems.add(
                        "Java Element is wrong type (ITD relationships should only contain types and intertype elements): "
                                + target + "\n\tIt is the source relationship of " + toRelString(rel));
            }
        }

    }
    return problems;
}

From source file:org.eclipse.ajdt.core.parserbridge.ITDInserter.java

License:Open Source License

private IType getHandleFromChild(String typeName, IParent parent) throws JavaModelException {
    IJavaElement[] children = parent.getChildren();
    for (int i = 0; i < children.length; i++) {
        if ((children[i].getElementType() == IJavaElement.TYPE)
                && typeName.equals(children[i].getElementName())) {
            return (IType) children[i];
        }//from  w  w w.  j  av a  2s  .c o m
    }
    for (int i = 0; i < children.length; i++) {
        if (children[i].getElementType() == IJavaElement.TYPE
                || children[i].getElementType() == IJavaElement.METHOD) {
            IType type = getHandleFromChild(typeName, (IParent) children[i]);
            if (type != null) {
                return type;
            }
        }
    }
    return null;
}

From source file:org.eclipse.ajdt.internal.ui.lazystart.ImageDecorator.java

License:Open Source License

private int computeJavaAdornmentFlags(IJavaElement element) {
    int flags = 0;
    if (true && element instanceof IMember) {
        try {/*from  w w  w. j  a v a  2s.  c  o m*/
            IMember member = (IMember) element;

            if (element.getElementType() == IJavaElement.METHOD && ((IMethod) element).isConstructor())
                flags |= JavaElementImageDescriptor.CONSTRUCTOR;

            int modifiers = member.getFlags();
            if (Flags.isAbstract(modifiers) && confirmAbstract(member))
                flags |= JavaElementImageDescriptor.ABSTRACT;
            if (Flags.isFinal(modifiers) || isInterfaceField(member))
                flags |= JavaElementImageDescriptor.FINAL;
            if (Flags.isSynchronized(modifiers) && confirmSynchronized(member))
                flags |= JavaElementImageDescriptor.SYNCHRONIZED;
            if (Flags.isStatic(modifiers) || isInterfaceField(member))
                flags |= JavaElementImageDescriptor.STATIC;

            if (Flags.isDeprecated(modifiers))
                flags |= JavaElementImageDescriptor.DEPRECATED;

            if (member.getElementType() == IJavaElement.TYPE) {
                if (JavaModelUtil.hasMainMethod((IType) member)) {
                    flags |= JavaElementImageDescriptor.RUNNABLE;
                }
            }
        } catch (JavaModelException e) {
            // do nothing. Can't compute runnable adornment or get flags
            // can be ignored
        }
    }
    return flags;
}