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: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 {/*from  w w w .  ja  v  a 2 s .c o 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.markers.UpdateAJMarkers.java

License:Open Source License

/**
* creates new markers for an entire project
*//*  ww w .java  2s  .c  om*/
private void addMarkersForProject(IProgressMonitor monitor) {
    if (!model.hasModel()) {
        return;
    }
    try {
        IJavaProject jProject = JavaCore.create(project);
        IPackageFragmentRoot[] fragRoots = jProject.getPackageFragmentRoots();
        SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, fragRoots.length);
        subMonitor.beginTask("Add markers for " + project.getName(), fragRoots.length);
        for (int i = 0; i < fragRoots.length; i++) {
            if (fragRoots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                IJavaElement[] frags = fragRoots[i].getChildren();
                for (int j = 0; j < frags.length; j++) {
                    Set<String> completedCUNames = new HashSet<String>(frags.length, 1.0f);
                    IJavaElement[] cus = ((IPackageFragment) frags[j]).getChildren();
                    for (int k = 0; k < cus.length; k++) {
                        // ignore any class files in the source folder (Bug 258698)
                        if (cus[k].getElementType() == IJavaElement.COMPILATION_UNIT) {
                            // ignore duplicate compilation units
                            IResource resource = cus[k].getResource();
                            if (!completedCUNames.contains(resource.getName())) {
                                subMonitor.subTask("Add markers for " + cus[k].getElementName());
                                addMarkersForFile((ICompilationUnit) cus[k],
                                        ((ICompilationUnit) cus[k]).getResource());
                                completedCUNames.add(resource.getName());
                                fileCount++;
                            }
                            if (subMonitor.isCanceled()) {
                                throw new OperationCanceledException();
                            }
                        }
                    }
                }
                subMonitor.worked(1);
            }
        }
    } catch (JavaModelException e) {
    }

}

From source file:org.eclipse.ajdt.internal.ui.refactoring.pullout.AspectInputContentAssistProcessor.java

License:Open Source License

public AspectInputContentAssistProcessor(IJavaProject project) throws JavaModelException {
    super(requestor = new TypeCompletionRequestor(/*enableBaseTypes*/false, /*enableVoid*/false,
            /*fullyQualify*/true));
    requestor.setProject(project);/* ww w . j ava 2 s  . c  om*/
    setPackageFragment(project.getPackageFragmentRoots()[0].getPackageFragment(""));
    this.javaProject = project;
}

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

License:Open Source License

private IContainer[] getOutputContainers(IJavaProject javaProject) throws CoreException {
    Set<IPath> outputPaths = new HashSet<IPath>();
    boolean includeDefaultOutputPath = false;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++) {
        if (roots[i] != null) {
            IClasspathEntry cpEntry = roots[i].getRawClasspathEntry();
            if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                IPath location = cpEntry.getOutputLocation();
                if (location != null)
                    outputPaths.add(location);
                else
                    includeDefaultOutputPath = true;
            }/*from ww  w.ja v  a2  s. c o  m*/
        }
    }

    if (includeDefaultOutputPath) {
        // Use default output location
        outputPaths.add(javaProject.getOutputLocation());
    }

    // Convert paths to containers
    Set<IContainer> outputContainers = new HashSet<IContainer>(outputPaths.size());
    Iterator<IPath> iter = outputPaths.iterator();
    while (iter.hasNext()) {
        IPath path = iter.next();
        if (javaProject.getProject().getFullPath().equals(path))
            outputContainers.add(javaProject.getProject());
        else {
            IFolder outputFolder = createFolderHandle(path);
            if (outputFolder == null || !outputFolder.isAccessible()) {
                String msg = JarPackagerMessages.JarFileExportOperation_outputContainerNotAccessible;
                addToStatus(new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                        IJavaStatusConstants.INTERNAL_ERROR, msg, null)));
            } else
                outputContainers.add(outputFolder);
        }
    }
    return outputContainers.toArray(new IContainer[outputContainers.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.
 */// w  w w.jav  a  2s  . co  m
protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
    if (!project.getProject().isOpen())
        return NO_CHILDREN;

    IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
    List list = new ArrayList(roots.length);
    // filter out package fragments that correspond to projects and
    // replace them with the package fragments directly
    for (int i = 0; i < roots.length; i++) {
        IPackageFragmentRoot root = roots[i];
        if (isProjectPackageFragmentRoot(root)) {
            Object[] children = root.getChildren();
            for (int k = 0; k < children.length; k++)
                list.add(children[k]);
        } else if (hasChildren(root)) {
            list.add(root);
        }
    }
    return concatenate(list.toArray(), project.getNonJavaResources());
}

From source file:org.eclipse.andmore.android.codeutils.wizards.SourcePackageChooserPartWizard.java

License:Apache License

/**
 * Constructor./*w  ww.  j a va2s.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) {
                AndmoreLogger.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:org.eclipse.che.jdt.util.JavaModelUtil.java

License:Open Source License

private static void addAllCus(HashSet<ICompilationUnit> collector, IJavaElement javaElement)
        throws JavaModelException {
    switch (javaElement.getElementType()) {
    case IJavaElement.JAVA_PROJECT:
        IJavaProject javaProject = (IJavaProject) javaElement;
        IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < packageFragmentRoots.length; i++)
            addAllCus(collector, packageFragmentRoots[i]);
        return;/* w w  w .  j  av a 2  s  .c  o m*/

    case IJavaElement.PACKAGE_FRAGMENT_ROOT:
        IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) javaElement;
        if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
            return;
        IJavaElement[] packageFragments = packageFragmentRoot.getChildren();
        for (int j = 0; j < packageFragments.length; j++)
            addAllCus(collector, packageFragments[j]);
        return;

    case IJavaElement.PACKAGE_FRAGMENT:
        IPackageFragment packageFragment = (IPackageFragment) javaElement;
        collector.addAll(Arrays.asList(packageFragment.getCompilationUnits()));
        return;

    case IJavaElement.COMPILATION_UNIT:
        collector.add((ICompilationUnit) javaElement);
        return;

    default:
        IJavaElement cu = javaElement.getAncestor(IJavaElement.COMPILATION_UNIT);
        if (cu != null)
            collector.add((ICompilationUnit) cu);
    }
}

From source file:org.eclipse.che.plugin.java.server.JavaNavigation.java

License:Open Source License

private List<PackageFragmentRoot> toPackageRoots(IJavaProject javaProject, boolean includePackages)
        throws JavaModelException {
    IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
    List<PackageFragmentRoot> result = new ArrayList<>();
    for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
        if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            PackageFragmentRoot root = DtoFactory.newDto(PackageFragmentRoot.class);
            root.setPath(packageFragmentRoot.getPath().toOSString());
            root.setProjectPath(packageFragmentRoot.getJavaProject().getPath().toOSString());
            if (includePackages) {
                root.setPackageFragments(toPackageFragments(packageFragmentRoot));
            }//w ww. jav  a 2  s .  c om
            result.add(root);
        }
    }
    return result;
}

From source file:org.eclipse.e4.tools.emf.editor3x.PDEClassContributionProvider.java

License:Open Source License

@SuppressWarnings("restriction")
public void findContribution(final Filter filter, final ContributionResultHandler handler) {
    boolean followReferences = true;
    if (filter instanceof FilterEx) {
        FilterEx filterEx = (FilterEx) filter;
        if (filterEx.getSearchScope().contains(ResourceSearchScope.PROJECT)
                && !filterEx.getSearchScope().contains(ResourceSearchScope.REFERENCES)) {
            followReferences = false;//from   w  w w. j av a 2  s. c  om
        }

    }
    IJavaSearchScope scope = null;
    if (followReferences == false) {
        IJavaProject javaProject = JavaCore.create(filter.project);
        IPackageFragmentRoot[] roots;
        try {
            roots = javaProject.getPackageFragmentRoots();
            scope = SearchEngine.createJavaSearchScope(roots, false);
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    } else {
        // filter.project may be null in the live editor
        scope = filter.project != null ? PDEJavaHelper.getSearchScope(filter.project)
                : SearchEngine.createWorkspaceScope();
    }
    char[] packageName = null;
    char[] typeName = null;
    String currentContent = filter.namePattern;
    int index = currentContent.lastIndexOf('.');

    if (index == -1) {
        // There is no package qualification
        // Perform the search only on the type name
        typeName = currentContent.toCharArray();
        if (currentContent.startsWith("*")) {
            if (!currentContent.endsWith("*")) {
                currentContent += "*";
            }
            typeName = currentContent.toCharArray();
            packageName = "*".toCharArray();
        }

    } else if ((index + 1) == currentContent.length()) {
        // There is a package qualification and the last character is a
        // dot
        // Perform the search for all types under the given package
        // Pattern for all types
        typeName = "".toCharArray(); //$NON-NLS-1$
        // Package name without the trailing dot
        packageName = currentContent.substring(0, index).toCharArray();
    } else {
        // There is a package qualification, followed by a dot, and 
        // a type fragment
        // Type name without the package qualification
        typeName = currentContent.substring(index + 1).toCharArray();
        // Package name without the trailing dot
        packageName = currentContent.substring(0, index).toCharArray();
    }

    //      char[] packageName = "at.bestsolution.e4.handlers".toCharArray();
    //      char[] typeName = "*".toCharArray();

    TypeNameRequestor req = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            // Accept search results from the JDT SearchEngine
            String cName = new String(simpleTypeName);
            String pName = new String(packageName);
            //            String label = cName + " - " + pName; //$NON-NLS-1$
            String content = pName.length() == 0 ? cName : pName + "." + cName; //$NON-NLS-1$

            //            System.err.println("Found: " + label + " => " + pName + " => " + path);

            IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);

            if (resource != null) {
                IProject project = resource.getProject();
                IFile f = project.getFile("/META-INF/MANIFEST.MF");

                if (f != null && f.exists()) {
                    BufferedReader r = null;
                    try {
                        InputStream s = f.getContents();
                        r = new BufferedReader(new InputStreamReader(s));
                        String line;
                        while ((line = r.readLine()) != null) {
                            if (line.startsWith("Bundle-SymbolicName:")) {
                                int start = line.indexOf(':');
                                int end = line.indexOf(';');
                                if (end == -1) {
                                    end = line.length();
                                }
                                ContributionData data = new ContributionData(
                                        line.substring(start + 1, end).trim(), content, "Java", null);
                                handler.result(data);
                                break;
                            }
                        }

                    } catch (CoreException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (r != null) {
                            try {
                                r.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            //Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) : PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
            //addProposalToCollection(c, startOffset, length, label, content, image);
        }
    };

    try {
        searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName,
                SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS,
                scope, req, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.eclipse.e4.tools.ui.designer.utils.ClassLoaderHelper.java

License:Open Source License

private static URL findResourceURL(IJavaProject javaProject, Set<IJavaProject> visited, boolean isFirstProject,
        String name) {/*from   w ww  .j  av a  2s . c o  m*/
    if (visited.contains(javaProject))
        return null;
    visited.add(javaProject);
    try {
        IPath outPath = javaProject.getProject().getLocation().removeLastSegments(1)
                .append(javaProject.getOutputLocation());
        outPath = outPath.addTrailingSeparator();
        {
            URL url = toURL(outPath.append(name));
            if (url != null) {
                return url;
            }
        }
        for (IPackageFragmentRoot fragment : javaProject.getPackageFragmentRoots()) {
            if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
                URL url = toURL(fragment.getResource().getLocation().append(name));
                if (url != null) {
                    return url;
                }
            }
        }
        // urls.add(out);
        IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
        for (IClasspathEntry entry : entries) {
            switch (entry.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY: {
                // TODO
                IClasspathEntry resolveEntry = JavaCore.getResolvedClasspathEntry(entry);
                File file = resolveEntry.getPath().toFile();
                IPath path = resolveEntry.getPath();
                if (!file.exists()) {
                    String projectName = path.segment(0);
                    IProject project = javaProject.getProject().getWorkspace().getRoot()
                            .getProject(projectName);
                    path = project.getLocation().append(path.removeFirstSegments(1));
                }
                String spec = "jar:file:" + path.toString() + "!/" + name;
                try {
                    URL url2 = new URL(spec);
                    url2.getContent();
                    return url2;
                } catch (Exception e) {
                }
            }
                break;
            case IClasspathEntry.CPE_CONTAINER:

                break;
            case IClasspathEntry.CPE_VARIABLE: {
                {
                    // TODO
                    URL url = toURL(outPath.append(name));
                    if (url != null) {
                        return url;
                    }
                }
            }
                break;
            case IClasspathEntry.CPE_PROJECT: {
                if (isFirstProject || entry.isExported()) {
                    URL url = findResourceURL(getJavaProject(entry), visited, false, name);
                    if (url != null) {
                        return url;
                    }
                }
                break;
            }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return null;
}