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.xtext.ui.resource.Storage2UriMapperJavaImpl.java

License:Open Source License

/**
 * @since 2.4//from w  w  w .  j  av a 2  s. c o  m
 */
private void updateCache(IJavaProject project) {
    Set<PackageFragmentRootData> datas = newHashSet();
    try {
        if (project.exists() && project.getProject().isAccessible()) {
            for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
                boolean isCachable = root.isArchive() || root.isExternal();
                if (isCachable)
                    datas.add(getCachedData(root));
            }
        }
    } catch (JavaModelException e) {
        if (!e.isDoesNotExist())
            log.error("Error getting package fragments roots of " + project.getElementName(), e);
    } finally {
        clearCache(project, datas);
    }
}

From source file:org.eclipse.xtext.ui.tests.core.builder.impl.PackageFragmentRootWalkerTest.java

License:Open Source License

@Test
public void testTraversePackageFragmentRoot() throws Exception {
    IJavaProject project = createJavaProject("foo");
    String jarName = "JarWalkerTest.jar";
    IFile file = project.getProject().getFile(jarName);
    file.create(getClass().getResourceAsStream(jarName), true, new NullProgressMonitor());
    addJarToClasspath(project, file);// ww  w .  j av a2  s . co m

    final Set<IPath> pathes = new HashSet<IPath>();
    PackageFragmentRootWalker<Void> walker = new PackageFragmentRootWalker<Void>() {
        @Override
        protected Void handle(IJarEntryResource jarEntry, TraversalState state) {
            pathes.add(jarEntry.getFullPath());
            return null;
        }
    };
    for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
        if (root.getElementName().equals(jarName))
            walker.traverse(root, false);
    }
    assertEquals(3, pathes.size());
}

From source file:org.eclipse.xtext.xbase.ui.editor.XbaseEditorInputRedirector.java

License:Open Source License

/**
 * @param an input/* w ww . j  a  v a 2  s  .  c  o  m*/
 * 
 * @return the original source for an editor input that points to an Xtext resource copied to the output folder, the given input otherwise
 */
public IEditorInput findOriginalSourceForOuputFolderCopy(final IEditorInput input) {
    try {
        final IFile resource = ResourceUtil.getFile(input);
        if ((resource != null)) {
            boolean _isValid = this.fileExtensionProvider.isValid(resource.getFullPath().getFileExtension());
            if (_isValid) {
                final IJavaProject project = JavaCore.create(resource.getProject());
                boolean _exists = project.exists();
                if (_exists) {
                    boolean _isPrefixOf = project.getOutputLocation().isPrefixOf(resource.getFullPath());
                    if (_isPrefixOf) {
                        final IPath relative = resource.getFullPath()
                                .removeFirstSegments(project.getOutputLocation().segmentCount());
                        final Function1<IPackageFragmentRoot, Boolean> _function = (
                                IPackageFragmentRoot it) -> {
                            try {
                                int _kind = it.getKind();
                                return Boolean.valueOf((_kind == IPackageFragmentRoot.K_SOURCE));
                            } catch (Throwable _e) {
                                throw Exceptions.sneakyThrow(_e);
                            }
                        };
                        Iterable<IPackageFragmentRoot> _filter = IterableExtensions
                                .<IPackageFragmentRoot>filter(((Iterable<IPackageFragmentRoot>) Conversions
                                        .doWrapArray(project.getPackageFragmentRoots())), _function);
                        for (final IPackageFragmentRoot source : _filter) {
                            {
                                final IPath fullPath = source.getCorrespondingResource()
                                        .getProjectRelativePath().append(relative);
                                final IFile newFile = resource.getProject().getFile(fullPath);
                                boolean _exists_1 = newFile.exists();
                                if (_exists_1) {
                                    return new FileEditorInput(newFile);
                                }
                            }
                        }
                    }
                    final Function1<IClasspathEntry, Boolean> _function_1 = (IClasspathEntry it) -> {
                        int _entryKind = it.getEntryKind();
                        return Boolean.valueOf((_entryKind == IClasspathEntry.CPE_SOURCE));
                    };
                    Iterable<IClasspathEntry> _filter_1 = IterableExtensions.<IClasspathEntry>filter(
                            ((Iterable<IClasspathEntry>) Conversions.doWrapArray(project.getRawClasspath())),
                            _function_1);
                    for (final IClasspathEntry sourceFolder : _filter_1) {
                        if (((sourceFolder.getOutputLocation() != null)
                                && sourceFolder.getOutputLocation().isPrefixOf(resource.getFullPath()))) {
                            final IPath relative_1 = resource.getFullPath()
                                    .removeFirstSegments(sourceFolder.getOutputLocation().segmentCount());
                            final IPackageFragmentRoot source_1 = IterableExtensions
                                    .<IPackageFragmentRoot>head(((Iterable<IPackageFragmentRoot>) Conversions
                                            .doWrapArray(project.findPackageFragmentRoots(sourceFolder))));
                            final IPath fullPath = source_1.getCorrespondingResource().getProjectRelativePath()
                                    .append(relative_1);
                            final IFile newFile = resource.getProject().getFile(fullPath);
                            boolean _exists_1 = newFile.exists();
                            if (_exists_1) {
                                return new FileEditorInput(newFile);
                            }
                        }
                    }
                }
            }
        }
        return input;
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:org.eclipse.xtext.xbase.ui.validation.ProjectAwareUniqueClassNameValidator.java

License:Open Source License

public boolean doCheckUniqueInProject(final QualifiedName name, final JvmDeclaredType type)
        throws JavaModelException {
    final IJavaProject javaProject = this.javaProjectProvider.getJavaProject(type.eResource().getResourceSet());
    this.getContext().put(ProjectAwareUniqueClassNameValidator.OUTPUT_CONFIGS,
            this.outputConfigurationProvider.getOutputConfigurations(type.eResource()));
    final String packageName = type.getPackageName();
    final String typeName = type.getSimpleName();
    final Function1<IPackageFragmentRoot, Boolean> _function = (IPackageFragmentRoot it) -> {
        try {//from   w  w w  .ja  v  a  2 s  .c  om
            int _kind = it.getKind();
            return Boolean.valueOf((_kind == IPackageFragmentRoot.K_SOURCE));
        } catch (Throwable _e) {
            throw Exceptions.sneakyThrow(_e);
        }
    };
    final Iterable<IPackageFragmentRoot> sourceFolders = IterableExtensions.<IPackageFragmentRoot>filter(
            ((Iterable<IPackageFragmentRoot>) Conversions.doWrapArray(javaProject.getPackageFragmentRoots())),
            _function);
    IndexManager indexManager = JavaModelManager.getIndexManager();
    if (((((Object[]) Conversions.unwrapArray(sourceFolders, Object.class)).length == 0)
            || (indexManager.awaitingJobsCount() > 0))) {
        String _elvis = null;
        if (packageName != null) {
            _elvis = packageName;
        } else {
            _elvis = "";
        }
        ProjectAwareUniqueClassNameValidator.SourceTraversal _doCheckUniqueInProjectSource = this
                .doCheckUniqueInProjectSource(_elvis, typeName, type, ((IPackageFragmentRoot[]) Conversions
                        .unwrapArray(sourceFolders, IPackageFragmentRoot.class)));
        if (_doCheckUniqueInProjectSource != null) {
            switch (_doCheckUniqueInProjectSource) {
            case DUPLICATE:
                return false;
            case UNIQUE:
                return true;
            default:
                break;
            }
        } else {
        }
    }
    final HashSet<String> workingCopyPaths = CollectionLiterals.<String>newHashSet();
    ICompilationUnit[] copies = this.getWorkingCopies(type);
    if ((copies != null)) {
        for (final ICompilationUnit workingCopy : copies) {
            {
                final IPath path = workingCopy.getPath();
                if ((javaProject.getPath().isPrefixOf(path) && (!this.isDerived(workingCopy.getResource())))) {
                    boolean _exists = workingCopy.getPackageDeclaration(packageName).exists();
                    if (_exists) {
                        IType result = workingCopy.getType(typeName);
                        boolean _exists_1 = result.exists();
                        if (_exists_1) {
                            this.addIssue(type, workingCopy.getElementName());
                            return false;
                        }
                    }
                    workingCopyPaths.add(workingCopy.getPath().toString());
                }
            }
        }
    }
    char[] _xifexpression = null;
    if ((packageName == null)) {
        _xifexpression = CharOperation.NO_CHAR;
    } else {
        _xifexpression = packageName.toCharArray();
    }
    char[] _charArray = typeName.toCharArray();
    final TypeDeclarationPattern pattern = new TypeDeclarationPattern(_xifexpression,
            CharOperation.NO_CHAR_CHAR, _charArray, IIndexConstants.TYPE_SUFFIX,
            (SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE));
    final IndexQueryRequestor _function_1 = new IndexQueryRequestor() {
        @Override
        public boolean acceptIndexMatch(final String documentPath, final SearchPattern indexRecord,
                final SearchParticipant participant, final AccessRuleSet access) {
            boolean _contains = workingCopyPaths.contains(documentPath);
            if (_contains) {
                return true;
            }
            IWorkspaceRoot _root = ResourcesPlugin.getWorkspace().getRoot();
            Path _path = new Path(documentPath);
            IFile file = _root.getFile(_path);
            boolean _isDerived = ProjectAwareUniqueClassNameValidator.this.isDerived(file);
            boolean _not = (!_isDerived);
            if (_not) {
                ProjectAwareUniqueClassNameValidator.this.addIssue(type, file.getName());
                return false;
            }
            return true;
        }
    };
    IndexQueryRequestor searchRequestor = _function_1;
    try {
        SearchParticipant _defaultSearchParticipant = BasicSearchEngine.getDefaultSearchParticipant();
        IJavaSearchScope _createJavaSearchScope = BasicSearchEngine.createJavaSearchScope(
                ((IJavaElement[]) Conversions.unwrapArray(sourceFolders, IJavaElement.class)));
        PatternSearchJob _patternSearchJob = new PatternSearchJob(pattern, _defaultSearchParticipant,
                _createJavaSearchScope, searchRequestor);
        indexManager.performConcurrentJob(_patternSearchJob, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
                null);
        return true;
    } catch (final Throwable _t) {
        if (_t instanceof OperationCanceledException) {
            final OperationCanceledException oce = (OperationCanceledException) _t;
            return false;
        } else {
            throw Exceptions.sneakyThrow(_t);
        }
    }
}

From source file:org.eclipseguru.gwt.core.GwtProject.java

License:Open Source License

/**
 * @param project/*from w  ww.j  a  va  2  s  . c o m*/
 * @return
 * @throws CoreException
 */
protected GwtModule[] findModules() throws CoreException {
    final IJavaProject javaProject = getJavaProject();
    final List<GwtModule> moduleFiles = new ArrayList<GwtModule>();
    for (final IPackageFragmentRoot aRoot : javaProject.getPackageFragmentRoots()) {
        // check only in source folders. Skip others
        if (aRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
            continue;
        }
        for (final IJavaElement aPackage : aRoot.getChildren()) {
            // look only for packages. Skip others
            if (aPackage.getElementType() != IJavaElement.PACKAGE_FRAGMENT) {
                continue;
            }

            for (final Object aResource : ((IPackageFragment) aPackage).getNonJavaResources()) {
                // look only files. Skip others
                if (!(aResource instanceof IFile)) {
                    continue;
                }

                final IFile aFile = (IFile) aResource;
                if (GwtUtil.isModuleDescriptor(aFile)) {
                    moduleFiles.add(createModule(aFile));
                }
            }
        }
    }
    return moduleFiles.toArray(new GwtModule[moduleFiles.size()]);
}

From source file:org.eclipseguru.gwt.core.launch.GwtLaunchUtil.java

License:Open Source License

/**
 * Adds the source folder from the specified project to the classpath list.
 * //  w w w .  j av a  2 s .  c o  m
 * @param gwtProject
 * @param classpath
 * @throws JavaModelException
 */
private static void addSourceFolderToClasspath(final IJavaProject project, final List<String> classpath)
        throws JavaModelException {
    if ((null == project) || !project.exists()) {
        return;
    }

    final IPackageFragmentRoot[] packageFragmentRoots = project.getPackageFragmentRoots();
    for (final IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
        if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
            classpath.add(packageFragmentRoot.getResource().getLocation().toOSString());
        }
    }
}

From source file:org.eclipseguru.gwt.ui.java.GwtJavaUtil.java

License:Open Source License

/**
 * Returns all package fragement roots excluding JRE contributed roots.
 * /*from w w  w  .  j  a  v  a 2s .c o m*/
 * @param project
 * @return
 */
public static IPackageFragmentRoot[] getNonJRERoots(final IJavaProject project) {
    final List<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>();
    try {
        final IPackageFragmentRoot[] roots = project.getPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++)
            if (!isJRELibrary(roots[i])) {
                result.add(roots[i]);
            }
    } catch (final JavaModelException e) {
    }
    return result.toArray(new IPackageFragmentRoot[result.size()]);
}

From source file:org.eclipselabs.spray.runtime.xtext.ui.builder.JdtToBeBuiltComputerExt.java

License:Open Source License

@Override
public ToBeBuilt updateProject(final IProject project, IProgressMonitor monitor) throws CoreException {
    SubMonitor progress = SubMonitor.convert(monitor, 2);
    final ToBeBuilt toBeBuilt = super.updateProject(project, progress.newChild(1));
    if (!project.isAccessible() || progress.isCanceled())
        return toBeBuilt;
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject.exists()) {
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
        progress.setWorkRemaining(roots.length);
        final Set<String> previouslyBuilt = Sets.newHashSet();
        final Set<String> subsequentlyBuilt = Sets.newHashSet();
        final JarEntryLocator locator = new JarEntryLocator();
        for (final IPackageFragmentRoot root : roots) {
            if (progress.isCanceled())
                return toBeBuilt;
            if (shouldHandle(root)) {
                try {
                    final Map<String, Long> updated = Maps.newHashMap();
                    new PackageFragmentRootWalker<Boolean>() {
                        @Override
                        protected Boolean handle(IJarEntryResource jarEntry, TraversalState state) {
                            URI uri = locator.getURI(root, jarEntry, state);
                            if (isValid(uri, jarEntry)) {
                                if (wasFragmentRootAlreadyProcessed(uri))
                                    return Boolean.TRUE; // abort traversal
                                if (log.isDebugEnabled())
                                    log.debug("Scheduling: " + project.getName() + " - " + uri);
                                toBeBuilt.getToBeDeleted().add(uri);
                                toBeBuilt.getToBeUpdated().add(uri);
                            }/*from ww w  .j av  a2s  .c om*/
                            return null;
                        }

                        protected boolean wasFragmentRootAlreadyProcessed(URI uri) {
                            Iterable<Pair<IStorage, IProject>> storages = getMapper().getStorages(uri);
                            for (Pair<IStorage, IProject> pair : storages) {
                                IProject otherProject = pair.getSecond();
                                // Spray issue#127 workaround
                                if (".org.eclipse.jdt.core.external.folders".equals(otherProject.getName())
                                        && uri.lastSegment().endsWith(".ecore"))
                                    return false;
                                if (!pair.getSecond().equals(project)) {
                                    if (previouslyBuilt.contains(otherProject.getName()))
                                        return true;
                                    if (!subsequentlyBuilt.contains(otherProject.getName())) {
                                        boolean process = XtextProjectHelper.hasNature(otherProject);
                                        String otherName = otherProject.getName();
                                        if (!process) {
                                            process = otherProject.isAccessible() && otherProject.isHidden();
                                            if (process) {
                                                Long previousStamp = modificationStampCache.projectToModificationStamp
                                                        .get(otherName);
                                                if (previousStamp == null || otherProject
                                                        .getModificationStamp() > previousStamp.longValue()) {
                                                    process = false;
                                                    updated.put(otherName, otherProject.getModificationStamp());
                                                }
                                            }
                                        }
                                        if (process) {
                                            ProjectOrder projectOrder = project.getWorkspace()
                                                    .computeProjectOrder(
                                                            new IProject[] { project, otherProject });
                                            if (!projectOrder.hasCycles) {
                                                if (otherProject.equals(projectOrder.projects[0])) {
                                                    previouslyBuilt.add(otherName);
                                                    return true;
                                                } else {
                                                    subsequentlyBuilt.add(otherName);
                                                }
                                            } else {
                                                subsequentlyBuilt.add(otherName);
                                            }
                                        }
                                    }
                                }
                            }
                            return false;
                        }
                    }.traverse(root, true);
                    synchronized (modificationStampCache) {
                        modificationStampCache.projectToModificationStamp.putAll(updated);
                    }
                } catch (JavaModelException ex) {
                    if (!ex.isDoesNotExist())
                        log.error(ex.getMessage(), ex);
                }
            }
            progress.worked(1);
        }
    }
    return toBeBuilt;
}

From source file:org.eclipselabs.spray.xtext.ui.commands.SprayJavaProjectUtil.java

License:Open Source License

protected IPackageFragmentRoot getPackageFragmentRoot(IJavaProject project, String name)
        throws JavaModelException {
    for (IPackageFragmentRoot pfr : project.getPackageFragmentRoots()) {
        if (pfr.getElementName().equals(name)) {
            return pfr;
        }//from w  w w .  ja  v  a 2  s .  c  o  m
    }
    return null;
}

From source file:org.eclipselabs.stlipse.util.ProjectUtil.java

License:Open Source License

public static IPackageFragmentRoot getFirstSourceRoot(IJavaProject project) throws JavaModelException {
    IPackageFragmentRoot pkgRoot = null;
    for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            // Use the first source folder.
            pkgRoot = root;/*www. ja v a2  s . co m*/
            break;
        }
    }
    return pkgRoot;
}