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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.objectteams.otdt.tests.otmodel.CalloutMappingTest.java

License:Open Source License

public void testMapping4FromMemento() throws JavaModelException {
    IRoleType roleOTElem = getRoleOTElem();
    assertNotNull(roleOTElem);//  w ww .  j av  a2s  .com
    IMethodMapping[] calloutMethodMappings = roleOTElem.getMethodMappings(IRoleType.CALLOUTS);

    IMethodMapping mapping = calloutMethodMappings[3];
    assertNotNull(mapping);

    String token = mapping.getHandleIdentifier();

    SourceType sourceType = (SourceType) roleOTElem.getCorrespondingJavaElement();
    IJavaElement fromMemento = JavaCore.create(token, sourceType.getCompilationUnit().getOwner());

    assertEquals("Elements should be equal", mapping, fromMemento);

    assertTrue("Element should exist", fromMemento.exists());

    assertTrue("Expecting callout to field", fromMemento instanceof ICalloutToFieldMapping);
    ICalloutToFieldMapping mappingFromMemento = (ICalloutToFieldMapping) fromMemento;
    assertTrue("Mapping should have signature", mappingFromMemento.hasSignature());

    assertFalse("Expecting no setter", mappingFromMemento.getBaseFieldHandle().isSetter());
}

From source file:org.eclipse.objectteams.otdt.ui.tests.refactoring.reorg.PasteActionTest.java

License:Open Source License

public void test3() throws Exception {
    //      printTestDisabledMessage("test for bug#19007");
    ICompilationUnit cuA = createCUfromTestFile(getPackageP(), "A");
    ICompilationUnit cuB = createCUfromTestFile(getPackageP(), "B");

    try {//from  w  w w  . ja  v a  2  s .co  m
        IJavaElement elem0 = cuA.getImport("java.lang.*");
        IImportContainer importContainer = cuB.getImportContainer();

        assertTrue("y does not exist", elem0.exists());
        assertTrue("B does not exist", importContainer.exists());

        IJavaElement[] copyJavaElements = { elem0 };
        IResource[] copyResources = {};
        IJavaElement[] pasteJavaElements = { importContainer };
        IResource[] pasteResources = {};
        PasteAction paste = verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements);
        paste.run((IStructuredSelection) paste.getSelection());
        compareContents("A");
        compareContents("B");
    } finally {
        delete(cuA);
        delete(cuB);
    }
}

From source file:org.eclipse.objectteams.otdt.ui.tests.refactoring.reorg.PasteActionTest.java

License:Open Source License

public void test4() throws Exception {
    //      printTestDisabledMessage("test for bug 20151");
    ICompilationUnit cuA = createCUfromTestFile(getPackageP(), "A");
    try {// w w  w  . java2s .c o  m
        IJavaElement elem0 = cuA.getType("A").getMethod("f", new String[0]);
        IMethod method = cuA.getType("A").getMethod("f1", new String[0]);

        assertTrue("y does not exist", elem0.exists());
        assertTrue("B does not exist", method.exists());

        IJavaElement[] copyJavaElements = { elem0 };
        IResource[] copyResources = {};
        IJavaElement[] pasteJavaElements = { method };
        IResource[] pasteResources = {};
        PasteAction paste = verifyEnabled(copyResources, copyJavaElements, pasteResources, pasteJavaElements);
        paste.run((IStructuredSelection) paste.getSelection());
        compareContents("A");
    } finally {
        delete(cuA);
    }
}

From source file:org.eclipse.osee.framework.ui.skynet.FindInWorkspaceOperation.java

License:Open Source License

@Override
protected void doWork(final IProgressMonitor monitor) throws Exception {
    final Map<String, Artifact> guids = getGuidMap();
    monitor.beginTask("Searching Java Files", guids.size());
    findByName(guids, monitor);//from www.  ja v a2s  .  c om

    if (guids.isEmpty()) {
        return;
    }

    final NullProgressMonitor subMonitor = new NullProgressMonitor();

    SearchPattern searchPattern = SearchPattern.createPattern("ObjectId", IJavaSearchConstants.ANNOTATION_TYPE,
            IJavaSearchConstants.ANNOTATION_TYPE_REFERENCE, SearchPattern.R_PATTERN_MATCH);

    IJavaSearchScope workspaceScope = SearchEngine.createWorkspaceScope();
    SearchRequestor requestor = new SearchRequestor() {

        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            ICompilationUnit unit = null;
            IJavaElement jElement = JavaCore.create(match.getResource());
            if (jElement != null && jElement.exists()
                    && jElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
                unit = (ICompilationUnit) jElement;
            }

            String uuid = getGuid(unit.getSource());
            if (guids.containsKey(uuid)) {
                monitor.worked(1);
                collector.onResource(unit.getResource());
                guids.remove(uuid);
                if (guids.isEmpty()) {
                    subMonitor.setCanceled(true);
                }
            }
        }
    };

    SearchEngine engine = new SearchEngine();
    try {
        engine.search(searchPattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() },
                workspaceScope, requestor, subMonitor);
    } catch (OperationCanceledException ex) {
        //do nothings
    }

    for (Artifact artifact : guids.values()) {
        collector.onNotFound(artifact);
    }
}

From source file:org.eclipse.pde.api.tools.ui.internal.markers.UpdateSinceTagOperation.java

License:Open Source License

public void run(IProgressMonitor monitor) {
    if (monitor != null && monitor.isCanceled()) {
        return;/* w  ww  .  j a  v  a  2s. c  om*/
    }
    if (monitor != null) {
        monitor.beginTask(MarkerMessages.UpdateSinceTagOperation_title, 3);
    }
    // retrieve the AST node compilation unit
    try {
        Integer charStartAttribute = (Integer) this.fMarker.getAttribute(IMarker.CHAR_START);
        int intValue = charStartAttribute.intValue();
        IJavaElement javaElement = null;
        IJavaElement handleElement = null;
        if (intValue > 0) {
            IResource resource = this.fMarker.getResource();
            javaElement = JavaCore.create(resource);
        } else {
            // this is a case where the marker is reported against the
            // MANIFEST.MF file
            String handle = (String) fMarker.getAttribute(IApiMarkerConstants.MARKER_ATTR_HANDLE_ID);
            if (handle != null) {
                handleElement = JavaCore.create(handle);
            }
            if (handleElement != null && handleElement.exists()) {
                javaElement = handleElement.getAncestor(IJavaElement.COMPILATION_UNIT);
            }
        }
        if (javaElement != null && javaElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
            ICompilationUnit compilationUnit = (ICompilationUnit) javaElement;
            if (!compilationUnit.isWorkingCopy()) {
                // open an editor of the corresponding unit to "show" the
                // quickfix change
                JavaUI.openInEditor(compilationUnit);
            }
            ASTParser parser = ASTParser.newParser(AST.JLS8);
            parser.setSource(compilationUnit);
            if (intValue <= 0) {
                // try to use the name range of the corresponding element
                if (handleElement instanceof IMember) {
                    IMember member = (IMember) handleElement;
                    ISourceRange range = member.getNameRange();
                    if (range != null) {
                        intValue = range.getOffset();
                    } else {
                        range = member.getSourceRange();
                        if (range != null && range.getOffset() > 0) {
                            intValue = range.getOffset();
                        } else {
                            return;
                        }
                    }
                } else {
                    return;
                }
            }
            parser.setFocalPosition(intValue);
            parser.setResolveBindings(true);
            Map<String, String> options = compilationUnit.getJavaProject().getOptions(true);
            options.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.ENABLED);
            parser.setCompilerOptions(options);
            final CompilationUnit unit = (CompilationUnit) parser.createAST(new NullProgressMonitor());
            BodyDeclaration node = null;
            NodeFinder nodeFinder = new NodeFinder(intValue);
            unit.accept(nodeFinder);
            if (monitor != null) {
                monitor.worked(1);
            }
            node = nodeFinder.getNode();
            if (node != null) {
                unit.recordModifications();
                AST ast = unit.getAST();
                ASTRewrite rewrite = ASTRewrite.create(ast);
                if (IApiProblem.SINCE_TAG_MISSING == this.sinceTagType) {
                    Javadoc docnode = node.getJavadoc();
                    if (docnode == null) {
                        docnode = ast.newJavadoc();
                        // we do not want to create a new empty Javadoc node
                        // in
                        // the AST if there are no missing tags
                        rewrite.set(node, node.getJavadocProperty(), docnode, null);
                    } else {
                        List<TagElement> tags = docnode.tags();
                        boolean found = false;
                        loop: for (Iterator<TagElement> iterator = tags.iterator(); iterator.hasNext();) {
                            TagElement element = iterator.next();
                            String tagName = element.getTagName();
                            if (TagElement.TAG_SINCE.equals(tagName)) {
                                found = true;
                                break loop;
                            }
                        }
                        if (found) {
                            return;
                        }
                    }
                    ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY);
                    // check the existing tags list
                    TagElement newtag = ast.newTagElement();
                    newtag.setTagName(TagElement.TAG_SINCE);
                    TextElement textElement = ast.newTextElement();
                    textElement.setText(this.sinceTagVersion);
                    newtag.fragments().add(textElement);
                    lrewrite.insertLast(newtag, null);
                } else {
                    Javadoc docnode = node.getJavadoc();
                    List<TagElement> tags = docnode.tags();
                    TagElement sinceTag = null;
                    for (Iterator<TagElement> iterator = tags.iterator(); iterator.hasNext();) {
                        TagElement tagElement = iterator.next();
                        if (TagElement.TAG_SINCE.equals(tagElement.getTagName())) {
                            sinceTag = tagElement;
                            break;
                        }
                    }
                    if (sinceTag != null) {
                        List<TextElement> fragments = sinceTag.fragments();
                        if (fragments.size() >= 1) {
                            TextElement textElement = fragments.get(0);
                            StringBuffer buffer = new StringBuffer();
                            buffer.append(' ').append(this.sinceTagVersion);
                            rewrite.set(textElement, TextElement.TEXT_PROPERTY, String.valueOf(buffer), null);
                        } else {
                            ListRewrite lrewrite = rewrite.getListRewrite(docnode, Javadoc.TAGS_PROPERTY);
                            // check the existing tags list
                            TagElement newtag = ast.newTagElement();
                            newtag.setTagName(TagElement.TAG_SINCE);
                            TextElement textElement = ast.newTextElement();
                            textElement.setText(this.sinceTagVersion);
                            newtag.fragments().add(textElement);
                            lrewrite.replace(sinceTag, newtag, null);
                        }
                    }
                }
                try {
                    if (monitor != null) {
                        monitor.worked(1);
                    }
                    TextEdit edit = rewrite.rewriteAST();
                    compilationUnit.applyTextEdit(edit, monitor);
                    if (monitor != null) {
                        monitor.worked(1);
                    }
                } finally {
                    compilationUnit.reconcile(ICompilationUnit.NO_AST, false /*
                                                                             * don
                                                                             * 't
                                                                             * force
                                                                             * problem
                                                                             * detection
                                                                             */, null /*
                                                                                       * use
                                                                                       * primary
                                                                                       * owner
                                                                                       */, null /*
                                                                                                 * no
                                                                                                 * progress
                                                                                                 * monitor
                                                                                                 */);
                }
            }
        }
    } catch (CoreException e) {
        ApiUIPlugin.log(e);
    } finally {
        if (monitor != null) {
            monitor.done();
        }
    }
}

From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine_Test.java

License:Open Source License

public void testSearchWithValidMethod() throws Exception {
    IType type = createEntryPointType();
    IJavaElement method = type.getMethod("createUI", null);
    assertTrue(method.exists()); // precondition

    IType[] entryPointTypes = searchEngine.search(new IJavaElement[] { method });

    assertEquals(1, entryPointTypes.length);
    assertEquals("foo.Foo", entryPointTypes[0].getFullyQualifiedName());
}

From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine_Test.java

License:Open Source License

public void testSearchWithWrongMethodSignature() throws Exception {
    String code = "package foo;\n" + "class Foo implements EntryPoint {\n"
            + "  public int createUI( Object arg0 ) {\n" + "    return 0;\n" + "  }\n" + "}\n";
    project.createJavaClass("foo", "Foo", code);
    IType type = project.getJavaProject().findType("foo.Foo");
    IJavaElement method = type.getMethod("createUI", new String[] { "QObject;" });
    assertTrue(method.exists()); // precondition

    IType[] entryPointTypes = searchEngine.search(new IJavaElement[] { method });

    assertEquals(0, entryPointTypes.length);
}

From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine_Test.java

License:Open Source License

public void testSearchWithoutEntryPointInterface() throws Exception {
    String code = "package foo;\n" + "class Foo {\n" + "  public int createUI() {\n" + "    return 0;\n"
            + "  }\n" + "}\n";
    project.createJavaClass("foo", "Foo", code);
    IType type = project.getJavaProject().findType("foo.Foo");
    IJavaElement method = type.getMethod("createUI", null);
    assertTrue(method.exists()); // precondition

    IType[] entryPointTypes = searchEngine.search(new IJavaElement[] { method });

    assertEquals(0, entryPointTypes.length);
}

From source file:org.eclipse.rap.ui.internal.launch.rwt.shortcut.EntryPointSearchEngine_Test.java

License:Open Source License

public void testSearchOnInterfaceWithInvalidEntryPoint() throws Exception {
    String code = "package foo;\n" + "interface Foo extends EntryPoint {\n" + "  public int createUI();\n"
            + "}\n";
    project.createJavaClass("foo", "Foo", code);
    IType type = project.getJavaProject().findType("foo.Foo");
    IJavaElement method = type.getMethod("createUI", null);
    assertTrue(method.exists()); // precondition

    IType[] entryPointTypes = searchEngine.search(new IJavaElement[] { method });

    assertEquals(0, entryPointTypes.length);
}

From source file:org.eclipse.recommenders.internal.rcp.JavaElementSelections.java

License:Open Source License

private static boolean isInvalidSelection(ITypeRoot root, final int offset) {
    try {//from w  w  w .  j a  va2  s.c o m
        if (!root.exists()) {
            return true;
        }
        // check whether the type root is part of an package fragment root. If not, it's an invalid selection and
        // all resolutions are likely to fail. Thus, return true (=invalid):
        IJavaElement ancestor = root.getAncestor(IJavaProject.PACKAGE_FRAGMENT_ROOT);
        if (!ancestor.exists()) {
            return true;
        }
        ISourceRange range = root.getSourceRange();
        return range == null || offset < 0 || offset > range.getLength();
    } catch (Exception e) {
        log(ERROR_EXCEPTION_WHILE_CHECKING_OFFSETS, e);
        return false;
    }
}