Example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots

List of usage examples for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getPackageFragmentRoots.

Prototype

IPackageFragmentRoot[] getPackageFragmentRoots() throws JavaModelException;

Source Link

Document

Returns all of the package fragment roots contained in this project, identified on this project's resolved classpath.

Usage

From source file:com.liferay.ide.server.remote.ModuleTraverser.java

License:Open Source License

private static Map getComponentClasspathDependencies(final IJavaProject javaProject, final boolean isWebApp)
        throws CoreException {

    // get the raw entries
    final Map referencedRawEntries = getRawComponentClasspathDependencies(javaProject);
    final Map<IClasspathEntry, IClasspathAttribute> validRawEntries = new HashMap<IClasspathEntry, IClasspathAttribute>();

    // filter out non-valid referenced raw entries
    final Iterator i = referencedRawEntries.keySet().iterator();
    while (i.hasNext()) {
        final IClasspathEntry entry = (IClasspathEntry) i.next();
        final IClasspathAttribute attrib = (IClasspathAttribute) referencedRawEntries.get(entry);
        if (isValid(entry, attrib, isWebApp, javaProject.getProject())) {
            validRawEntries.put(entry, attrib);
        }// w  w  w . j a va 2 s.c  o m
    }

    // if we have no valid raw entries, return empty map
    if (validRawEntries.isEmpty()) {
        return Collections.EMPTY_MAP;
    }

    // XXX Would like to replace the code below with use of a public JDT API that returns
    // the raw IClasspathEntry for a given resolved IClasspathEntry (see see https://bugs.eclipse.org/bugs/show_bug.cgi?id=183995)
    // The code must currently leverage IPackageFragmentRoot to determine this
    // mapping and, because IPackageFragmentRoots do not maintain IClasspathEntry data, a prior
    // call is needed to getResolvedClasspath() and the resolved IClasspathEntries have to be stored in a Map from IPath-to-IClasspathEntry to
    // support retrieval using the resolved IPackageFragmentRoot

    // retrieve the resolved classpath
    final IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
    final Map<IPath, IClasspathEntry> pathToResolvedEntry = new HashMap<IPath, IClasspathEntry>();

    // store in a map from path to entry
    for (int j = 0; j < entries.length; j++) {
        pathToResolvedEntry.put(entries[j].getPath(), entries[j]);
    }

    final Map<IClasspathEntry, IClasspathAttribute> referencedEntries = new LinkedHashMap<IClasspathEntry, IClasspathAttribute>();

    // grab all IPackageFragmentRoots
    final IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int j = 0; j < roots.length; j++) {
        final IPackageFragmentRoot root = roots[j];
        final IClasspathEntry rawEntry = root.getRawClasspathEntry();

        // is the raw entry valid?
        IClasspathAttribute attrib = validRawEntries.get(rawEntry);
        if (attrib == null) {
            continue;
        }

        final IPath pkgFragPath = root.getPath();
        final IClasspathEntry resolvedEntry = pathToResolvedEntry.get(pkgFragPath);
        final IClasspathAttribute resolvedAttrib = checkForComponentDependencyAttribute(resolvedEntry,
                DEPENDECYATTRIBUTETYPE_DEPENDENCY_OR_NONDEPENDENCY);
        // attribute for the resolved entry must either be unspecified or it must be the
        // dependency attribute for it to be included
        if (resolvedAttrib == null || resolvedAttrib.getName().equals(CLASSPATH_COMPONENT_DEPENDENCY)) {
            // filter out resolved entry if it doesn't pass the validation rules
            if (isValid(resolvedEntry, resolvedAttrib != null ? resolvedAttrib : attrib, isWebApp,
                    javaProject.getProject())) {
                if (resolvedAttrib != null) {
                    // if there is an attribute on the sub-entry, use that
                    attrib = resolvedAttrib;
                }
                referencedEntries.put(resolvedEntry, attrib);
            }
        }
    }

    return referencedEntries;
}

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

License:Open Source License

private static IPackageFragmentRoot[] getSources(IProject project) {
    IJavaProject jProject = JavaCore.create(project);

    if (jProject == null) {
        return new IPackageFragmentRoot[0];
    }/*from w ww . j  ava 2  s .  com*/

    List<IPackageFragmentRoot> list = new ArrayList<IPackageFragmentRoot>();
    IVirtualComponent vc = ComponentCore.createComponent(project);
    IPackageFragmentRoot[] roots;

    try {
        roots = jProject.getPackageFragmentRoots();

        for (int i = 0; i < roots.length; i++) {
            if (roots[i].getKind() != IPackageFragmentRoot.K_SOURCE) {
                continue;
            }

            IResource resource = roots[i].getResource();

            if (null != resource) {
                IVirtualResource[] vResources = ComponentCore.createResources(resource);
                boolean found = false;

                for (int j = 0; !found && j < vResources.length; j++) {
                    if (vResources[j].getComponent().equals(vc)) {
                        if (!list.contains(roots[i])) {
                            list.add(roots[i]);
                        }

                        found = true;
                    }
                }
            }
        }

        if (list.size() == 0) {
            for (IPackageFragmentRoot root : roots) {
                if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    if (!list.contains(root)) {
                        list.add(root);
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        LiferayServerCore.logError(e);
    }

    return list.toArray(new IPackageFragmentRoot[list.size()]);
}

From source file:com.motorola.studio.android.codeutils.wizards.DatabaseManagementClassesCreationMainPage.java

License:Apache License

/**
 * Update project information within this wizard. Besides
 * the basic project field input update, the package fragment
 * root is determined and correctly updated in this wizard. Therefore,
 * use this method preferably to update the project so everything in the
 * wizard is updated accordingly.// w  w  w .jav a 2  s  .co  m
 * 
 * @param project {@link IProject} information to update
 * @throws JavaModelException Exception thrown when there are problems retrieving
 * the projects fragment root.
 */
private void updateProject(IProject project) throws JavaModelException {
    if (project != null) {
        // set selected project
        this.selectedProject = project;

        // update project text in case it is not already set correctly
        if ((projectChooser != null) && !projectChooser.getText().equals(project.getName())) {
            projectChooser.setText(project.getName());
        }

        // get the java project
        IJavaProject javaProject = JavaCore.create(project);
        IPackageFragmentRoot[] possibleRoots = null;
        // continue in case it does exist
        if (javaProject != null) {
            // get all possible roots
            possibleRoots = javaProject.getPackageFragmentRoots();
            // select the first one, in case it does exist
            if ((possibleRoots != null) && (possibleRoots.length > 0)) {
                // set the first one
                setPackageFragmentRoot(possibleRoots[0], true);
                if (contentProviderPackageComposite != null) {
                    contentProviderPackageComposite.setPackageFragmentRoot(possibleRoots[0], true);
                }
            }
        }
    } else {
        // update null information
        selectedProject = null;
        setPackageFragmentRoot(null, true);
        if (contentProviderPackageComposite != null) {
            contentProviderPackageComposite.setPackageFragmentRoot(null, true);
        }
    }
}

From source file:com.motorola.studio.android.codeutils.wizards.SourcePackageChooserPartWizard.java

License:Apache License

/**
 * Constructor./*from   w w  w.  j a  v  a  2  s . c  o m*/
 * 
 * @param pageName Page Name
 * @param project Project related to the wizard
 * @param defaultPackageName The name of the default package to use
 * on the package field
 * @param parent The parent composite
 * @param numColumnsGridLayout The number of columns on the grid layout
 */
public SourcePackageChooserPartWizard(String pageName, IProject project, String defaultPackageName,
        Composite parent, int numColumnsGridLayout) {
    super(true, pageName);
    // set description and title
    setDescription(CodeUtilsNLS.UI_PersistenceWizardPageDescriptionDeploy);
    setTitle(CodeUtilsNLS.UI_PersistenceWizardPageTitleDeploy);

    // set attributes
    this.numColumnsGridLayout = numColumnsGridLayout;
    if (project != null) {
        // get the java project
        IJavaProject javaProject = JavaCore.create(project);
        IPackageFragmentRoot[] possibleRoots = null;
        // continue in case it does exist
        if (javaProject != null) {
            try {
                // get all possible roots
                possibleRoots = javaProject.getPackageFragmentRoots();
                // select the first one, in case it does exist
                if ((possibleRoots != null) && (possibleRoots.length > 0)) {
                    // set the first one
                    setPackageFragmentRoot(possibleRoots[0], true);
                }
            } catch (JavaModelException e) {
                StudioLogger.error(this.getClass(), CodeUtilsNLS.Db_GenerateManagementClassesError, e);
                IStatus status = new Status(IStatus.ERROR, CodeUtilsActivator.PLUGIN_ID,
                        e.getLocalizedMessage());
                EclipseUtils.showErrorDialog(CodeUtilsNLS.Db_GenerateManagementClassesError,
                        CodeUtilsNLS.Db_GenerateManagementClassesError, status);
            }
        }
    }

    doStatusUpdate();

    // create GUI here because since this GUI is an auxiliary one, the interface does not work when created in the org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite method 
    setPackageFragmentRoot(getPackageFragmentRoot(), true);
    createContainerControls(parent, this.numColumnsGridLayout);

    boolean defaultPackageUsed = false;
    if (defaultPackageName != null) {
        // try to use the manifest package, but if this fails, use the default getPackageFragment() logic
        try {
            setPackageFragment(getPackageFragmentRoot().getPackageFragment(defaultPackageName), true);
            defaultPackageUsed = true;
        } catch (Exception e) {
            // do nothing
        }
    }
    if (!defaultPackageUsed) {
        setPackageFragment(getPackageFragment(), true);
    }
    createPackageControls(parent, this.numColumnsGridLayout);
}

From source file:com.motorola.studio.android.model.BuildingBlockModel.java

License:Apache License

/**
 * Extract source folder from selection.
 * @param selection//  ww w  .j a va  2 s  .co  m
 * @return
 * @throws CoreException
 */
private static IPackageFragmentRoot extractPackageFragmentRoot(IStructuredSelection selection)
        throws CoreException {
    IPackageFragmentRoot pack = null;
    Object selectionElement = selection.getFirstElement();

    if (selectionElement instanceof IPackageFragmentRoot) {
        pack = (IPackageFragmentRoot) selectionElement;
    } else if (selectionElement instanceof IJavaElement) {
        pack = (IPackageFragmentRoot) ((IJavaElement) selectionElement)
                .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        if (pack == null) {
            IJavaProject element = ((IJavaElement) selectionElement).getJavaProject();

            for (IPackageFragmentRoot root : element.getPackageFragmentRoots()) {
                if (root.getResource() != null) {
                    boolean isSrc = (root.getElementType()
                            & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE;
                    boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER)
                            && (root.getParent() instanceof IJavaProject);
                    if (isSrc && !isGen) {
                        pack = root;
                        break;
                    }
                }
            }
        }
    } else if (selectionElement instanceof IResource) {
        IJavaProject element = JavaCore.create(((IResource) selectionElement).getProject());

        if (element.isOpen()) {
            for (IPackageFragmentRoot root : element.getPackageFragmentRoots()) {
                if (root.getResource() != null) {
                    boolean isSrc = (root.getElementType()
                            & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE;
                    boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER)
                            && (root.getParent() instanceof IJavaProject);
                    if (isSrc && !isGen) {
                        pack = root;
                        break;
                    }
                }
            }
        }
    } else {
        IJavaProject[] allProjects = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot())
                .getJavaProjects();
        if ((allProjects != null) && (allProjects.length > 0)) {
            for (IJavaProject project : allProjects) {
                if (project.getResource().getProject().hasNature(IAndroidConstants.ANDROID_NATURE)) {
                    IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();

                    if ((roots != null) && (roots.length > 0)) {
                        boolean found = false;

                        for (IPackageFragmentRoot root : roots) {
                            boolean isSrc = (root.getElementType()
                                    & IPackageFragmentRoot.K_SOURCE) == IPackageFragmentRoot.K_SOURCE;
                            boolean isGen = root.getElementName().equals(IAndroidConstants.GEN_SRC_FOLDER)
                                    && (root.getParent() instanceof IJavaProject);
                            if (isSrc && !isGen) {
                                found = true;
                                pack = root;
                                break;
                            }
                        }

                        if (found) {
                            break;
                        }
                    }
                }
            }
        }
    }

    if (pack != null) {
        if (!pack.getJavaProject().getProject().hasNature(IAndroidConstants.ANDROID_NATURE)) {
            pack = extractPackageFragmentRoot(new TreeSelection());
        }
    }
    return pack;
}

From source file:com.mountainminds.eclemma.core.launching.EclipseLauncher.java

License:Open Source License

public Set<IPackageFragmentRoot> getOverallScope(ILaunchConfiguration configuration) throws CoreException {
    final IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    final Set<IPackageFragmentRoot> result = new HashSet<IPackageFragmentRoot>();
    for (final IJavaProject project : model.getJavaProjects()) {
        if (project.getProject().hasNature(PLUGIN_NATURE)) {
            result.addAll(Arrays.asList(project.getPackageFragmentRoots()));
        }//from ww w  .j  a  v  a 2 s  .c om
    }
    return ScopeUtils.filterJREEntries(result);
}

From source file:com.mountainminds.eclemma.core.ScopeUtils.java

License:Open Source License

/**
 * Determines all package fragment roots in the workspace.
 * //from ww  w. j ava2  s  .  c  o  m
 * @return all package fragment roots
 */
public static Set<IPackageFragmentRoot> getWorkspaceScope() throws JavaModelException {
    final Set<IPackageFragmentRoot> scope = new HashSet<IPackageFragmentRoot>();
    final IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    for (IJavaProject p : model.getJavaProjects()) {
        scope.addAll(Arrays.asList(p.getPackageFragmentRoots()));
    }
    return filterJREEntries(scope);
}

From source file:com.mountainminds.eclemma.internal.core.instr.ClassFilesStore.java

License:Open Source License

/**
 * Adds all class files of the given Java project.
 * /*  w ww. jav  a 2  s . c  o m*/
 * @param javaProject
 *          Java project to add
 * @throws JavaModelException
 *           might be thrown by the underlying Java model
 */
public void add(IJavaProject javaProject) throws JavaModelException {
    final IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        add(roots[i]);
    }
}

From source file:com.mountainminds.eclemma.internal.core.SessionExporter.java

License:Open Source License

private void createReport(IProgressMonitor monitor) throws CoreException, IOException {
    final int work = session.getScope().size();
    monitor.beginTask(NLS.bind(CoreMessages.ExportingSession_task, session.getDescription()), work * 2);
    final SessionAnalyzer analyzer = new SessionAnalyzer();
    final IJavaModelCoverage modelCoverage = analyzer.processSession(session,
            new SubProgressMonitor(monitor, work));
    final IReportVisitor formatter = createFormatter();
    formatter.visitInfo(analyzer.getSessionInfos(), analyzer.getExecutionData());
    final IReportGroupVisitor modelgroup = formatter.visitGroup(session.getDescription());
    for (IJavaProject project : modelCoverage.getProjects()) {
        final IReportGroupVisitor projectgroup = modelgroup.visitGroup(project.getElementName());
        for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
            final IBundleCoverage coverage = (IBundleCoverage) modelCoverage.getCoverageFor(root);
            if (coverage != null) {
                projectgroup.visitBundle(coverage, createSourceFileLocator(root));
                monitor.worked(1);/*  www  .  j  a v  a2  s. co m*/
            }
        }
    }
    formatter.visitEnd();
    monitor.done();
}

From source file:com.redhat.ceylon.eclipse.code.correct.CeylonCorrectionProcessor.java

License:Open Source License

public CeylonCorrectionProcessor(IMarker marker) {
    IFileEditorInput input = MarkerUtils.getInput(marker);
    if (input != null) {
        file = input.getFile();/*from   ww  w .j a va 2s . co  m*/
        IProject project = file.getProject();
        IJavaProject javaProject = JavaCore.create(project);
        TypeChecker tc = getProjectTypeChecker(project);
        if (tc != null) {
            try {
                for (IPackageFragmentRoot pfr : javaProject.getPackageFragmentRoots()) {
                    if (pfr.getPath().isPrefixOf(file.getFullPath())) {
                        IPath relPath = file.getFullPath().makeRelativeTo(pfr.getPath());
                        model = tc.getPhasedUnitFromRelativePath(relPath.toString()).getCompilationUnit();
                    }
                }
            } catch (JavaModelException e) {
                e.printStackTrace();
            }
        }
    }
    setQuickAssistProcessor(this);
}