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

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

Introduction

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

Prototype

IResource getResource();

Source Link

Document

Returns the innermost resource enclosing this element.

Usage

From source file:org.springframework.ide.eclipse.beans.ui.properties.NonJavaResourceContentProvider.java

License:Open Source License

private Object[] getNonJavaResources(IPackageFragmentRoot root) throws JavaModelException {
    Object[] nonJavaResources = root.getNonJavaResources();

    // Replace JAR entries with our own wrapper
    if (root.getKind() == IPackageFragmentRoot.K_BINARY && root.getResource() instanceof IFile) {
        for (int i = 0; i < nonJavaResources.length; i++) {
            Object resource = nonJavaResources[i];
            if (resource instanceof IStorage) {
                IStorage storage = (IStorage) resource;
                nonJavaResources[i] = new ZipEntryStorage((IFile) root.getResource(),
                        storage.getFullPath().toString());
            }//  ww w . j  a  v a2  s.  c o m
        }
    }
    return nonJavaResources;
}

From source file:org.springframework.ide.eclipse.beans.ui.properties.NonJavaResourceContentProvider.java

License:Open Source License

protected boolean isInternalLibrary(IJavaProject project, IPackageFragmentRoot root) {
    if (root.isArchive()) {
        IResource resource = root.getResource();
        if (resource != null) {
            IProject jarProject = resource.getProject();
            IProject container = root.getJavaProject().getProject();
            return container.equals(jarProject);
        }/*from   www  .  j av a  2 s .  co m*/
        return false;
    }
    return true;
}

From source file:org.springframework.ide.eclipse.beans.ui.properties.NonJavaResourceContentProvider.java

License:Open Source License

protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) {
    IResource resource = root.getResource();
    return (resource instanceof IProject);
}

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

License:Open Source License

/**
 *
 * Determines if the given package fragment root corresponds to the class
 * path entry path.// w  w w.j  ava2s.  c  o  m
 * <p/>
 * Note that different package fragment roots may point to the same class
 * path entry.
 * <p/>
 * Example:
 * <p/>
 * A Java project may have the following package fragment roots:
 * <p/>
 * - src/main/java
 * <p/>
 * - src/main/resources
 * <p/>
 * Both may be using the same output folder:
 * <p/>
 * target/classes.
 * <p/>
 * In this case, the output folder will have a class path entry -
 * target/classes - and it will be the same for both roots, and this method
 * will return true for both roots if passed the entry for target/classes
 *
 * @param root
 *            to check if it corresponds to the given class path entry path
 * @param entry
 * @return true if root is at the given entry
 */
private static boolean isRootAtEntry(IPackageFragmentRoot root, IPath entry) {
    try {
        IClasspathEntry cpe = root.getRawClasspathEntry();
        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
            IPath outputLocation = cpe.getOutputLocation();
            if (outputLocation == null) {
                outputLocation = root.getJavaProject().getOutputLocation();
            }

            IPath location = ResourcesPlugin.getWorkspace().getRoot().findMember(outputLocation).getLocation();
            if (entry.equals(location)) {
                return true;
            }
        }
    } catch (JavaModelException e) {
        BootDashActivator.log(e);
    }

    IResource resource = root.getResource();
    if (resource != null && entry.equals(resource.getLocation())) {
        return true;
    }

    IPath path = root.getPath();
    if (path != null && entry.equals(path)) {
        return true;
    }

    return false;
}

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  www . ja va  2 s . com*/
                        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 www.java2 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.quickfix.processors.ClassAttributeQuickAssistProcessor.java

License:Open Source License

public ICompletionProposal[] computeQuickAssistProposals(IQuickAssistInvocationContext invocationContext) {
    List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

    // find similar classes and add as proposals
    String className;/*from  w ww .ja v a  2 s. c o m*/
    int lastDotPos = text.lastIndexOf(".");
    if (lastDotPos < 0) {
        className = text;
    } else {
        className = text.substring(lastDotPos + 1);
    }

    try {
        SimilarCUFindingVisitor visitor = new SimilarCUFindingVisitor(className);
        IPackageFragmentRoot[] fragmentRoots = javaProject.getAllPackageFragmentRoots();
        for (IPackageFragmentRoot fragmentRoot : fragmentRoots) {
            if (fragmentRoot instanceof JarPackageFragmentRoot) {
                visitor.visitJar((JarPackageFragmentRoot) fragmentRoot);
            }
            IResource resource = fragmentRoot.getResource();
            if (resource != null) {
                resource.accept(visitor);
            }
        }
        List<String> suggestedClassNames = visitor.getSuggestedClassNames();
        for (String suggestedClassName : suggestedClassNames) {
            proposals.add(new RenameToSimilarNameQuickFixProposal(suggestedClassName, offset, length,
                    missingEndQuote));
        }

        proposals.add(new CreateNewClassQuickFixProposal(offset, length, text, missingEndQuote, javaProject,
                propertyNames, numConstructorArgs));

        return proposals.toArray(new ICompletionProposal[proposals.size()]);
    } catch (CoreException e1) {
        StatusHandler.log(new Status(Status.ERROR, Activator.PLUGIN_ID, "Cound not compute proposals."));
    }

    return new ICompletionProposal[0];
}

From source file:org.summer.dsl.builder.trace.JarEntryAwareTrace.java

License:Open Source License

protected URI resolvePath(IJavaProject javaProject, URI path) {
    try {//from   ww  w  .  j a  va2  s .c o m
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots())
            if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                IResource resource = root.getResource();
                if (resource instanceof IFolder) {
                    IFolder folder = (IFolder) resource;
                    IResource candidate = folder.findMember(path.toString());
                    if (candidate != null && candidate.exists())
                        return URI.createPlatformResourceURI(resource.getFullPath() + "/" + path, true);
                }
            }
    } catch (JavaModelException e) {
        log.error(e);
    }
    return null;
}

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

License:Open Source License

@Override
public boolean performFinish() {
    if (_filePage != null) {
        _fNewFile = _filePage.createNewFile();
        if (_fNewFile == null) {
            return false;
        }/*from   w  ww  .ja  va 2  s  . com*/

        String charSet = "UTF-8"; //$NON-NLS-1$
        String wsdlPrefix = "wsdl"; //$NON-NLS-1$
        Vector<?> namespaces = _optionsPage.getNamespaceInfo();

        String prefix = _optionsPage.getPrefix();
        String definitionName = _optionsPage.getDefinitionName();

        URI uri2 = URI.createPlatformResourceURI(_fNewFile.getFullPath().toOSString(), false);
        ResourceSet resourceSet = new ResourceSetImpl();
        WSDLResourceImpl resource = (WSDLResourceImpl) resourceSet.createResource(URI.createURI("*.wsdl")); //$NON-NLS-1$
        resource.setURI(uri2);

        WSDLFactoryImpl factory = new WSDLFactoryImpl();
        DefinitionImpl definition = (DefinitionImpl) factory.createDefinition();
        resource.getContents().add(definition);

        definition.setTargetNamespace(_optionsPage.getTargetNamespace());
        definition.setLocation(_fNewFile.getLocation().toString());
        definition.setEncoding(charSet);
        definition.setQName(new QName(wsdlPrefix, definitionName));
        definition.addNamespace(prefix, _optionsPage.getTargetNamespace());

        for (int i = 0; i < namespaces.size(); i++) {
            NamespaceInfo info = (NamespaceInfo) namespaces.get(i);

            if (info.prefix.length() > 0) {
                definition.addNamespace(info.prefix, info.uri);
            } else {
                definition.addNamespace(null, info.uri);
            }
        }

        definition.updateElement(true);
        try {
            if (_optionsPage.getCreateSkeletonBoolean()) {
                if (_optionsPage.isSoapDocLiteralProtocol()) {
                    CreateWSDLElementHelper.PART_TYPE_OR_DEFINITION = CreateWSDLElementHelper.PART_INFO_ELEMENT_DECLARATION;
                } else {
                    CreateWSDLElementHelper.PART_TYPE_OR_DEFINITION = CreateWSDLElementHelper.PART_INFO_TYPE_DEFINITION;
                }

                CreateWSDLElementHelper.serviceName = definitionName;

                // use protocol name (as opposed to protocol label) in port
                // name
                String protocolName = new String();
                String protocol = _optionsPage.getProtocol();
                ContentGeneratorUIExtensionRegistry registry = WSDLEditorPlugin.getInstance()
                        .getContentGeneratorUIExtensionRegistry();
                ContentGeneratorUIExtension extension = registry.getExtensionForLabel(protocol);
                if (extension != null) {
                    protocolName = extension.getName();
                }
                CreateWSDLElementHelper.portName = definitionName + protocolName;
                createPortType(definitionName, wsdlPrefix, prefix, charSet, factory);

                Service service = CreateWSDLElementHelper.createService(definition);

                // Generate Binding
                Iterator<?> bindingIt = definition.getEBindings().iterator();
                Binding binding = null;
                if (bindingIt.hasNext()) {
                    binding = (Binding) bindingIt.next();
                }

                _generator.setDefinition(definition);
                _generator.setBinding(binding);
                Port port = (Port) service.getEPorts().iterator().next();
                _generator.setName(ComponentReferenceUtil.getName(port.getEBinding()));
                _generator.setRefName(ComponentReferenceUtil.getPortTypeReference(port.getEBinding()));
                _generator.setOverwrite(true);
                _generator.generateBinding();
                _generator.generatePortContent();
            }
            resource.save(null);
        } catch (Exception e) {
            System.out.println("\nCould not write new WSDL file in WSDL Wizard: " + e); //$NON-NLS-1$
        }

        if (getSelection().getFirstElement() instanceof IPackageFragmentRoot) {
            IPackageFragmentRoot root = (IPackageFragmentRoot) getSelection().getFirstElement();
            IResource pkgresource = root.getResource();
            if (pkgresource == null) {
                IJavaElement element = root.getParent();
                pkgresource = element.getResource();
            }
            if (_fNewFile instanceof IFile) {
                pkgresource = ((IFile) _fNewFile).getParent();
            }
            if (pkgresource instanceof IFolder) {
                IFolder folder = (IFolder) pkgresource;
                IFolder parent = (IFolder) folder.getParent();
                _createdFilePath = _fNewFile.getProjectRelativePath()
                        .makeRelativeTo(parent.getProjectRelativePath()).toPortableString();
            }
        } else {
            _createdFilePath = _fNewFile.getProjectRelativePath().toPortableString();
        }

        if (_fOpenEditorWhenFinished) {
            openEditor(_fNewFile);
        }

        return true;
    }
    return false;
}

From source file:org.teavm.eclipse.debugger.TeaVMSourcePathComputerDelegate.java

License:Apache License

@Override
public ISourceContainer[] computeSourceContainers(ILaunchConfiguration config, IProgressMonitor monitor)
        throws CoreException {
    List<ISourceContainer> sourceContainers = new ArrayList<>();
    IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
    for (IProject project : projects) {
        if (!project.isOpen()) {
            continue;
        }/*from   ww w . ja v a  2 s .com*/
        if (project.hasNature(JavaCore.NATURE_ID)) {
            IJavaProject javaProject = JavaCore.create(project);
            for (IPackageFragmentRoot fragmentRoot : javaProject.getAllPackageFragmentRoots()) {
                if (fragmentRoot.getResource() instanceof IFolder) {
                    sourceContainers.add(new FolderSourceContainer((IFolder) fragmentRoot.getResource(), true));
                }
            }
            for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
                switch (entry.getEntryKind()) {
                case IClasspathEntry.CPE_CONTAINER:
                    sourceContainers.add(new ClasspathContainerSourceContainer(entry.getPath()));
                    break;
                case IClasspathEntry.CPE_LIBRARY:
                    sourceContainers.add(new ExternalArchiveSourceContainer(entry.getPath().toString(), true));
                    if (entry.getSourceAttachmentPath() != null) {
                        System.out.println(entry.getSourceAttachmentPath());
                        sourceContainers.add(new ExternalArchiveSourceContainer(
                                entry.getSourceAttachmentPath().toString(), true));
                        sourceContainers
                                .add(new DirectorySourceContainer(entry.getSourceAttachmentPath(), true));
                    }
                    break;
                case IClasspathEntry.CPE_SOURCE:
                    sourceContainers.add(new DirectorySourceContainer(entry.getPath(), true));
                    break;
                }
            }
        }
    }
    IRuntimeClasspathEntry[] entries = JavaRuntime.computeUnresolvedSourceLookupPath(config);
    IRuntimeClasspathEntry[] resolved = JavaRuntime.resolveSourceLookupPath(entries, config);
    sourceContainers.addAll(Arrays.asList(JavaRuntime.getSourceContainers(resolved)));
    return sourceContainers.toArray(new ISourceContainer[sourceContainers.size()]);
}