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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

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./*from ww w  . j a  v  a  2  s  .c  om*/
 * @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.javaelements.AJCompilationUnitManager.java

License:Open Source License

public List getAJCompilationUnits(IPackageFragmentRoot root) throws CoreException {
    final List ajcus = new ArrayList();
    root.getResource().accept(new IResourceVisitor() {

        public boolean visit(IResource resource) {
            if (resource instanceof IFile && AspectJPlugin.AJ_FILE_EXT.equals(resource.getFileExtension())) {
                AJCompilationUnit ajcu = getAJCompilationUnit((IFile) resource);
                if (ajcu != null) {
                    ajcus.add(ajcu);/* w w w .j a v a 2 s. c  o m*/
                }
            }
            return resource.getType() == IResource.FOLDER || resource.getType() == IResource.PROJECT;
        }
    });
    return ajcus;
}

From source file:org.eclipse.ajdt.internal.core.ajde.CoreOutputLocationManager.java

License:Open Source License

public String getSourceFolderForFile(File sourceFile) {
    String sourceFilePath = sourceFile.getAbsolutePath();
    for (Entry<String, String> sourceFolderMapping : allSourceFolders.entrySet()) {
        if (sourceFilePath.startsWith(sourceFolderMapping.getKey())) {
            return sourceFolderMapping.getValue();
        }/*w  ww . ja v  a  2 s  .  c  o m*/
    }

    // might be a linked folder in a source folder
    IFile[] files = fileCache.findFilesForURI(sourceFile.toURI());
    try {
        IPackageFragmentRoot[] roots = jProject.getPackageFragmentRoots();
        for (IPackageFragmentRoot root : roots) {
            if (!root.isReadOnly()) {
                IContainer container = (IContainer) root.getResource();
                for (IFile file : files) {
                    if (container.getFullPath().isPrefixOf(file.getFullPath())) {
                        return allSourceFolders.get(container.getLocation().toOSString());
                    }
                }
            }
        }
    } catch (JavaModelException e) {
    }

    return null;
}

From source file:org.eclipse.ajdt.internal.launching.LTWUtils.java

License:Open Source License

/**
 * Get a list of all the aspects found in the given source
 * directory, which are included in the current build.
 * @param root/*ww w  .j a  va2s  .c o m*/
 * @return List of AspectElements
 * @throws CoreException
 */
public static List<IType> getAspects(final IPackageFragmentRoot root) throws CoreException {
    final List<IType> aspects = new ArrayList();
    final Set<IFile> includedFiles = BuildConfig.getIncludedSourceFiles(root.getJavaProject().getProject());
    root.getResource().accept(new IResourceVisitor() {

        public boolean visit(IResource resource) {
            if (includedFiles.contains(resource)) {
                AJCompilationUnit ajcu = AJCompilationUnitManager.INSTANCE
                        .getAJCompilationUnit((IFile) resource);
                if (ajcu != null) {
                    try {
                        IType[] types = ajcu.getAllAspects();
                        for (int i = 0; i < types.length; i++) {
                            aspects.add(types[i]);
                        }
                    } catch (JavaModelException e) {
                    }
                } else {
                    ICompilationUnit cu = JavaCore.createCompilationUnitFrom((IFile) resource);
                    if (cu != null) {
                        Set<IType> types = AJProjectModelFactory.getInstance().getModelForJavaElement(cu)
                                .aspectsForFile(cu);

                        for (IType element : types) {
                            aspects.add(element);
                        }
                    }
                }
            }
            return resource.getType() == IResource.FOLDER || resource.getType() == IResource.PROJECT;
        }
    });
    return aspects;
}

From source file:org.eclipse.ajdt.internal.ui.ajdocexport.AJdocTreeWizardPage.java

License:Open Source License

private IPath[] getSourcePath(IJavaProject[] projects) {
    HashSet res = new HashSet();
    //loops through all projects and gets a list if of thier sourpaths
    for (int k = 0; k < projects.length; k++) {
        IJavaProject iJavaProject = projects[k];

        try {/*  ww w. j  a  va2s. co m*/
            IPackageFragmentRoot[] roots = iJavaProject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                IPackageFragmentRoot curr = roots[i];
                if (curr.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    IResource resource = curr.getResource();
                    if (resource != null) {
                        IPath p = resource.getLocation();
                        if (p != null) {
                            res.add(p);
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            JavaPlugin.log(e);
        }
    }
    return (IPath[]) res.toArray(new IPath[res.size()]);
}

From source file:org.eclipse.ajdt.internal.ui.wizards.exports.StandardJavaElementContentProvider.java

License:Open Source License

/**
 * Note: This method is for internal use only. Clients should not call this method.
 *//*from  www .j av  a2s . com*/
protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) {
    IResource resource = root.getResource();
    return (resource instanceof IProject);
}

From source file:org.eclipse.babel.tapiji.tools.core.ui.quickfix.CreateResourceBundle.java

License:Open Source License

protected void runAction() {
    // First see if this is a "new wizard".
    IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard);
    // If not check if it is an "import wizard".
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard);
    }//  w  w  w. j  av  a2s  . c  o m
    // Or maybe an export wizard
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard);
    }
    try {
        // Then if we have a wizard, open it.
        if (descriptor != null) {
            IWizard wizard = descriptor.createWizard();
            if (!(wizard instanceof IResourceBundleWizard)) {
                return;
            }

            IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
            String[] keySilbings = key.split("\\.");
            String rbName = keySilbings[keySilbings.length - 1];
            String packageName = "";

            rbw.setBundleId(rbName);

            // Set the default path according to the specified package name
            String pathName = "";
            if (keySilbings.length > 1) {
                try {
                    IJavaProject jp = JavaCore.create(resource.getProject());
                    packageName = key.substring(0, key.lastIndexOf("."));

                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        IPackageFragment pf = fr.getPackageFragment(packageName);
                        if (pf.exists()) {
                            pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                } catch (Exception e) {
                    pathName = "";
                }
            }

            try {
                IJavaProject jp = JavaCore.create(resource.getProject());
                if (pathName.trim().equals("")) {
                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        if (!fr.isReadOnly()) {
                            pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                pathName = "";
            }

            rbw.setDefaultPath(pathName);

            WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard);
            wd.setTitle(wizard.getWindowTitle());
            if (wd.open() == WizardDialog.OK) {
                try {
                    resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID,
                            null, null);
                } catch (CoreException e) {
                    Logger.logError(e);
                }

                ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
                IPath path = resource.getRawLocation();
                try {
                    bufferManager.connect(path, null);
                    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
                    IDocument document = textFileBuffer.getDocument();

                    if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') {
                        start--;
                        end++;
                    }
                    if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') {
                        end++;
                    }

                    document.replace(start, end - start,
                            "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\"");

                    textFileBuffer.commit(null, false);
                } catch (Exception e) {
                    Logger.logError(e);
                } finally {
                    try {
                        bufferManager.disconnect(path, null);
                    } catch (CoreException e) {
                        Logger.logError(e);
                    }
                }
            }
        }
    } catch (CoreException e) {
        Logger.logError(e);
    }
}

From source file:org.eclipse.babel.tapiji.tools.java.ui.autocompletion.CreateResourceBundleProposal.java

License:Open Source License

@SuppressWarnings("deprecation")
protected void runAction() {
    // First see if this is a "new wizard".
    IWizardDescriptor descriptor = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard(newBunldeWizard);
    // If not check if it is an "import wizard".
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getImportWizardRegistry().findWizard(newBunldeWizard);
    }/*  w w w .ja va  2  s  . c o m*/
    // Or maybe an export wizard
    if (descriptor == null) {
        descriptor = PlatformUI.getWorkbench().getExportWizardRegistry().findWizard(newBunldeWizard);
    }
    try {
        // Then if we have a wizard, open it.
        if (descriptor != null) {
            IWizard wizard = descriptor.createWizard();

            if (!(wizard instanceof IResourceBundleWizard)) {
                return;
            }

            IResourceBundleWizard rbw = (IResourceBundleWizard) wizard;
            String[] keySilbings = key.split("\\.");
            String rbName = keySilbings[keySilbings.length - 1];
            String packageName = "";

            rbw.setBundleId(rbName);

            // Set the default path according to the specified package name
            String pathName = "";
            if (keySilbings.length > 1) {
                try {
                    IJavaProject jp = JavaCore.create(resource.getProject());
                    packageName = key.substring(0, key.lastIndexOf("."));

                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        IPackageFragment pf = fr.getPackageFragment(packageName);
                        if (pf.exists()) {
                            pathName = pf.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                } catch (Exception e) {
                    pathName = "";
                }
            }

            try {
                IJavaProject jp = JavaCore.create(resource.getProject());
                if (pathName.trim().equals("")) {
                    for (IPackageFragmentRoot fr : jp.getAllPackageFragmentRoots()) {
                        if (!fr.isReadOnly()) {
                            pathName = fr.getResource().getFullPath().removeFirstSegments(0).toOSString();
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                pathName = "";
            }

            rbw.setDefaultPath(pathName);

            WizardDialog wd = new WizardDialog(Display.getDefault().getActiveShell(), wizard);

            wd.setTitle(wizard.getWindowTitle());
            if (wd.open() == WizardDialog.OK) {
                try {
                    resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, I18nBuilder.BUILDER_ID,
                            null, null);
                } catch (CoreException e) {
                    Logger.logError(e);
                }

                ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager();
                IPath path = resource.getRawLocation();
                try {
                    bufferManager.connect(path, LocationKind.NORMALIZE, null);
                    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path,
                            LocationKind.NORMALIZE);
                    IDocument document = textFileBuffer.getDocument();

                    if (document.get().charAt(start - 1) == '"' && document.get().charAt(start) != '"') {
                        start--;
                        end++;
                    }
                    if (document.get().charAt(end + 1) == '"' && document.get().charAt(end) != '"') {
                        end++;
                    }

                    document.replace(start, end - start,
                            "\"" + (packageName.equals("") ? "" : packageName + ".") + rbName + "\"");

                    textFileBuffer.commit(null, false);
                } catch (Exception e) {
                } finally {
                    try {
                        bufferManager.disconnect(path, null);
                    } catch (CoreException e) {
                    }
                }
            }
        }
    } catch (CoreException e) {
    }
}

From source file:org.eclipse.che.jdt.refactoring.ccp.MoveTest.java

License:Open Source License

@Test
public void testDestination_yes_cuToOtherPackageWithMultiRoot() throws Exception {
    ParticipantTesting.reset();/* w  w  w.  jav a 2 s  . co  m*/
    //regression test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=47788
    IPackageFragment otherPackage = getRoot().createPackageFragment("otherPackage", true,
            new NullProgressMonitor());
    String oldA = "package p;public class A{}";
    String newA = "package otherPackage;public class A{}";
    ICompilationUnit cuA = getPackageP().createCompilationUnit("A.java", oldA, false,
            new NullProgressMonitor());

    IPackageFragmentRoot testSrc = JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(),
            "testSrc");

    ResourceChangedEvent event = new ResourceChangedEvent(
            new File(BaseTest.class.getResource("/projects").getFile()),
            new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, "projects",
                    testSrc.getJavaProject().getProject().getName(),
                    testSrc.getResource().getFullPath().toOSString(), false));
    JavaModelManager.getJavaModelManager().deltaState.resourceChanged(event);

    IPackageFragment testP = testSrc.createPackageFragment("p", true, new NullProgressMonitor());
    String oldRef = "package p;\npublic class Ref { A t = new A(); }";
    String newRef = "package p;\n\nimport otherPackage.A;\n\npublic class Ref { A t = new A(); }";
    ICompilationUnit cuRef = testP.createCompilationUnit("Ref.java", oldRef, false, new NullProgressMonitor());
    event = new ResourceChangedEvent(new File(BaseTest.class.getResource("/projects").getFile()),
            new ProjectItemModifiedEvent(ProjectItemModifiedEvent.EventType.CREATED, "projects",
                    cuRef.getJavaProject().getProject().getName(),
                    cuRef.getResource().getFullPath().toOSString(), false));
    JavaModelManager.getJavaModelManager().deltaState.resourceChanged(event);
    IJavaElement[] javaElements = { cuA };
    IResource[] resources = {};
    String[] handles = ParticipantTesting
            .createHandles(new Object[] { cuA, cuA.getTypes()[0], cuA.getResource() });
    JavaMoveProcessor processor = verifyEnabled(resources, javaElements, createReorgQueries());

    Object destination = otherPackage;
    verifyValidDestination(processor, destination);

    assertTrue("source file does not exist before moving", cuA.exists());
    RefactoringStatus status = performRefactoring(processor, true);
    assertEquals(null, status);
    assertTrue("source file exists after moving", !cuA.exists());
    ICompilationUnit newCu = otherPackage.getCompilationUnit(cuA.getElementName());
    assertTrue("new file does not exist after moving", newCu.exists());
    assertEqualLines("source differs", newA, newCu.getSource());
    assertEqualLines("Ref differs", newRef, cuRef.getSource());

    ParticipantTesting.testMove(handles,
            new MoveArguments[] { new MoveArguments(otherPackage, processor.getUpdateReferences()),
                    new MoveArguments(otherPackage, processor.getUpdateReferences()),
                    new MoveArguments(otherPackage.getResource(), processor.getUpdateReferences()) });
}

From source file:org.eclipse.che.jdt.refactoring.ccp.MoveTest.java

License:Open Source License

@Test
@Ignore//from   w w w  .j av a  2 s . com
public void testDestination_yes_sourceFolderToOtherProject() throws Exception {
    ParticipantTesting.reset();
    IJavaProject otherJavaProject = JavaProjectHelper.createJavaProject("other", "bin");

    IPackageFragmentRoot oldRoot = JavaProjectHelper.addSourceContainer(RefactoringTestSetup.getProject(),
            "newSrc");
    try {
        IJavaElement[] javaElements = { oldRoot };
        IResource[] resources = {};
        String[] handles = ParticipantTesting.createHandles(new Object[] { oldRoot, oldRoot.getResource() });
        JavaMoveProcessor ref = verifyEnabled(resources, javaElements, createReorgQueries());

        Object destination = otherJavaProject;
        verifyValidDestination(ref, destination);

        assertTrue("folder does not exist before", oldRoot.exists());
        RefactoringStatus status = performRefactoring(ref, false);
        assertEquals(null, status);
        assertTrue("folder not moved", !oldRoot.getResource().exists());
        IPackageFragmentRoot newRoot = getSourceFolder(otherJavaProject, oldRoot.getElementName());
        assertTrue("new folder does not exist after", newRoot.exists());
        ParticipantTesting.testMove(handles,
                new MoveArguments[] { new MoveArguments(otherJavaProject, ref.getUpdateReferences()),
                        new MoveArguments(otherJavaProject.getResource(), ref.getUpdateReferences()) });
    } finally {
        JavaProjectHelper.delete(otherJavaProject);
    }
}