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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:org.cubictest.exporters.selenium.ui.CustomStepWizard.java

License:Open Source License

@Override
public void addPages() {
    classWizard = new NewClassWizardPage();
    IJavaProject javaProject = JavaCore.create(project);
    IResource pageFragmentRoot = null;/*from w  w  w  . j  a va2  s.c o m*/
    try {
        for (IJavaElement element : javaProject.getChildren())
            if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
                pageFragmentRoot = element.getResource();
                break;
            }
    } catch (JavaModelException e) {
        Logger.error(e.getMessage(), e);
    }
    if (pageFragmentRoot != null)
        classWizard.setPackageFragmentRoot(javaProject.getPackageFragmentRoot(pageFragmentRoot), true);
    classWizard.addSuperInterface("org.cubictest.selenium.custom.ICustomTestStep");
    classWizard.setMethodStubSelection(false, false, true, true);
    addPage(classWizard);
}

From source file:org.dawnsci.common.widgets.breadcrumb.ResourceToItemsMapper.java

License:Open Source License

/**
 * Method that decides which elements can have error markers
 * Returns null if an element can not have error markers.
 * @param element The input element//from ww  w  . ja  v a  2  s. c  o m
 * @return Returns the corresponding resource or null
 */
private static IResource getCorrespondingResource(Object element) {
    if (element instanceof IJavaElement) {
        IJavaElement elem = (IJavaElement) element;
        IResource res = elem.getResource();
        if (res == null) {
            ICompilationUnit cu = (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
            if (cu != null) {
                // elements in compilation units are mapped to the underlying resource of the original cu
                res = cu.getResource();
            }
        }
        return res;
    } else if (element instanceof IResource) {
        return (IResource) element;
    }
    return null;
}

From source file:org.ebayopensource.dsf.javatojs.translate.TranslateHelper.java

License:Open Source License

public static String getResourceString(final ASTNode node) {
    if (node != null && node.getRoot() instanceof CompilationUnit) {
        CompilationUnit cu = (CompilationUnit) node.getRoot();
        IJavaElement javaElement = cu.getJavaElement();
        if (javaElement != null && javaElement.getResource() != null) {
            return javaElement.getResource().getFullPath().toString();
        }/*  w w  w . ja v  a 2 s .  c om*/
    }
    return null;
}

From source file:org.ecipse.che.plugin.testing.testng.server.TestSetUpUtil.java

License:Open Source License

/**
 * Removes an IJavaElement's resource. Retries if deletion failed (e.g. because the indexer still
 * locks the file)./* ww w .j av  a2  s. c o  m*/
 *
 * @param elem the element to delete
 * @throws CoreException if operation failed
 * @see #ASSERT_NO_MIXED_LINE_DELIMIERS
 */
public static void delete(final IJavaElement elem) throws CoreException {
    //      if (ASSERT_NO_MIXED_LINE_DELIMIERS)
    //         MixedLineDelimiterDetector.assertNoMixedLineDelimiters(elem);
    if (elem instanceof JavaProject) {
        ((JavaProject) elem).close();
        JavaModelManager.getJavaModelManager().removePerProjectInfo((JavaProject) elem, true);
    }
    JavaModelManager.getJavaModelManager().resetTemporaryCache();
    IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
        public void run(IProgressMonitor monitor) throws CoreException {
            //            performDummySearch();
            if (elem instanceof IJavaProject) {
                IJavaProject jproject = (IJavaProject) elem;
                jproject.setRawClasspath(new IClasspathEntry[0], jproject.getProject().getFullPath(), null);
            }
            delete(elem.getResource());
        }
    };
    ResourcesPlugin.getWorkspace().run(runnable, null);
    //      emptyDisplayLoop();
}

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

License:Open Source License

/**
 * Creates a Position from the supplied SearchMatch.
 *
 * @param project The project searching from.
 * @param match The SearchMatch.//www  . ja  v  a  2 s  .c o m
 * @return The Position.
 */
protected Position createPosition(IProject project, SearchMatch match) throws Exception {
    IJavaElement element = (IJavaElement) match.getElement();
    IJavaElement parent = JavaUtils.getPrimaryElement(element);

    String file = null;
    String elementName = JavaUtils.getFullyQualifiedName(parent);
    if (parent.getElementType() == IJavaElement.CLASS_FILE) {
        IResource resource = parent.getResource();
        // occurs with a referenced project as a lib with no source and class
        // files that are not archived in that project
        if (resource != null && resource.getType() == IResource.FILE && !isJarArchive(resource.getLocation())) {
            file = resource.getLocation().toOSString();

        } else {
            IPath path = null;
            IPackageFragmentRoot root = (IPackageFragmentRoot) parent.getParent().getParent();
            resource = root.getResource();
            if (resource != null) {
                if (resource.getType() == IResource.PROJECT) {
                    path = ProjectUtils.getIPath((IProject) resource);
                } else {
                    path = resource.getLocation();
                }
            } else {
                path = root.getPath();
            }

            String classFile = elementName.replace('.', File.separatorChar);
            if (isJarArchive(path)) {
                file = "jar:file://" + path.toOSString() + '!' + classFile + ".class";
            } else {
                file = path.toOSString() + '/' + classFile + ".class";
            }

            // android injects its jdk classes, so filter those out if the project
            // doesn't have the android nature.
            if (ANDROID_JDK_URL.matcher(file).matches() && project != null
                    && !project.hasNature(ANDROID_NATURE)) {
                return null;
            }

            // if a source path attachment exists, use it.
            IPath srcPath = root.getSourceAttachmentPath();
            if (srcPath != null) {
                String rootPath;
                IProject elementProject = root.getJavaProject().getProject();

                // determine if src path is project relative or file system absolute.
                if (srcPath.isAbsolute() && elementProject.getName().equals(srcPath.segment(0))) {
                    rootPath = ProjectUtils.getFilePath(elementProject, srcPath.toString());
                } else {
                    rootPath = srcPath.toOSString();
                }
                String srcFile = FileUtils.toUrl(rootPath + File.separator + classFile + ".java");

                // see if source file exists at source path.
                FileSystemManager fsManager = VFS.getManager();
                FileObject fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                if (fileObject.exists()) {
                    file = srcFile;

                    // jdk sources on osx are under a "src/" dir in the jar
                } else if (Os.isFamily(Os.FAMILY_MAC)) {
                    srcFile = FileUtils
                            .toUrl(rootPath + File.separator + "src" + File.separator + classFile + ".java");
                    fileObject = fsManager.resolveFile(srcFile.replace("%", "%25"));
                    if (fileObject.exists()) {
                        file = srcFile;
                    }
                }
            }
        }
    } else {
        IPath location = match.getResource().getLocation();
        file = location != null ? location.toOSString() : null;
    }

    elementName = JavaUtils.getFullyQualifiedName(element);
    return Position.fromOffset(file.replace('\\', '/'), elementName, match.getOffset(), match.getLength());
}

From source file:org.eclipse.ajdt.core.AspectJCore.java

License:Open Source License

/**
* Converts a handle signifying Java class to a handle signifying an
* aspect element.//from   w w w.  java 2 s  .c o  m
* 
* This method is necessary because JavaCore does not create
* AspectElements when it is building structure using the {@link AspectsConvertingParser}
* 
* Note that this changes the top level class to being an aspect and keeps 
* all others the same.  This may not work in all situations (eg- an inner aspect)
* 
* @param classHandle
* @return converts the handle to using {@link AspectElement#JEM_ASPECT_CU} and 
* {@link AspectElement#JEM_ASPECT_TYPE}
*/
public static String convertToAspectHandle(String classHandle, IJavaElement elt) {
    String aspectHandle = classHandle.replaceFirst("\\" + Character.toString(JavaElement.JEM_TYPE),
            Character.toString(AspectElement.JEM_ASPECT_TYPE));

    if (CoreUtils.ASPECTJ_SOURCE_ONLY_FILTER.accept(elt.getResource().getName())) {
        aspectHandle = aspectHandle.replace(JavaElement.JEM_COMPILATIONUNIT, AspectElement.JEM_ASPECT_CU);
    }
    return aspectHandle;
}

From source file:org.eclipse.ajdt.core.AspectJCore.java

License:Open Source License

public static String convertToJavaCUHandle(String aspectHandle, IJavaElement elt) {
    String javaHandle = aspectHandle;
    if (elt != null) {
        IResource resource = elt.getResource();
        if (resource != null) {
            if (CoreUtils.ASPECTJ_SOURCE_ONLY_FILTER.accept(resource.getName())) {
                javaHandle = javaHandle.replaceFirst("\\" + AspectElement.JEM_ASPECT_CU,
                        Character.toString(JavaElement.JEM_COMPILATIONUNIT));
            }//from   w ww.  j a v  a 2 s  . c  o m
        }
    }
    return javaHandle;
}

From source file:org.eclipse.ajdt.core.tests.AJCoreTest.java

License:Open Source License

private void compareWithHandles(String[][] testHandles) {
    for (int i = 0; i < testHandles.length; i++) {
        IJavaElement el = AspectJCore.create(testHandles[i][0]);
        assertEquals("Handle identifier of created element doesn't match original", //$NON-NLS-1$
                testHandles[i][0], el.getHandleIdentifier());
        assertEquals("Name of created element doesn't match expected", //$NON-NLS-1$
                testHandles[i][1], el.getElementName());
        assertEquals("Name of created element resource doesn't match expected", //$NON-NLS-1$
                testHandles[i][2], el.getResource().getName());
        assertEquals("Created element is not of the expected class type", //$NON-NLS-1$
                testHandles[i][3], getSimpleClassName(el));
    }/*from  w  w w  . j  a  v a2 s . co m*/
}

From source file:org.eclipse.ajdt.core.tests.codeselect.AbstractITDAwareCodeSelectionTests.java

License:Open Source License

protected void validateCodeSelect(ICompilationUnit unit, IRegion region, String expectedSrcFile,
        String expectedSignature) throws Exception {
    IJavaElement[] result = unit.codeSelect(region.getOffset(), region.getLength());
    assertEquals("Should have found exactly one hyperlink", 1, result.length);
    IJavaElement elt = result[0];
    assertTrue("Java element " + elt.getHandleIdentifier() + " should exist", elt.exists());
    String actualSrcFile = elt.getResource().getFullPath().toString();
    assertTrue("Element found is in the wrong source file:\n" + "   expected: " + expectedSrcFile + "\n"
            + "   found:    " + actualSrcFile, actualSrcFile.endsWith(expectedSrcFile));
    assertEquals("Element found has wrong signature", expectedSignature, getSignature(elt));
}

From source file:org.eclipse.ajdt.core.tests.model.BinaryWeavingSupportTest.java

License:Open Source License

public void testAspectPathDirWeaving() throws Exception {
    /*IProject libProject = */createPredefinedProject("MyAspectLibrary2"); //$NON-NLS-1$
    //      AJProjectModelFacade libModel = AJProjectModelFactory.getInstance().getModelForProject(libProject);

    IProject weaveMeProject = createPredefinedProject("WeaveMe2"); //$NON-NLS-1$
    AJProjectModelFacade weaveMeModel = AJProjectModelFactory.getInstance().getModelForProject(weaveMeProject);

    AJRelationshipType[] rels = new AJRelationshipType[] { AJRelationshipManager.ADVISED_BY };
    List allRels = weaveMeModel.getRelationshipsForProject(rels);
    IJavaElement mainEl = null;//from   w  ww  .j a va 2  s  . c  om
    for (Iterator iter = allRels.iterator(); (mainEl == null) && iter.hasNext();) {
        IRelationship rel = (IRelationship) iter.next();
        IJavaElement source = weaveMeModel.programElementToJavaElement(rel.getSourceHandle());
        if (source.getElementName().equals("main")) { //$NON-NLS-1$
            mainEl = source;
        }
    }
    assertNotNull("Didn't find element for advised main method", mainEl); //$NON-NLS-1$
    List related = weaveMeModel.getRelationshipsForElement(mainEl, AJRelationshipManager.ADVISED_BY);
    assertNotNull("getRelatedElements returned null", related); //$NON-NLS-1$
    boolean found1 = false;
    boolean found2 = false;
    boolean found3 = false;
    for (Iterator iter = related.iterator(); iter.hasNext();) {
        IJavaElement el = (IJavaElement) iter.next();
        String elName = el.getElementName();
        String resName = el.getResource().getName();
        if (elName.equals("before")) { //$NON-NLS-1$
            found1 = true;
            assertEquals("Found before element in wrong file", "MyBar.aj", resName); //$NON-NLS-1$ //$NON-NLS-2$
        } else if (elName.equals("afterReturning")) { //$NON-NLS-1$
            found2 = true;
            assertEquals("Found before afterReturning in wrong file", "MyBar2.aj", resName); //$NON-NLS-1$ //$NON-NLS-2$
        } else if (elName.equals("around")) { //$NON-NLS-1$
            found3 = true;
            assertEquals("Found before around in wrong file", "MyBar3.aj", resName); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
    assertTrue("Didn't find advised by before() relationship", found1); //$NON-NLS-1$
    assertTrue("Didn't find advised by afterReturning() relationship", found2); //$NON-NLS-1$
    assertTrue("Didn't find advised by around() relationship", found3); //$NON-NLS-1$

    // now look for added "advises" relationships in the aspect library
    // probject
    // XXX Not doing this any more
    //      rels = new AJRelationshipType[] { AJRelationshipManager.ADVISES };
    //      allRels = libModel.getRelationshipsForProject(rels);
    //      found1 = false;
    //      found2 = false;
    //      found3 = false;
    //      for (Iterator iter = allRels.iterator(); iter.hasNext();) {
    //         IRelationship rel = (IRelationship) iter.next();
    //         String sourceName = libModel.programElementToJavaElement(rel.getSourceHandle()).getElementName();
    //         for (Iterator targetIter = rel.getTargets().iterator(); targetIter.hasNext(); ) {
    //             String targetName = libModel.programElementToJavaElement((String) targetIter.next()).getElementName();
    //             if (sourceName.equals("before")) { //$NON-NLS-1$
    //                found1 = true;
    //                assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //             } else if (sourceName.equals("afterReturning")) { //$NON-NLS-1$
    //                found2 = true;
    //                assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //             } else if (sourceName.equals("around")) { //$NON-NLS-1$
    //                found3 = true;
    //                assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //             }
    //         }
    //      }
    //      assertTrue("Didn't find advises before() relationship", found1); //$NON-NLS-1$
    //      assertTrue("Didn't find advises afterReturning() relationship", found2); //$NON-NLS-1$
    //      assertTrue("Didn't find advises around() relationship", found3); //$NON-NLS-1$

    // there is no "getOtherProjectAllRelationships" any more
    //      List otherProjectRels = model.getOtherProjectAllRelationships(rels);
    //      found1 = false;
    //      found2 = false;
    //      found3 = false;
    //      for (Iterator iter = otherProjectRels.iterator(); iter.hasNext();) {
    //         AJRelationship rel = (AJRelationship) iter.next();
    //         String sourceName = rel.getSource().getElementName();
    //         String targetName = rel.getTarget().getElementName();
    //         if (sourceName.equals("before")) { //$NON-NLS-1$
    //            found1 = true;
    //            assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //         } else if (sourceName.equals("afterReturning")) { //$NON-NLS-1$
    //            found2 = true;
    //            assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //         } else if (sourceName.equals("around")) { //$NON-NLS-1$
    //            found3 = true;
    //            assertEquals("Incorrect target name", "main", targetName); //$NON-NLS-1$ //$NON-NLS-2$
    //         }
    //      }
    //      assertTrue("Didn't find advises before() relationship", found1); //$NON-NLS-1$
    //      assertTrue("Didn't find advises afterReturning() relationship", found2); //$NON-NLS-1$
    //      assertTrue("Didn't find advises around() relationship", found3); //$NON-NLS-1$
}