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

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

Introduction

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

Prototype

IJavaProject getJavaProject();

Source Link

Document

Returns the Java project this element is contained in, or null if this element is not contained in any Java project (for instance, the IJavaModel is not contained in any Java project).

Usage

From source file:at.bestsolution.fxide.jdt.corext.javadoc.JavaDocLocations.java

License:Open Source License

public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
    if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
        return getProjectJavadocLocation((IJavaProject) element);
    }/*  w  ww. ja  va  2s  .co  m*/

    IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
    if (root == null) {
        return null;
    }

    if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
        IClasspathEntry entry = root.getResolvedClasspathEntry();
        URL javadocLocation = getLibraryJavadocLocation(entry);
        if (javadocLocation != null) {
            return getLibraryJavadocLocation(entry);
        }
        entry = root.getRawClasspathEntry();
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
        case IClasspathEntry.CPE_VARIABLE:
            return getLibraryJavadocLocation(entry);
        default:
            return null;
        }
    } else {
        return getProjectJavadocLocation(root.getJavaProject());
    }
}

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Returns <code>true</code> if the given package fragment root is
 * referenced. This means it is a descendant of a different project but is referenced
 * by the root's parent. Returns <code>false</code> if the given root
 * doesn't have an underlying resource.//from w  w  w.  j a v a  2s  .  c  o  m
 *
 * @param root the package fragment root
 * @return returns <code>true</code> if the given package fragment root is referenced
 */
private boolean isReferenced(IPackageFragmentRoot root) {
    IResource resource = root.getResource();
    if (resource != null) {
        IProject jarProject = resource.getProject();
        IProject container = root.getJavaProject().getProject();
        return !container.equals(jarProject);
    }
    return false;
}

From source file:cn.ieclipse.pde.explorer.java.JavaAdapterFactory.java

License:Apache License

public IExplorable getFromJava(IJavaElement obj) {
    String path = null;// ww w . j  a va  2 s.  com
    // 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.internal.core.DeltaProcessor.java

License:Open Source License

private void addPackageFragmentRoot(OpenableElementInfo parent, IPackageFragmentRoot child)
        throws JavaModelException {

    IJavaElement[] roots = parent.getChildren();
    if (roots.length > 0) {
        IClasspathEntry[] resolvedClasspath = ((JavaProject) child.getJavaProject()).getResolvedClasspath();
        IPath currentEntryPath = child.getResolvedClasspathEntry().getPath();
        int indexToInsert = -1;
        int lastComparedIndex = -1;
        int i = 0, j = 0;
        for (; i < roots.length && j < resolvedClasspath.length;) {

            IClasspathEntry classpathEntry = resolvedClasspath[j];
            if (lastComparedIndex != j && currentEntryPath.equals(classpathEntry.getPath())) {
                indexToInsert = i;/* w  w w  . j a va2s.c  o  m*/
                break;
            }
            lastComparedIndex = j;

            IClasspathEntry rootEntry = ((IPackageFragmentRoot) roots[i]).getResolvedClasspathEntry();
            if (rootEntry.getPath().equals(classpathEntry.getPath()))
                i++;
            else
                j++;
        }

        for (; i < roots.length; i++) {
            // If the new root is already among the children, no need to proceed further. Just return.
            if (roots[i].equals(child)) {
                return;
            }
            // If we start seeing root's classpath entry different from the child's entry, then the child can't
            // be present further down the roots array.
            if (!((IPackageFragmentRoot) roots[i]).getResolvedClasspathEntry().getPath()
                    .equals(currentEntryPath))
                break;
        }

        if (indexToInsert >= 0) {
            int newSize = roots.length + 1;
            IPackageFragmentRoot[] newChildren = new IPackageFragmentRoot[newSize];

            if (indexToInsert > 0)
                System.arraycopy(roots, 0, newChildren, 0, indexToInsert);

            newChildren[indexToInsert] = child;
            System.arraycopy(roots, indexToInsert, newChildren, indexToInsert + 1,
                    (newSize - indexToInsert - 1));
            parent.setChildren(newChildren);
            return;
        }
    }
    parent.addChild(child);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.PackageFragmentRootInfo.java

License:Open Source License

/**
 * Starting at this folder, create non-java resources for this package fragment root
 * and add them to the non-java resources collection.
 *
 * @exception org.eclipse.jdt.core.JavaModelException  The resource associated with this package fragment does not exist
 *///from w  w  w.  ja v  a2  s.  com
static Object[] computeFolderNonJavaResources(IPackageFragmentRoot root, IContainer folder,
        char[][] inclusionPatterns, char[][] exclusionPatterns) throws JavaModelException {
    IResource[] nonJavaResources = new IResource[5];
    int nonJavaResourcesCounter = 0;
    try {
        IResource[] members = folder.members();
        int length = members.length;
        if (length > 0) {
            // if package fragment root refers to folder in another IProject, then
            // folder.getProject() is different than root.getJavaProject().getProject()
            // use the other java project's options to verify the name
            IJavaProject otherJavaProject = JavaCore.create(folder.getProject());
            String sourceLevel = otherJavaProject.getOption(JavaCore.COMPILER_SOURCE, true);
            String complianceLevel = otherJavaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
            JavaProject javaProject = (JavaProject) root.getJavaProject();
            IClasspathEntry[] classpath = javaProject.getResolvedClasspath();
            nextResource: for (int i = 0; i < length; i++) {
                IResource member = members[i];
                switch (member.getType()) {
                case IResource.FILE:
                    String fileName = member.getName();

                    // ignore .java files that are not excluded
                    if (Util.isValidCompilationUnitName(fileName, sourceLevel, complianceLevel)
                            && !Util.isExcluded(member, inclusionPatterns, exclusionPatterns))
                        continue nextResource;
                    // ignore .class files
                    if (Util.isValidClassFileName(fileName, sourceLevel, complianceLevel))
                        continue nextResource;
                    // ignore .zip or .jar file on classpath
                    if (isClasspathEntry(member.getFullPath(), classpath))
                        continue nextResource;
                    break;

                case IResource.FOLDER:
                    // ignore valid packages or excluded folders that correspond to a nested pkg fragment root
                    if (Util.isValidFolderNameForPackage(member.getName(), sourceLevel, complianceLevel)
                            && (!Util.isExcluded(member, inclusionPatterns, exclusionPatterns)
                                    || isClasspathEntry(member.getFullPath(), classpath)))
                        continue nextResource;
                    break;
                }
                if (nonJavaResources.length == nonJavaResourcesCounter) {
                    // resize
                    System.arraycopy(nonJavaResources, 0,
                            (nonJavaResources = new IResource[nonJavaResourcesCounter * 2]), 0,
                            nonJavaResourcesCounter);
                }
                nonJavaResources[nonJavaResourcesCounter++] = member;
            }
        }
        //      if (ExternalFoldersManager.isInternalPathForExternalFolder(folder.getFullPath())) {
        //         IJarEntryResource[] jarEntryResources = new IJarEntryResource[nonJavaResourcesCounter];
        //         for (int i = 0; i < nonJavaResourcesCounter; i++) {
        //            jarEntryResources[i] = new NonJavaResource(root, nonJavaResources[i]);
        //         }
        //         return jarEntryResources;
        //      } else if (nonJavaResources.length != nonJavaResourcesCounter) {
        //         System.arraycopy(nonJavaResources, 0, (nonJavaResources = new IResource[nonJavaResourcesCounter]), 0, nonJavaResourcesCounter);
        //      }
        return nonJavaResources;
    } catch (CoreException e) {
        throw new JavaModelException(e);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

private synchronized void computeAllRootPaths(IType type) {
    if (this.areRootPathsComputed) {
        return;/*  w w w  .j a  v  a 2 s.  c  o m*/
    }
    IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
    IPath pkgFragmentRootPath = root.getPath();
    final HashSet tempRoots = new HashSet();
    long time = 0;
    if (VERBOSE) {
        System.out.println("compute all root paths for " + root.getElementName()); //$NON-NLS-1$
        time = System.currentTimeMillis();
    }
    final HashSet firstLevelPackageNames = new HashSet();
    boolean containsADefaultPackage = false;
    boolean containsJavaSource = !pkgFragmentRootPath.equals(this.sourcePath); // used to optimize zip file reading only if source path and root path are equals, otherwise
    // assume that attachment contains Java source

    String sourceLevel = null;
    String complianceLevel = null;
    if (root.isArchive()) {
        //         org.eclipse.jdt.internal.core.JavaModelManager manager = org.eclipse.jdt.internal.core.JavaModelManager.getJavaModelManager();
        ZipFile zip = null;
        try {
            zip = manager.getZipFile(pkgFragmentRootPath);
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (!entry.isDirectory()) {
                    if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entryName)) {
                        int index = entryName.indexOf('/');
                        if (index != -1) {
                            String firstLevelPackageName = entryName.substring(0, index);
                            if (!firstLevelPackageNames.contains(firstLevelPackageName)) {
                                if (sourceLevel == null) {
                                    IJavaProject project = root.getJavaProject();
                                    sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                                    complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                                }
                                IStatus status = Status.OK_STATUS;// JavaConventions
                                //                                 .validatePackageName(firstLevelPackageName, sourceLevel, complianceLevel);
                                if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                                    firstLevelPackageNames.add(firstLevelPackageName);
                                }
                            }
                        } else {
                            containsADefaultPackage = true;
                        }
                    } else if (!containsJavaSource && com.codenvy.ide.ext.java.server.internal.core.util.Util
                            .isJavaLikeFileName(entryName)) {
                        containsJavaSource = true;
                    }
                }
            }
        } catch (CoreException e) {
            // ignore
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
    } /*else {
      Object target = JavaModel.getTarget(root.getPath(), true);
      if (target instanceof IResource) {
      IResource resource = (IResource) target;
      if (resource instanceof IContainer) {
         try {
            IResource[] members = ((IContainer) resource).members();
            for (int i = 0, max = members.length; i < max; i++) {
               IResource member = members[i];
               String resourceName = member.getName();
               if (member.getType() == IResource.FOLDER) {
                  if (sourceLevel == null) {
                     IJavaProject project = root.getJavaProject();
                     sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
                     complianceLevel = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
                  }
                  IStatus status = JavaConventions.validatePackageName(resourceName, sourceLevel, complianceLevel);
                  if (status.isOK() || status.getSeverity() == IStatus.WARNING) {
                     firstLevelPackageNames.add(resourceName);
                  }
               } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resourceName)) {
                  containsADefaultPackage = true;
               } else if (!containsJavaSource && Util.isJavaLikeFileName(resourceName)) {
                  containsJavaSource = true;
               }
            }
         } catch (CoreException e) {
            // ignore
         }
      }
      }
      }*/

    if (containsJavaSource) { // no need to read source attachment if it contains no Java source (see https://bugs.eclipse
        // .org/bugs/show_bug.cgi?id=190840 )
        //         Object target = JavaModel.getTarget(this.sourcePath, true);
        //         if (target instanceof IContainer) {
        //            IContainer folder = (IContainer)target;
        //            computeRootPath(folder, firstLevelPackageNames, containsADefaultPackage, tempRoots, folder.getFullPath().segmentCount()
        // /*if external folder, this is the linked folder path*/);
        //         } else {
        //            JavaModelManager
        //                  manager = JavaModelManager.getJavaModelManager();
        ZipFile zip = null;
        try {
            zip = manager.getZipFile(this.sourcePath);
            for (Enumeration entries = zip.entries(); entries.hasMoreElements();) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName;
                if (!entry.isDirectory() && Util.isJavaLikeFileName(entryName = entry.getName())) {
                    IPath path = new Path(entryName);
                    int segmentCount = path.segmentCount();
                    if (segmentCount > 1) {
                        for (int i = 0, max = path.segmentCount() - 1; i < max; i++) {
                            if (firstLevelPackageNames.contains(path.segment(i))) {
                                tempRoots.add(path.uptoSegment(i));
                                // don't break here as this path could contain other first level package names (see https://bugs
                                // .eclipse.org/bugs/show_bug.cgi?id=74014)
                            }
                            if (i == max - 1 && containsADefaultPackage) {
                                tempRoots.add(path.uptoSegment(max));
                            }
                        }
                    } else if (containsADefaultPackage) {
                        tempRoots.add(new Path("")); //$NON-NLS-1$
                    }
                }
            }
        } catch (CoreException e) {
            // ignore
        } finally {
            manager.closeZipFile(zip); // handle null case
        }
        //         }
    }
    int size = tempRoots.size();
    if (this.rootPaths != null) {
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            tempRoots.add(new Path((String) iterator.next()));
        }
        this.rootPaths.clear();
    } else {
        this.rootPaths = new ArrayList(size);
    }
    size = tempRoots.size();
    if (size > 0) {
        ArrayList sortedRoots = new ArrayList(tempRoots);
        if (size > 1) {
            Collections.sort(sortedRoots, new Comparator() {
                public int compare(Object o1, Object o2) {
                    IPath path1 = (IPath) o1;
                    IPath path2 = (IPath) o2;
                    return path1.segmentCount() - path2.segmentCount();
                }
            });
        }
        for (Iterator iter = sortedRoots.iterator(); iter.hasNext();) {
            IPath path = (IPath) iter.next();
            this.rootPaths.add(path.toString());
        }
    }
    this.areRootPathsComputed = true;
    if (VERBOSE) {
        System.out.println("Spent " + (System.currentTimeMillis() - time) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$
        System.out.println("Found " + size + " root paths"); //$NON-NLS-1$ //$NON-NLS-2$
        int i = 0;
        for (Iterator iterator = this.rootPaths.iterator(); iterator.hasNext();) {
            System.out.println("root[" + i + "]=" + ((String) iterator.next()));//$NON-NLS-1$ //$NON-NLS-2$
            i++;
        }
    }
}

From source file:com.drgarbage.bytecodevisualizer.editors.NoSourceViewer.java

License:Apache License

private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root)
        throws JavaModelException {
    IClasspathEntry entry;/*from w ww . ja  v a  2 s . c o  m*/
    try {
        entry = root.getRawClasspathEntry();
    } catch (JavaModelException ex) {
        if (ex.isDoesNotExist())
            entry = null;
        else
            throw ex;
    }
    IPath containerPath = null;

    if (entry == null || root.getKind() != IPackageFragmentRoot.K_BINARY) {
        String s = CoreMessages.SourceAttachmentForm_message_noSource;
        createLabel(composite, MessageFormat.format(s, new Object[] { fFile.getElementName() }));
        return;
    }

    IJavaProject jproject = root.getJavaProject();
    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
        containerPath = entry.getPath();
        ClasspathContainerInitializer initializer = JavaCore
                .getClasspathContainerInitializer(containerPath.segment(0));
        IClasspathContainer container = JavaCore.getClasspathContainer(containerPath, jproject);
        if (initializer == null || container == null) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_cannotconfigure,
                    new Object[] { containerPath.toString() }));
            return;
        }
        String containerName = container.getDescription();
        IStatus status = initializer.getSourceAttachmentStatus(containerPath, jproject);
        if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_notsupported,
                    new Object[] { containerName }));
            return;
        }
        if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
            createLabel(composite, MessageFormat.format(CoreMessages.SourceAttachmentForm_readonly,
                    new Object[] { containerName }));
            return;
        }
        entry = JavaModelUtil.findEntryInContainer(container, root.getPath());
        Assert.isNotNull(entry);
    }

    Button button;

    String msg = null;
    String btnText = null;

    IPath path = entry.getSourceAttachmentPath();
    if (path == null || path.isEmpty()) {
        msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceAttachment,
                new Object[] { root.getElementName() });
        btnText = CoreMessages.SourceAttachmentForm_button_attachSource;
    } else {
        msg = MessageFormat.format(CoreMessages.SourceAttachmentForm_message_noSourceInAttachment,
                new Object[] { fFile.getElementName() });
        btnText = CoreMessages.SourceAttachmentForm_button_changeAttachedSource;
    }

    createLabel(composite, msg);
    createLabel(composite, CoreMessages.SourceAttachmentForm_message_pressButtonToAttach);
    createLabel(composite, null);

    button = createButton(composite, btnText);
    button.addSelectionListener(createButtonListener(entry, containerPath, jproject));
}

From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java

License:Open Source License

public void setGaeProjectSrc(IPackageFragmentRoot gaeProjectSrc) {
    this.gaeProjectSrc = gaeProjectSrc;
    try {//  w  w  w  .  jav  a2  s.c om
        this.packageName = inferPackageName(gaeProjectSrc.getJavaProject());
    } catch (JavaModelException e) {
        AppEngineRPCPlugin.log(e);
    }
}

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

License:Open Source License

public static IClasspathEntry getNullableRawClasspathEntryForPackageFragmentRoot(IPackageFragmentRoot root)
        throws JavaModelException {

    IClasspathEntry rawEntry = null;//  w w  w . j av  a  2  s .c om
    {
        JavaProject project = (JavaProject) root.getJavaProject();
        // force the reverse rawEntry cache to be populated
        project.getResolvedClasspath(true);
        @SuppressWarnings("rawtypes")
        Map rootPathToRawEntries = project.getPerProjectInfo().rootPathToRawEntries;
        if (rootPathToRawEntries != null) {
            rawEntry = (IClasspathEntry) rootPathToRawEntries.get(root.getPath());
        }
    }
    return rawEntry;
}

From source file:com.google.gdt.eclipse.designer.wizards.model.common.ClientPackageSelectionDialogField.java

License:Open Source License

/**
 * Return strings presentation of package.
 *//*from ww w.  ja  v  a 2s  . c o  m*/
private static String getPackageString(IPackageFragment packageFragment) {
    try {
        if (packageFragment != null) {
            IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) packageFragment.getParent();
            IJavaProject javaProject = packageFragmentRoot.getJavaProject();
            if (packageFragmentRoot.getUnderlyingResource() == javaProject.getUnderlyingResource()) {
                return javaProject.getElementName() + "/" + packageFragment.getElementName();
            } else {
                return javaProject.getElementName() + "/" + packageFragmentRoot.getElementName() + "/"
                        + packageFragment.getElementName();
            }
        }
        return "";
    } catch (Throwable e) {
        throw ReflectionUtils.propagate(e);
    }
}