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.codehaus.groovy.eclipse.codebrowsing.requestor.CodeSelectRequestor.java

License:Apache License

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

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

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

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

License:Apache License

private IField findSyntheticProperty(IJavaElement element) throws JavaModelException {
    if (element.getElementType() != IJavaElement.METHOD) {
        return null;
    }/*from w w w.  j a v a2s  .  c  om*/
    String name = element.getElementName();
    if (name.length() <= 2) {
        return null;
    }
    int prefixLength;
    if (name.startsWith("is")) {
        prefixLength = 2;
    } else {
        if (name.length() == 3) {
            return null;
        }
        prefixLength = 3;
    }

    String fieldName = "" + Character.toLowerCase(name.charAt(prefixLength)) + name.substring(prefixLength + 1);
    IType parent = (IType) element.getParent();
    IField field = parent.getField(fieldName);
    // only return if field doesn't exist since otherwise, this method would
    // not be synthetic
    return field.exists() && Flags.isProtected(field.getFlags()) ? null : field;
}

From source file:org.codehaus.groovy.eclipse.editor.outline.GroovyScriptOutlineExtender.java

License:Apache License

/**
 * @param scriptElt/* w w w  . ja v a2 s .  c o m*/
 * @return
 */
private boolean isConstructor(IJavaElement scriptElt) throws JavaModelException {
    if (scriptElt.getElementType() != IJavaElement.METHOD) {
        return false;
    }
    return ((IMethod) scriptElt).isConstructor();
}

From source file:org.codehaus.groovy.eclipse.editor.outline.GroovyScriptOutlineExtender.java

License:Apache License

private boolean isMainMethod(IJavaElement scriptElt) throws JavaModelException {
    if (scriptElt.getElementType() != IJavaElement.METHOD) {
        return false;
    }//w  w w .jav  a  2 s  .com
    return ((IMethod) scriptElt).isMainMethod();
}

From source file:org.codehaus.groovy.eclipse.editor.outline.GroovyScriptOutlineExtender.java

License:Apache License

private boolean isRunMethod(IJavaElement scriptElt) {
    if (scriptElt.getElementType() != IJavaElement.METHOD) {
        return false;
    }//w w w  . ja va2  s  . c om
    if (!scriptElt.getElementName().equals("run")) {
        return false;
    }
    String[] parammeterTypes = ((IMethod) scriptElt).getParameterTypes();
    return parammeterTypes == null || parammeterTypes.length == 0;
}

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

License:Apache License

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

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

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

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

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

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

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

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

License:Open Source License

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

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

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

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

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

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

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

License:Open Source License

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

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

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

        if (element == null) {
            continue;
        }/* w w  w  .j ava2 s .c  om*/

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

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

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

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

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

From source file:org.eclim.plugin.jdt.command.junit.JUnitCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String testName = commandLine.getValue(Options.TEST_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int offset = getOffset(commandLine);
    boolean debug = commandLine.hasOption(Options.DEBUG_OPTION);
    boolean halt = commandLine.hasOption(Options.HALT_OPTION);

    IProject project = ProjectUtils.getProject(projectName);
    project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, null);

    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    JUnitTask junit = createJUnitTask(javaProject, debug, halt);

    String[] vmargs = getPreferences().getArrayValue(project, "org.eclim.java.junit.jvmargs");
    for (String vmarg : vmargs) {
        if (!vmarg.startsWith("-")) {
            continue;
        }//from  ww  w. ja  va 2  s. co  m
        Argument a = junit.createJvmarg();
        a.setValue(vmarg);
    }

    String[] props = getPreferences().getArrayValue(project, "org.eclim.java.junit.sysprops");
    for (String prop : props) {
        String[] sysprop = StringUtils.split(prop, "=", 2);
        if (sysprop.length != 2) {
            continue;
        }
        if (sysprop[0].startsWith("-D")) {
            sysprop[0] = sysprop[0].substring(2);
        }
        Variable var = new Variable();
        var.setKey(sysprop[0]);
        var.setValue(sysprop[1]);
        junit.addConfiguredSysproperty(var);
    }

    String[] envs = getPreferences().getArrayValue(project, "org.eclim.java.junit.envvars");
    for (String env : envs) {
        String[] envvar = StringUtils.split(env, "=", 2);
        if (envvar.length != 2) {
            continue;
        }
        Variable var = new Variable();
        var.setKey(envvar[0]);
        var.setValue(envvar[1]);
        junit.addEnv(var);
    }

    if (file != null) {
        ICompilationUnit src = JavaUtils.getCompilationUnit(javaProject, file);
        IMethod method = null;
        if (offset != -1) {
            IJavaElement element = src.getElementAt(offset);
            if (element != null && element.getElementType() == IJavaElement.METHOD) {
                method = (IMethod) element;
            }
        }

        JUnit4TestFinder finder = new JUnit4TestFinder();
        IType type = src.getTypes()[0];
        if (!finder.isTest(type)) {
            src = JUnitUtils.findTest(javaProject, type);
            if (src == null) {
                println(Services.getMessage("junit.testing.test.not.found"));
                return null;
            }

            if (method != null) {
                method = JUnitUtils.findTestMethod(src, method);
                if (method == null) {
                    println(Services.getMessage("junit.testing.test.method.not.found"));
                    return null;
                }
            }
        }

        JUnitTest test = new JUnitTest();
        test.setName(JavaUtils.getFullyQualifiedName(src));
        if (method != null) {
            IAnnotation testAnnotation = method.getAnnotation("Test");
            if (testAnnotation == null || !testAnnotation.exists()) {
                println(Services.getMessage("junit.testing.test.method.not.annotated",
                        method.getElementName()));
                return null;
            }
            test.setMethods(method.getElementName());
        }
        junit.addTest(test);

    } else if (testName != null) {
        if (testName.indexOf('*') != -1) {
            createBatchTest(javaProject, junit, testName);
        } else {
            JUnitTest test = new JUnitTest();
            test.setName(testName);
            junit.addTest(test);
        }

    } else {
        ArrayList<String> names = new ArrayList<String>();
        IType[] types = JUnitCore.findTestTypes(javaProject, null);
        for (IType type : types) {
            names.add(type.getFullyQualifiedName());
        }
        Collections.sort(names);

        for (String name : names) {
            JUnitTest test = new JUnitTest();
            test.setName(name);
            junit.addTest(test);
        }
    }

    try {
        junit.init();
        junit.execute();
    } catch (BuildException be) {
        if (debug) {
            be.printStackTrace(getContext().err);
        }
    }

    return null;
}

From source file:org.eclim.plugin.jdt.command.junit.JUnitFindTestCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    int offset = getOffset(commandLine);

    IProject project = ProjectUtils.getProject(projectName);
    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    JUnit4TestFinder finder = new JUnit4TestFinder();

    ICompilationUnit src = JavaUtils.getCompilationUnit(javaProject, file);
    ICompilationUnit result = null;//from ww w.  j a  va 2  s  .c  om
    if (finder.isTest(src.getTypes()[0])) {
        result = JUnitUtils.findClass(javaProject, src.getTypes()[0]);
        if (result == null) {
            return Services.getMessage("junit.testing.class.not.found");
        }
    } else {
        result = JUnitUtils.findTest(javaProject, src.getTypes()[0]);
        if (result == null) {
            return Services.getMessage("junit.testing.test.not.found");
        }
    }

    IType resultType = result.getTypes()[0];
    String name = resultType.getElementName();
    ISourceReference ref = resultType;
    ISourceRange docRange = resultType.getJavadocRange();

    IJavaElement element = src.getElementAt(offset);
    if (element != null && element.getElementType() == IJavaElement.METHOD) {
        IMethod method = null;
        if (finder.isTest(src.getTypes()[0])) {
            method = JUnitUtils.findClassMethod(result, (IMethod) element);
        } else {
            method = JUnitUtils.findTestMethod(result, (IMethod) element);
        }
        if (method != null) {
            name = method.getElementName();
            ref = method;
            docRange = method.getJavadocRange();
        }
    }

    String lineDelim = result.findRecommendedLineSeparator();
    int docLength = docRange != null ? docRange.getLength() + lineDelim.length() : 0;
    return Position.fromOffset(result.getResource().getLocation().toOSString(), name,
            ref.getSourceRange().getOffset() + docLength, 0);
}