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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.seasar.s2daoplugin.cache.deployment.deployer.JarComponentAutoRegisterDeployer.java

License:Apache License

protected void doDeploy(IHandler handler) throws CoreException {
    if (referenceClass == null) {
        return;/*from  ww  w. ja  v a  2  s .c  om*/
    }
    IPackageFragmentRoot jar = JavaProjectUtil.findPackageFragmentRoot(referenceClass.getType());
    if (!jar.isArchive()) {
        return;
    }
    IContainer base = jar.getResource().getParent();
    IResource[] archives = archives = base.members();
    IJavaProject project = jar.getJavaProject();
    for (int i = 0; i < archives.length; i++) {
        if (!"jar".equalsIgnoreCase(archives[i].getFileExtension())) {
            continue;
        }
        jar = project.getPackageFragmentRoot(archives[i].getFullPath().toString());
        if (!jar.exists()) {
            continue;
        }
        if (isAppliedJar(jar)) {
            handler.processPackageFragmentRoot(jar);
        }
    }
}

From source file:org.springframework.ide.eclipse.core.io.EclipsePathMatchingResourcePatternResolver.java

License:Open Source License

private Resource processRawResource(IPackageFragmentRoot[] roots, Resource resource)
        throws IOException, JavaModelException {
    if (resource instanceof FileSystemResource) {
        // This can only be something in the Eclipse workspace

        // first check the location in the project that this pattern resolver is associated with (most likely path)
        Path path = new Path(((FileSystemResource) resource).getPath());
        IPath projectLocation = this.project.getLocation();
        if (projectLocation.isPrefixOf(path)) {
            int segmentsToRemove = projectLocation.segmentCount();
            IPath projectRelativePath = path.removeFirstSegments(segmentsToRemove);
            IFile file = this.project.getFile(projectRelativePath);
            if (file != null && file.exists()) {
                return new FileResource(file);
            }//from  www .  j  av  a2 s.com
        }

        // then check the simple getFileForLocation (faster in case it is not a linked resource)
        IFile fileForLocation = ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
        if (fileForLocation != null) {
            return new FileResource(fileForLocation);
        }

        // fall back to full resolution via findFilesForLocationURI
        IResource[] allResourcesFor = ResourcesPlugin.getWorkspace().getRoot()
                .findFilesForLocationURI(resource.getURI());
        for (IResource res : allResourcesFor) {
            return new FileResource((IFile) res);
        }
    } else if (resource instanceof UrlResource) {
        URL url = resource.getURL();
        String path = url.getPath();
        int ix = path.indexOf('!');
        if (ix > 0) {
            String entryName = path.substring(ix + 1);
            path = path.substring(0, ix);

            try {
                return new ExternalFile(new File(new URI(path)), entryName, project);
            } catch (URISyntaxException e) {
            }
        } else {
            IResource[] allResourcesFor = ResourcesPlugin.getWorkspace().getRoot()
                    .findFilesForLocationURI(resource.getURI());
            for (IResource res : allResourcesFor) {
                return new FileResource((IFile) res);
            }
        }
    } else if (resource instanceof ClassPathResource) {
        String path = ((ClassPathResource) resource).getPath();
        String fileName = path;
        String packageName = "";
        int ix = path.lastIndexOf('/');
        if (ix > 0) {
            fileName = path.substring(ix + 1);
            packageName = path.substring(0, ix).replace('/', '.');
        }
        if (fileName.endsWith(ClassUtils.CLASS_FILE_SUFFIX)) {
            String typeName = packageName + "." + fileName.substring(0, fileName.length() - 6);
            for (IPackageFragmentRoot root : roots) {
                Resource storage = null;

                if ("".equals(packageName) && root.exists()) {
                    storage = processClassResource(path, fileName, typeName, root, root.getChildren());
                }

                IPackageFragment packageFragment = root.getPackageFragment(packageName);
                if (storage == null && packageFragment != null && packageFragment.exists()) {
                    storage = processClassResource(path, fileName, typeName, root,
                            packageFragment.getChildren());
                }

                if (storage != null) {
                    return storage;
                }
            }
        }

        else {
            for (IPackageFragmentRoot root : roots) {
                IStorage storage = null;

                // Look in the root of the package fragment root
                if ("".equals(packageName) && root.exists()) {
                    storage = contains(root.getNonJavaResources(), fileName);
                }

                // Check the package
                IPackageFragment packageFragment = root.getPackageFragment(packageName);
                if (storage == null && packageFragment != null && packageFragment.exists()) {
                    storage = contains(packageFragment.getNonJavaResources(), fileName);
                }

                // Check the root folder in case no package exists 
                if (storage == null) {
                    IResource rootResource = root.getUnderlyingResource();
                    if (rootResource instanceof IFolder) {
                        IFile file = ((IFolder) rootResource).getFile(path);
                        if (file.exists()) {
                            storage = file;
                        }
                    }
                }

                // Found the resource in the package fragment root? -> construct usable Resource
                if (storage != null) {
                    if (storage instanceof IFile) {
                        return new FileResource((IFile) storage);
                    } else if (storage instanceof IJarEntryResource) {

                        // Workspace jar or resource
                        if (root.getResource() != null) {
                            return new StorageResource(new ZipEntryStorage((IFile) root.getResource(),
                                    ((IJarEntryResource) storage).getFullPath().toString()), project);
                        }
                        // Workspace external jar
                        else {
                            File jarFile = root.getPath().toFile();
                            return new ExternalFile(jarFile,
                                    ((IJarEntryResource) storage).getFullPath().toString(), project);
                        }
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.springframework.ide.eclipse.internal.uaa.monitor.LibraryUsageMonitor.java

License:Open Source License

@SuppressWarnings("deprecation")
private ProductMatch readPackageFragmentRoot(IJavaProject source, IPackageFragmentRoot entry)
        throws JavaModelException {
    // Quick assertion that we only check JARs that exist
    if (!entry.exists() || !entry.isArchive()) {
        return null;
    }/*from  w w w . j a va2  s  .c  o  m*/

    // Check for previous matches or misses
    if (matches.containsKey(entry.getElementName())) {
        ProductMatch match = matches.get(entry.getElementName());
        return match;
    } else if (noMatches.contains(entry.getElementName())) {
        return null;
    }

    String groupId = null;
    String artifactId = null;
    String version = null;
    ProductInfo productInfo = null;

    JarEntryDirectory metaInfDirectory = getJarEntryDirectory(entry);

    // Step 1: Check META-INF/maven
    if (metaInfDirectory != null) {
        for (IJarEntryResource jarEntryResource : metaInfDirectory.getChildren()) {
            if ("maven".equals(jarEntryResource.getName())) {
                Product product = readMaven(jarEntryResource, entry);
                if (product != null) {
                    groupId = product.getGroupId();
                    artifactId = product.getArtifactId();
                    version = product.getVersion();
                    break;
                }
            }
        }
    }

    // Step 2: Check path if it follows the Maven convention of groupId/artifactId/version
    if (artifactId == null || groupId == null) {
        IPath jarPath = entry.getPath();

        IPath m2RepoPath = JavaCore.getClasspathVariable(M2_REPO);
        if (m2RepoPath == null) {
            m2RepoPath = ResourcesPlugin.getWorkspace().getPathVariableManager().getValue(M2_REPO);
        }
        if (m2RepoPath != null && m2RepoPath.isPrefixOf(jarPath)) {
            jarPath = jarPath.removeFirstSegments(m2RepoPath.segmentCount());
            int segments = jarPath.segmentCount();
            for (int i = 0; i < segments - 1; i++) {
                if (i == 0) {
                    groupId = jarPath.segment(i);
                } else if (i > 0 && i < segments - 3) {
                    groupId += "." + jarPath.segment(i);
                } else if (i == segments - 3) {
                    artifactId = jarPath.segment(i);
                } else if (i == segments - 2) {
                    version = jarPath.segment(i);
                }
            }
        }
    }

    // Step 3: Check for typeName match
    if (artifactId == null || groupId == null) {
        for (ProductInfo info : getProducts()) {
            String typeName = info.getTypeName();
            String packageName = "";
            if (typeName != null) {
                int i = typeName.lastIndexOf('.');
                if (i > 0) {
                    packageName = typeName.substring(0, i);
                    typeName = typeName.substring(i + 1);
                }
                IPackageFragment packageFragment = entry.getPackageFragment(packageName);
                if (packageFragment.exists()) {
                    if (packageFragment.getClassFile(typeName + ClassUtils.CLASS_FILE_SUFFIX).exists()) {
                        artifactId = info.getArtifactId();
                        groupId = info.getGroupId();
                        productInfo = info;
                        break;
                    }
                }
            }
        }
    }

    // Step 4: Obtain version from MANIFEST.MF
    if (groupId != null && artifactId != null && metaInfDirectory != null && version == null) {
        for (IJarEntryResource jarEntryResource : metaInfDirectory.getChildren()) {
            if (MANIFEST_FILE_NAME.equals(jarEntryResource.getName())) {
                version = readManifest(jarEntryResource, entry);
            }
        }
    }

    // Step 5: Obtain version from file name
    if (groupId != null && artifactId != null && version == null && entry.getPath() != null) {
        String fileName = entry.getPath().lastSegment();

        // Use regular expression to match any version number
        Matcher matcher = VERSION_PATTERN.matcher(fileName);
        if (matcher.matches()) {
            StringBuilder builder = new StringBuilder();
            for (int i = 1; i <= matcher.groupCount(); i++) {
                builder.append(matcher.group(i));
            }
            version = builder.toString();
        }
    }

    // Step 6: Construct the ProductMatch
    ProductMatch productMatch = null;
    if (productInfo == null) {
        for (ProductInfo info : getProducts()) {
            if (info.getArtifactId().equals(artifactId) && info.getGroupId().equals(groupId)) {
                productInfo = info;
                productMatch = new ProductMatch(info, version);
                break;
            }
        }
    } else {
        productMatch = new ProductMatch(productInfo, version);
    }

    // Step 7: Store ProductMatch for faster access in subsequent runs
    if (productMatch != null) {
        matches.put(entry.getElementName(), productMatch);
        return productMatch;
    } else {
        noMatches.add(entry.getElementName());
        return null;
    }
}

From source file:x10dt.search.core.pdb.X10FactGenerator.java

License:Open Source License

private void processEntries(final CompilerOptionsBuilder cmpOptBuilder, final IWorkspaceRoot wsRoot,
        final IClasspathEntry[] entries, final IJavaProject javaProject, final IResource contextResource,
        final boolean isInRuntime) throws JavaModelException, AnalysisException {
    for (final IClasspathEntry pathEntry : entries) {
        switch (pathEntry.getEntryKind()) {
        case IClasspathEntry.CPE_SOURCE:
            if (pathEntry.getPath().isRoot()) {
                cmpOptBuilder.addToSourcePath(pathEntry.getPath().toFile());
            } else {
                cmpOptBuilder.addToSourcePath(wsRoot.getLocation().append(pathEntry.getPath()).toFile());
            }//from  www . j av a2s  .  c  om
            if (pathEntry.getPath().segmentCount() > 1) {
                processSourceFolder(cmpOptBuilder, wsRoot.getFolder(pathEntry.getPath()), contextResource);
            }
            break;

        case IClasspathEntry.CPE_LIBRARY:
            try {
                final IPackageFragmentRoot pkgRoot = javaProject.findPackageFragmentRoot(pathEntry.getPath());
                if ((pkgRoot != null) && pkgRoot.exists()) {
                    final File localFile;
                    if (pkgRoot.isExternal()) {
                        localFile = pathEntry.getPath().toFile();
                    } else {
                        localFile = pkgRoot.getResource().getLocation().toFile();
                    }
                    cmpOptBuilder.addToClassPath(localFile.getAbsolutePath());
                    if (isInRuntime) {
                        cmpOptBuilder.addToSourcePath(localFile);
                    }
                    final ZipFile zipFile;
                    if (JAR_EXT.equals(pathEntry.getPath().getFileExtension())) {
                        zipFile = new JarFile(localFile);
                    } else {
                        zipFile = new ZipFile(localFile);
                    }
                    processLibrary(cmpOptBuilder, zipFile, localFile, contextResource, isInRuntime);
                }
            } catch (IOException except) {
                throw new AnalysisException(NLS.bind(Messages.XFG_JarReadingError, pathEntry.getPath()),
                        except);
            }
            break;

        case IClasspathEntry.CPE_CONTAINER:
            final IClasspathContainer cpContainer = JavaCore.getClasspathContainer(pathEntry.getPath(),
                    javaProject);
            processEntries(cmpOptBuilder, wsRoot, cpContainer.getClasspathEntries(), javaProject,
                    contextResource, true);
            break;

        case IClasspathEntry.CPE_PROJECT:
            final IResource projectResource = ResourcesPlugin.getWorkspace().getRoot()
                    .findMember(pathEntry.getPath());
            if ((projectResource != null) && projectResource.isAccessible()) {
                final IJavaProject newJavaProject = JavaCore.create((IProject) projectResource);
                processEntries(cmpOptBuilder, wsRoot, newJavaProject.getRawClasspath(), newJavaProject,
                        contextResource, false);
            }
            break;

        case IClasspathEntry.CPE_VARIABLE:
            processEntries(cmpOptBuilder, wsRoot,
                    new IClasspathEntry[] { JavaCore.getResolvedClasspathEntry(pathEntry) }, javaProject,
                    contextResource, false);
            break;
        }
    }
}

From source file:x10dt.ui.wizards.NewX10ClassPage.java

License:Open Source License

/**
 * The worker method. It will find the container, create the file if missing or just replace its contents, and open the
 * editor on the newly created file./*from  www  . j a v a2  s .com*/
 */
private void doCreateType(String typeName, IPackageFragment pkgFrag, String superClass, List<String> superIntfs,
        IProgressMonitor monitor) throws CoreException {
    monitor.beginTask("Creating " + typeName, 2);
    if (!pkgFrag.exists()) {
        String pkgName = pkgFrag.getElementName();
        IPackageFragmentRoot root = this.getPackageFragmentRoot();

        if (!root.exists()) {
            IJavaProject javaProject = getJavaProject();
            IClasspathEntry newEntry = JavaCore
                    .newSourceEntry(new Path(getPackageFragmentRootText()).makeAbsolute());
            IClasspathEntry[] entries = javaProject.getRawClasspath();
            IClasspathEntry[] newEntries = new IClasspathEntry[entries.length + 1];

            System.arraycopy(entries, 0, newEntries, 0, entries.length);
            newEntries[entries.length] = newEntry;
            javaProject.setRawClasspath(newEntries, new NullProgressMonitor());

            root = (IPackageFragmentRoot) JavaCore
                    .create(javaProject.getProject().getWorkspace().getRoot().getFolder(newEntry.getPath()));
        }
        pkgFrag = root.createPackageFragment(pkgName, true, null);
    }
    IResource resource = pkgFrag.getCorrespondingResource();
    IContainer container = (IContainer) resource;

    final IFile file = container.getFile(new Path(typeName + ".x10"));
    try {
        boolean doComments = isAddComments();
        InputStream stream = createContentStream(file, typeName, pkgFrag, superClass, superIntfs,
                isCreateMain(), isCreateConstructors(), doComments);

        if (file.exists()) {
            file.setContents(stream, true, true, monitor);
        } else {
            file.create(stream, IResource.FORCE | IResource.KEEP_HISTORY, monitor);
        }
        stream.close();
    } catch (IOException e) {
    }
    monitor.worked(1);
}