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

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

Introduction

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

Prototype

IPath getPath();

Source Link

Document

Returns the path to the innermost resource enclosing this element.

Usage

From source file:org.springframework.ide.eclipse.boot.dash.cloudfoundry.packaging.CloudApplicationArchiver.java

License:Open Source License

protected void bootRepackage(final IPackageFragmentRoot[] roots, File packagedFile) throws Exception {
    Repackager bootRepackager = new Repackager(packagedFile);
    bootRepackager.repackage(new Libraries() {

        public void doWithLibraries(LibraryCallback callBack) throws IOException {
            for (IPackageFragmentRoot root : roots) {

                if (root.isArchive()) {

                    File rootFile = new File(root.getPath().toOSString());
                    if (rootFile.exists()) {
                        callBack.library(new Library(rootFile, LibraryScope.COMPILE));
                    }/*  ww  w  .  j av a2 s  . com*/
                }
            }
        }
    });
}

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

License:Open Source License

private Resource processClassResource(String path, String fileName, String typeName, IPackageFragmentRoot root,
        IJavaElement[] children) throws JavaModelException {
    for (IJavaElement je : children) {
        if (je instanceof ICompilationUnit) {
            for (IType type : ((ICompilationUnit) je).getAllTypes()) {
                if (type.getFullyQualifiedName('$').equals(typeName)) {
                    if (root.getRawClasspathEntry().getEntryKind() == IClasspathEntry.CPE_SOURCE) {

                        IPath outputLocation = root.getRawClasspathEntry().getOutputLocation();
                        if (outputLocation == null) {
                            outputLocation = root.getJavaProject().getOutputLocation();
                        }/*from  ww w  .jav  a 2 s.co m*/
                        IResource classResource = ResourcesPlugin.getWorkspace().getRoot()
                                .findMember(outputLocation.append(path));
                        if (classResource != null) {
                            return new FileResource((IFile) classResource);
                        }
                    }
                }
            }
        } else if (je instanceof IClassFile) {
            if (((IClassFile) je).getElementName().equals(fileName)) {
                // Workspace jar or resource
                if (root.getResource() != null) {
                    return new StorageResource(new ZipEntryStorage((IFile) root.getResource(), path), project);
                }
                // Workspace external jar
                else {
                    File jarFile = root.getPath().toFile();
                    return new ExternalFile(jarFile, path, project);
                }
            }
        }
    }
    return null;
}

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   w w w  .  j  a  va  2  s  .  co m*/
        }

        // 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

private String readManifest(IJarEntryResource jarEntryResource, IPackageFragmentRoot entry) {
    InputStream is = null;// w w  w .j a v a2s.  c o m
    try {
        String fileName = "";
        if (entry.getPath() != null) {
            fileName = entry.getPath().lastSegment();
        }

        Manifest manifest = new Manifest();
        is = jarEntryResource.getContents();
        manifest.read(is);

        String bundleVersion = null;
        String implementationVersion = null;
        String specificationVersion = null;

        Attributes attributes = manifest.getMainAttributes();
        if (attributes != null) {
            bundleVersion = attributes.getValue(Constants.BUNDLE_VERSION);
            implementationVersion = attributes.getValue(IMPLEMENTATION_VERSION);
            specificationVersion = attributes.getValue(SPECIFICATION_VERSION);
        }

        Map<String, Attributes> map = manifest.getEntries();
        for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
            String entryName = it.next();
            Attributes attrs = map.get(entryName);
            for (Iterator<?> it2 = attrs.keySet().iterator(); it2.hasNext();) {
                Attributes.Name attrName = (Attributes.Name) it2.next();
                if (attrName.toString().equals(Constants.BUNDLE_VERSION)) {
                    bundleVersion = attrs.getValue(attrName);
                } else if (attrName.toString().equals(IMPLEMENTATION_VERSION)) {
                    implementationVersion = attrs.getValue(attrName);
                } else if (attrName.toString().equals(SPECIFICATION_VERSION)) {
                    implementationVersion = attrs.getValue(attrName);
                }
            }
        }

        if (bundleVersion != null) {
            return bundleVersion;
        }
        if (fileName.contains(implementationVersion)) {
            return implementationVersion;
        }
        if (fileName.contains(specificationVersion)) {
            return specificationVersion;
        }
        if (implementationVersion != null) {
            return implementationVersion;
        }
        if (specificationVersion != null) {
            return specificationVersion;
        }
    } catch (Exception e) {
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    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;
    }//  w w w  .j av  a 2s .  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:org.springframework.ide.eclipse.wizard.ui.BeanWizardPage.java

License:Open Source License

private void createAttribute(String attributeName, Hyperlink link, Text text) {
    link.setText(getDisplayText(attributeName) + ":"); //$NON-NLS-1$
    link.setUnderlined(true);//from ww w.  j a v  a2  s.com
    link.setLayoutData(new GridData());

    link.addHyperlinkListener(new HyperlinkAdapter() {
        @Override
        public void linkActivated(HyperlinkEvent e) {
            IProject project = BeanWizardPage.this.wizard.getBeanFile().getProject();
            String className = classText.getText();

            try {
                if (project.hasNature(JavaCore.NATURE_ID)) {
                    IJavaProject javaProject = JavaCore.create(project);
                    IJavaElement result = null;
                    if (className.length() > 0) {
                        result = javaProject.findType(className);
                    }

                    if (result != null) {
                        JavaUI.openInEditor(result);
                        return;
                    }

                    NewClassWizardPage page = new NewClassWizardPage();

                    int index = className.lastIndexOf(".");
                    if (index > 0) {
                        String packageName = className.substring(0, index);
                        className = className.substring(index + 1);

                        IPackageFragment[] packageFragments = javaProject.getPackageFragments();
                        for (IPackageFragment packageFragment : packageFragments) {
                            if (packageFragment.getElementName().equals(packageName)) {
                                page.setPackageFragment(packageFragment, true);

                                IPackageFragmentRoot[] packageFragmentRoots = javaProject
                                        .getAllPackageFragmentRoots();
                                for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
                                    if (packageFragmentRoot.getPath().isPrefixOf(packageFragment.getPath())) {
                                        page.setPackageFragmentRoot(packageFragmentRoot, true);
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }

                    page.setTypeName(className, false);

                    NewClassCreationWizard wizard = new NewClassCreationWizard(page, true);
                    IWorkbench workbench = PlatformUI.getWorkbench();
                    wizard.init(workbench, null);

                    Shell shell = workbench.getActiveWorkbenchWindow().getShell();
                    WizardDialog dialog = new WizardDialog(shell, wizard);
                    dialog.create();
                    dialog.getShell().setText("New Class");

                    dialog.setBlockOnOpen(true);
                    if (dialog.open() == Window.OK) {
                        validateAttribute(BeansSchemaConstants.ATTR_CLASS, className);
                    }

                }
            } catch (CoreException ex) {

            }

        }
    });

    createAttrbute(attributeName, text);
}

From source file:org.summer.dsl.xbase.ui.validation.XbaseUIValidator.java

License:Open Source License

@Nullable
protected IClasspathEntry getResolvedClasspathEntry(IJavaProject javaProject,
        @NonNull IPackageFragmentRoot root) throws JavaModelException {
    IClasspathEntry result = null;//from   w w w . j  av  a  2s  . c  om
    JavaProject castedProject = (JavaProject) javaProject;
    castedProject.getResolvedClasspath(); // force the resolved entry cache to be populated
    @SuppressWarnings("rawtypes")
    Map rootPathToResolvedEntries = castedProject.getPerProjectInfo().rootPathToResolvedEntries;
    if (rootPathToResolvedEntries != null) {
        result = (IClasspathEntry) rootPathToResolvedEntries.get(root.getPath());
        if (result == null)
            result = (IClasspathEntry) rootPathToResolvedEntries.get(root.getJavaProject().getPath());
    }

    return result;
}

From source file:org.summer.ss.ide.builder.SsBuilderParticipant.java

License:Open Source License

/**
 * @since 2.4/*from  w  w  w . java 2s  .  c  om*/
 */
protected List<IPath> getSourceFolderPathes(IProject project) {
    List<IPath> sourceFolder = Lists.newArrayList();
    try {
        if (project.isOpen() && JavaProject.hasJavaNature(project)) {
            IJavaProject javaProject = JavaCore.create(project);
            List<IPackageFragmentRoot> packageFragmentRoots = Arrays
                    .asList(javaProject.getPackageFragmentRoots());
            for (IPackageFragmentRoot packageFragmentRoot : packageFragmentRoots) {
                if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) {
                    IPath path = packageFragmentRoot.getPath();
                    sourceFolder.add(path);
                }
            }
        }
    } catch (JavaModelException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return sourceFolder;
}

From source file:org.switchyard.tools.ui.SwitchYardModelUtils.java

License:Open Source License

/**
 * Return the corresponding resource for the resource path.
 * /*from w  ww  .  ja  v  a 2s. c o m*/
 * @param project the project containing the resource (or reference)
 * @param resourcePath the location relative to the project's classpath
 * @return the corresponding resource.
 */
public static IResource getJavaResource(IProject project, String resourcePath) {
    if (project == null || resourcePath == null || resourcePath.length() == 0) {
        return null;
    }

    IJavaProject jp = JavaCore.create(project);
    if (jp == null) {
        return null;
    }
    resourcePath = URI.create(resourcePath).getPath();
    try {
        for (IPackageFragmentRoot pfr : jp.getAllPackageFragmentRoots()) {
            if (pfr.isArchive() || pfr.isExternal()) {
                continue;
            }
            final IPath path = pfr.getPath().append(resourcePath);
            IFile file = project.getWorkspace().getRoot().getFile(path);
            if (file.exists()) {
                return file;
            }
        }
    } catch (JavaModelException e) {
        return null;
    }
    return null;
}

From source file:org.switchyard.tools.ui.wizards.NewServiceTestClassWizardPage.java

License:Open Source License

private void checkPackageRoot() {
    _rootStatus = new StatusInfo();
    IPackageFragmentRoot root = getPackageFragmentRoot();
    if (root == null || _mavenProjectFacade == null) {
        return;/*  ww w .j a  va 2 s .c o m*/
    }
    if (!Arrays.asList(_mavenProjectFacade.getTestCompileSourceLocations()).contains(root.getPath())) {
        _rootStatus.setWarning(
                Messages.NewServiceTestClassWizardPage_warningMessage_sourceFolderNotConfiguredForTestSource);
    }
}