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:cn.ieclipse.pde.explorer.java.JavaAdapterFactory.java

License:Apache License

public IExplorable getFromJava(IJavaElement obj) {
    String path = null;/*from w  w w  . j  av a 2  s.c om*/
    // java project.
    if (obj instanceof IJavaProject) {
        path = ((IJavaProject) obj).getProject().getLocation().toOSString();
        return new Explorer(path, null);
    }
    // jar resource is null
    else if (obj instanceof JarPackageFragmentRoot) {
        IPackageFragmentRoot lib = ((IPackageFragmentRoot) obj);
        if (!lib.isExternal()) {
            IWorkspaceRoot root = lib.getJavaProject().getProject().getWorkspace().getRoot();
            IResource res = root.findMember(lib.getPath());
            if (res != null) {
                return ExplorerPlugin.getFromResource(res);
            }
        }
        // external lib
        String file = lib.getPath().toOSString();
        return new Explorer(null, file);
    } else if (obj instanceof IPackageFragmentRoot) {
        // src folder
        IPackageFragmentRoot src = ((IPackageFragmentRoot) obj);
        IProject p = src.getJavaProject().getProject();
        String prjPath = p.getLocation().toOSString();
        IResource res = src.getResource();
        // Fix multi-folder source folder issue
        String srcospath = res.getProjectRelativePath().toOSString();
        path = new File(prjPath, srcospath).getAbsolutePath();
        // end fix
        return new Explorer(path, null);
        // System.out.println(path);
    } else if (obj instanceof IPackageFragment) {// other : package
        IResource resource = ((IPackageFragment) obj).getResource();
        path = resource.getLocation().toOSString();
        return new Explorer(path, null);
    } else {// member:filed:
        IResource resource = ((IJavaElement) obj).getResource();
        String file = resource.getLocation().toOSString();
        // get folder
        return new Explorer(null, file);
    }
}

From source file:com.codenvy.ide.ext.java.server.javadoc.JavadocContentAccess2.java

License:Open Source License

private boolean handleDocRoot(TagElement node) {
    if (!TagElement.TAG_DOCROOT.equals(node.getTagName()))
        return false;

    String url = null;/*ww w . java  2  s  . co m*/
    if (fElement instanceof IMember && ((IMember) fElement).isBinary()) {
        //TODO
        URL javadocBaseLocation = null;//JavaUI.getJavadocBaseLocation(fElement);
        if (javadocBaseLocation != null) {
            url = javadocBaseLocation.toExternalForm();
        }
    } else {
        IPackageFragmentRoot srcRoot = JavaModelUtil.getPackageFragmentRoot(fElement);
        if (srcRoot != null) {
            IResource resource = srcRoot.getResource();
            if (resource != null) {
                /*
                 * Too bad: Browser widget knows nothing about EFS and custom URL handlers,
                 * so IResource#getLocationURI() does not work in all cases.
                 * We only support the local file system for now.
                 * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
                 */
                IPath location = resource.getLocation();
                if (location != null) {
                    url = location.toFile().toURI().toASCIIString();
                }
            }

        }
    }
    if (url != null) {
        if (url.endsWith("/")) { //$NON-NLS-1$
            url = url.substring(0, url.length() - 1);
        }
        fBuf.append(url);
        return true;
    }
    return false;
}

From source file:com.ebmwebsourcing.petals.studio.dev.properties.internal.wizards.GenerateConstantsWizardPage.java

License:Open Source License

@Override
public void createControl(Composite parent) {

    // Create the composite container and define its layout
    final Composite container = new Composite(parent, SWT.NONE);
    GridLayoutFactory.swtDefaults().extendedMargins(15, 15, 15, 10).numColumns(2).applyTo(container);
    container.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    // Container viewer
    Label l = new Label(container, SWT.NONE);
    l.setText("Select the output directory to generate the Java constants.");
    GridDataFactory.swtDefaults().span(2, 1).applyTo(l);

    TreeViewer viewer = new TreeViewer(container, SWT.SINGLE | SWT.BORDER | SWT.V_SCROLL | SWT.HIDE_SELECTION);
    GridData layoutData = new GridData(GridData.FILL_BOTH);
    layoutData.heightHint = 100;/*from w w  w  .  java2s.co  m*/
    layoutData.horizontalSpan = 2;
    viewer.getTree().setLayoutData(layoutData);
    viewer.setLabelProvider(new WorkbenchLabelProvider());
    viewer.setContentProvider(new WorkbenchContentProvider() {

        /*
         * (non-Javadoc)
         * @see org.eclipse.ui.model.BaseWorkbenchContentProvider
         * #getChildren(java.lang.Object)
         */
        @Override
        public Object[] getChildren(Object o) {

            List<Object> children = new ArrayList<Object>();
            try {
                if (o instanceof IJavaProject) {
                    for (IPackageFragmentRoot root : ((IJavaProject) o).getPackageFragmentRoots()) {
                        if (root.getResource() instanceof IContainer)
                            children.add(root);
                    }

                } else if (o instanceof IWorkspaceRoot) {
                    for (IProject p : ((IWorkspaceRoot) o).getProjects()) {
                        if (!p.isAccessible() || !p.hasNature(JavaCore.NATURE_ID))
                            continue;

                        IJavaProject jp = JavaCore.create(p);
                        if (jp != null)
                            children.add(jp);
                    }
                }

            } catch (CoreException e) {
                PetalsStudioDevPlugin.log(e, IStatus.ERROR);
            }

            return children.toArray(new Object[0]);
        }

        /*
         * (non-Javadoc)
         * @see org.eclipse.ui.model.BaseWorkbenchContentProvider
         * #hasChildren(java.lang.Object)
         */
        @Override
        public boolean hasChildren(Object element) {
            return getChildren(element).length > 0;
        }
    });

    // Set page input
    viewer.setInput(ResourcesPlugin.getWorkspace().getRoot());
    if (this.originalSelection != null) {
        try {
            IJavaProject jp = JavaCore.create(this.originalSelection);
            for (IPackageFragmentRoot root : jp.getPackageFragmentRoots()) {
                if (root.getResource() instanceof IContainer) {
                    GenerateConstantsWizardPage.this.target = root;
                    break;
                }
            }

        } catch (JavaModelException e) {
            PetalsStudioDevPlugin.log(e, IStatus.ERROR, "This should not happen (check in the handler).");
        }
    }

    if (this.target != null) {
        viewer.setSelection(new StructuredSelection(this.target), true);
        viewer.expandToLevel(this.target, 1);
        viewer.getTree().notifyListeners(SWT.Selection, new Event());
    }

    // Java meta
    new Label(container, SWT.NONE).setText("Java Package:");
    final Text packageText = new Text(container, SWT.SINGLE | SWT.BORDER);
    packageText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    packageText.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e) {
            GenerateConstantsWizardPage.this.javaPackage = ((Text) e.widget).getText().trim();
            validate();
        }
    });

    new Label(container, SWT.NONE).setText("Java Class Name:");
    final Text classText = new Text(container, SWT.SINGLE | SWT.BORDER);
    classText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
    classText.addModifyListener(new ModifyListener() {
        @Override
        public void modifyText(ModifyEvent e) {
            GenerateConstantsWizardPage.this.className = ((Text) e.widget).getText().trim();
            validate();
        }
    });

    // Add the missing listeners
    viewer.addPostSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {

            Object o = ((IStructuredSelection) event.getSelection()).getFirstElement();
            if (o instanceof IPackageFragmentRoot) {

                GenerateConstantsWizardPage.this.target = (IPackageFragmentRoot) o;
                String pName = GenerateConstantsWizardPage.this.target.getJavaProject().getProject().getName();
                packageText.setText(pName.replaceAll("-", ".") + ".generated");

                int index = pName.lastIndexOf('.') + 1;
                if (index <= 0 || index > pName.length())
                    pName = "Default";
                else
                    pName = pName.substring(index);
                classText.setText(pName);

            } else {
                GenerateConstantsWizardPage.this.target = null;
            }
        }
    });

    // Set control
    setControl(container);
}

From source file:com.google.gdt.eclipse.core.java.ClasspathResourceUtilities.java

License:Open Source License

/**
 * Gets the classpath relative path of a given resource.
 * //from www  .jav  a  2  s.c  o  m
 * Note: This method does not consider build path exclusion/inclusion filters.
 * 
 * @param resource
 * @param javaProject
 * @return the classpath relative path, or null if it could not be determined
 * @throws JavaModelException
 * @see JavaModelSearch#isValidElement(org.eclipse.jdt.core.IJavaElement)
 */
public static IPath getClasspathRelativePathOfResource(IResource resource, IJavaProject javaProject)
        throws JavaModelException {

    IPackageFragmentRoot root = getPackageFragmentRootForResource(resource, javaProject);
    if (root == null) {
        return null;
    }

    IResource rootResource = root.getResource();
    IPath rootProjectPath = rootResource.getProjectRelativePath();
    IPath resourceProjectPath = resource.getProjectRelativePath();

    if (rootProjectPath.isPrefixOf(resourceProjectPath)) {
        return resourceProjectPath.removeFirstSegments(rootProjectPath.segmentCount());
    } else {
        return null;
    }
}

From source file:com.google.gdt.eclipse.designer.actions.deploy.DeployModuleAction.java

License:Open Source License

/**
 * Returns ANT code for creating jar's for given project itself, coping its jar's from classpath
 * and calls itself for required projects.
 *///from w ww. j av  a2 s  .  c  o  m
private static String prepareJars(IProject project, String targetModulePath, boolean addRuntimeJars)
        throws Exception {
    String script = "";
    //
    IJavaProject javaProject = JavaCore.create(project);
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    // add <jar> task for creating jar from project source and output folders
    {
        List<String> sourceLocations = Lists.newArrayList();
        List<String> binaryLocations = Lists.newArrayList();
        for (IPackageFragmentRoot packageFragmentRoot : roots) {
            if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                // add source location
                sourceLocations.add(packageFragmentRoot.getResource().getLocation().toPortableString());
                // add output location
                {
                    // prepare output location
                    IPath location;
                    {
                        IClasspathEntry cpEntry = packageFragmentRoot.getRawClasspathEntry();
                        location = cpEntry.getOutputLocation();
                        if (location == null) {
                            location = javaProject.getOutputLocation();
                        }
                    }
                    // add absolute location
                    {
                        // remove first segment (project)
                        location = location.removeFirstSegments(1);
                        // prepare absolute location
                        IPath absoluteLocation = project.getLocation().append(location);
                        binaryLocations.add(absoluteLocation.toPortableString());
                    }
                }
            }
        }
        //
        script += "\t\t<!--=== " + project.getName() + " ===-->\n";
        script += "\t\t<jar destfile='" + targetModulePath + "/WEB-INF/lib/" + project.getName() + ".jar'>\n";
        script += prepareFileSets(sourceLocations, "**");
        script += prepareFileSets(binaryLocations, "**/*.class");
        script += "\t\t</jar>\n";
    }
    // add <copy> task for coping required runtime jar's
    if (addRuntimeJars) {
        String jars = "";
        IRuntimeClasspathEntry[] classpathEntries = JavaRuntime.computeUnresolvedRuntimeClasspath(javaProject);
        for (int entryIndex = 0; entryIndex < classpathEntries.length; entryIndex++) {
            IRuntimeClasspathEntry entry = classpathEntries[entryIndex];
            IRuntimeClasspathEntry[] resolvedEntries = JavaRuntime.resolveRuntimeClasspathEntry(entry,
                    javaProject);
            for (int resolvedEntryIndex = 0; resolvedEntryIndex < resolvedEntries.length; resolvedEntryIndex++) {
                IRuntimeClasspathEntry resolvedEntry = resolvedEntries[resolvedEntryIndex];
                if (resolvedEntry.getClasspathProperty() == IRuntimeClasspathEntry.USER_CLASSES
                        && resolvedEntry.getType() == IRuntimeClasspathEntry.ARCHIVE) {
                    String location = resolvedEntry.getLocation();
                    // exclude gwt-user.jar, it is in classpath, but it has Servlet class, so can not be in application
                    if (location.endsWith("gwt-user.jar")) {
                        continue;
                    }
                    // add jar file in fileset
                    jars += "\t\t\t<fileset file=\"" + location + "\"/>\n";
                }
            }
        }
        //
        if (jars.length() != 0) {
            script += "\t\t<copy todir='" + targetModulePath + "/WEB-INF/lib'>\n";
            script += jars;
            script += "\t\t</copy>\n";
        }
    }
    // add required projects
    {
        IProject[] referencedProjects = project.getReferencedProjects();
        for (int i = 0; i < referencedProjects.length; i++) {
            IProject referencedProject = referencedProjects[i];
            script += prepareJars(referencedProject, targetModulePath, false);
        }
    }
    //
    return script;
}

From source file:com.google.gdt.eclipse.designer.launch.AbstractGwtLaunchConfigurationDelegate.java

License:Open Source License

/**
 * GWT requires source folders in classpath (because it has its own compiler), so we should add
 * all source folders for given project and its required projects.
 *//*w  ww .  ja  v a  2 s . c  om*/
public static void addSourceFolders(Set<IProject> visitedProjects, List<String> entries, IProject project)
        throws CoreException {
    // HACK: see above
    if (project.getName().endsWith("-design")) {
        return;
    }
    // check for recursion
    if (visitedProjects.contains(project)) {
        return;
    }
    visitedProjects.add(project);
    //
    IJavaProject javaProject = JavaCore.create(project);
    // add source folders for given project
    {
        IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < packageFragmentRoots.length; i++) {
            IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[i];
            if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                entries.add(packageFragmentRoot.getResource().getLocation().toPortableString());
            }
        }
    }
    // process required projects
    {
        IProject[] referencedProjects = project.getReferencedProjects();
        for (int i = 0; i < referencedProjects.length; i++) {
            IProject referencedProject = referencedProjects[i];
            addSourceFolders(visitedProjects, entries, referencedProject);
        }
    }
}

From source file:com.google.gdt.eclipse.designer.util.resources.DefaultResourcesProvider.java

License:Open Source License

/**
 * Appends source {@link IPackageFragmentRoot}'s, because {@link DefaultResourcesProvider} should
 * provide access not only to the binary resources (i.e. just resources in classpath), but also to
 * the source resources./*w w  w.  ja  v a2 s . co  m*/
 */
private static void addSourceFolders(Set<IProject> visitedProjects, List<String> entries, IProject project)
        throws Exception {
    // may be not exists
    if (!project.exists()) {
        return;
    }
    // may be already visited
    if (visitedProjects.contains(project)) {
        return;
    }
    visitedProjects.add(project);
    // add source folders for IJavaProject
    {
        IJavaProject javaProject = JavaCore.create(project);
        if (javaProject.exists()) {
            for (IPackageFragmentRoot packageFragmentRoot : javaProject.getPackageFragmentRoots()) {
                if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    entries.add(packageFragmentRoot.getResource().getLocation().toPortableString());
                }
            }
        }
    }
    // process required projects
    for (IProject referencedProject : project.getReferencedProjects()) {
        addSourceFolders(visitedProjects, entries, referencedProject);
    }
}

From source file:com.jstar.eclipse.objects.JavaFile.java

License:BSD License

private String getAbsolutePath(IClasspathEntry entry) {
    IPath entryPath = entry.getPath();/*from   ww  w.  j a  v a2 s.  c  om*/
    IPackageFragmentRoot lib = null;

    try {
        lib = getJavaProject().getProject().findPackageFragmentRoot(entryPath);
    } catch (JavaModelException jme) {
    }

    if (lib == null) {
        return entryPath.toOSString();
    }

    if (lib.getResource() == null) {
        return entryPath.toOSString();
    } else {
        return lib.getResource().getLocation().toOSString();
    }

}

From source file:com.liferay.ide.server.util.ComponentUtil.java

License:Open Source License

public static IFolder[] getSourceContainers(IProject project) {
    List<IFolder> sourceFolders = new ArrayList<IFolder>();

    IPackageFragmentRoot[] sources = getSources(project);

    for (IPackageFragmentRoot source : sources) {
        if (source.getResource() instanceof IFolder) {
            sourceFolders.add(((IFolder) source.getResource()));
        }/*  w  w  w. j  a v  a 2s  .c  om*/
    }

    return sourceFolders.toArray(new IFolder[sourceFolders.size()]);
}

From source file:com.microsoft.javapkgsrv.JavaElementLabelComposer.java

License:Open Source License

private void appendInternalArchiveLabel(IPackageFragmentRoot root, long flags) {
    IResource resource = root.getResource();
    boolean rootQualified = getFlag(flags, ROOT_QUALIFIED);
    if (rootQualified) {
        fBuffer.append(root.getPath().makeRelative().toString());
    } else {/*from w w  w.j a  va  2s  .c  om*/
        fBuffer.append(root.getElementName());
        int offset = fBuffer.length();
        boolean referencedPostQualified = getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED);
        if (referencedPostQualified && isReferenced(root)) {
            fBuffer.append(CONCAT_STRING);
            fBuffer.append(resource.getParent().getFullPath().makeRelative().toString());
        } else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
            fBuffer.append(CONCAT_STRING);
            fBuffer.append(root.getParent().getPath().makeRelative().toString());
        }
        if (referencedPostQualified) {
            try {
                IClasspathEntry referencingEntry = getClasspathEntry(root).getReferencingEntry();
                if (referencingEntry != null) {
                    fBuffer.append(" (from ");
                    fBuffer.append(Name.CLASS_PATH.toString());
                    fBuffer.append(" of ");
                    fBuffer.append(referencingEntry.getPath().lastSegment());
                    fBuffer.append(")");
                }
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }
}