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.seasar.s2daoplugin.util.JavaUtil.java

License:Apache License

private static IPath[] getOutputLocationPaths(IJavaProject project) {
    IPackageFragmentRoot[] roots;/*from w  w  w. j  ava 2  s. c o m*/
    try {
        roots = project.getPackageFragmentRoots();
    } catch (JavaModelException e) {
        return null;
    }
    Set ret = new HashSet();
    try {
        ret.add(project.getOutputLocation());
    } catch (JavaModelException e) {
        return new IPath[0];
    }
    for (int i = 0; i < roots.length; i++) {
        if (roots[i].isArchive()) {
            continue;
        }
        try {
            IPath output = roots[i].getRawClasspathEntry().getOutputLocation();
            if (output != null) {
                ret.add(output);
            }
        } catch (JavaModelException ignore) {
        }
    }
    return (IPath[]) ret.toArray(new IPath[ret.size()]);
}

From source file:org.seasar.sastrutsplugin.util.SAStrutsUtil.java

License:Apache License

private static String getRootPackageName(IProject project) {
    String conventionDiconPath = PreferencesUtil.getPreferenceStoreOfProject(project)
            .getString(SAStrutsConstants.PREF_CONVENTION_DICON_PATH);
    File conventionDicon = ((Path) project.getFile(conventionDiconPath).getLocation()).toFile();
    try {/* w  w w  .ja  v  a 2s  .co m*/
        DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance();
        dbfactory.setNamespaceAware(true);
        DocumentBuilder builder = dbfactory.newDocumentBuilder();
        builder.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
                if (publicId.equals(SAStrutsConstants.PUBLIC_ID_DICON_24)
                        && systemId.equals(SAStrutsConstants.SYSTEM_ID_DICON_24)) {
                    try {
                        InputSource source = new InputSource(Activator.getDefault().getBundle()
                                .getEntry(SAStrutsConstants.DTD_DICON_24).openStream());
                        return source;
                    } catch (IOException e) {
                        LogUtil.log(Activator.getDefault(), e);
                    }
                }
                return null;
            }
        });
        Document doc = builder.parse(conventionDicon);
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(SAStrutsConstants.ROOTPACKAGE_XPATH);
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        if (nodes.getLength() == 0) {
            String title = Messages.ERROR_DIALOG_ROOT_PACKAGE_NAME_TITLE;
            String msg = Messages.ERROR_DIALOG_ROOT_PACKAGE_NAME_NOT_FOUND_MESSAGE;
            MessageDialog.openError(getShell(), title, msg);
        } else if (nodes.getLength() == 1) {
            return StringUtil.decodeString(nodes.item(0).getNodeValue());
        } else {
            for (int i = 0; i < nodes.getLength(); i++) {
                String rootPackageName = StringUtil.decodeString(nodes.item(i).getNodeValue());
                IJavaProject javaProject = JavaCore.create(project);
                IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
                for (int j = 0; j < roots.length; j++) {
                    if (roots[j].getKind() == IPackageFragmentRoot.K_SOURCE) {
                        IPackageFragment packageFragment = roots[j].getPackageFragment(
                                rootPackageName + "." + SAStrutsConstants.LOWER_CASE_ACTION);
                        if (packageFragment.exists()) {
                            return rootPackageName;
                        }
                    }
                }
            }
        }
    } catch (XPathExpressionException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    } catch (DOMException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    } catch (ParserConfigurationException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    } catch (SAXException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    } catch (IOException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    } catch (JavaModelException e) {
        LogUtil.log(Activator.getDefault(), e);
        showConventionDiconAnalyzeErrorDialog(e);
    }
    return null;
}

From source file:org.springframework.ide.eclipse.beans.ui.editor.util.BeansJavaCompletionUtils.java

License:Open Source License

private static IPackageFragment getPackageFragment(IJavaProject project, String prefix)
        throws JavaModelException {
    int dot = prefix.lastIndexOf('.');
    if (dot > -1) {
        String packageName = prefix.substring(0, dot);
        for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
            IPackageFragment p = root.getPackageFragment(packageName);
            if (p != null && p.exists()) {
                return p;
            }//from  w ww .  j  av a  2s . c o m
        }
        IPackageFragment[] packages = project.getPackageFragments();
        for (IPackageFragment p : packages) {
            if (p.getElementName().equals(packageName))
                return p;
        }
    } else {
        for (IPackageFragmentRoot p : project.getAllPackageFragmentRoots()) {
            if (p.getKind() == IPackageFragmentRoot.K_SOURCE) {
                return p.getPackageFragment("");
            }
        }
    }
    return project.getPackageFragments()[0];
}

From source file:org.springframework.ide.eclipse.beans.ui.namespaces.DefaultNamespaceDefinition.java

License:Open Source License

private String getDefaultSchemaLocationFromClasspath(IResource resource) {
    IJavaProject jp = JdtUtils.getJavaProject(resource);
    Set<String> existingLocations = new HashSet<String>();
    try {//from   ww  w  .j  a v a 2  s  .c  om
        for (Map.Entry<Object, Object> entry : uriMapping.entrySet()) {

            // Check that we are looking for relevant entries only; e.g. util, tool and beans are in the same
            // package
            if (((String) entry.getKey()).startsWith(uri)) {
                String fileLocation = (String) entry.getValue();

                // Get the package name from the location
                String packageName = "";
                int ix = fileLocation.lastIndexOf('/');
                if (ix > 0) {
                    packageName = fileLocation.substring(0, ix).replace('/', '.');
                }

                // Search in all project packages
                for (IPackageFragmentRoot root : jp.getPackageFragmentRoots()) {
                    IPackageFragment pf = root.getPackageFragment(packageName);
                    if (pf.exists()) {
                        for (Object obj : pf.getNonJavaResources()) {
                            // Entry is coming from a JAR file on the classpath
                            if (obj instanceof JarEntryFile
                                    && ("/" + fileLocation)
                                            .equals((((JarEntryFile) obj).getFullPath().toString()))
                                    && locations.contains(entry.getKey())) {
                                existingLocations.add((String) entry.getKey());
                            }
                            // Entry is coming from the local project
                            else if (obj instanceof IFile && fileLocation.equals(
                                    pf.getElementName().replace('.', '/') + "/" + ((IFile) obj).getName())
                                    && locations.contains(entry.getKey())) {
                                existingLocations.add((String) entry.getKey());
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        // We have a safe fall-back
    }

    // Search for the highest version among the existing resources
    String highestLocation = null;
    Version version = Version.MINIMUM_VERSION;
    for (String location : existingLocations) {
        Version tempVersion = Version.MINIMUM_VERSION;
        Matcher matcher = VERSION_PATTERN.matcher(location);
        if (matcher.matches()) {
            tempVersion = new Version(matcher.group(1));
        }
        if (tempVersion.compareTo(version) >= 0) {
            version = tempVersion;
            highestLocation = location;
        }
    }
    return highestLocation;
}

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

License:Open Source License

protected Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
    if (!project.getProject().isOpen()) {
        return NO_CHILDREN;
    }//from   ww w  .  j  a va  2  s .co m

    List<IJavaElement> list = new ArrayList<IJavaElement>();
    for (IPackageFragmentRoot root : project.getPackageFragmentRoots()) {
        if (!JVM_CLASSPATH_CONTAINER.isPrefixOf(root.getRawClasspathEntry().getPath())) {
            if (isProjectPackageFragmentRoot(root)) {
                for (IJavaElement element : root.getChildren()) {
                    list.add(element);
                }
            } else if (hasChildren(root)) {
                list.add(root);
            }
        }
    }
    return concatenate(list.toArray(), project.getNonJavaResources());
}

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

License:Open Source License

public IPackageFragmentRoot[] getPackageFragmentRoots(IProgressMonitor monitor) throws Exception {

    IPath[] classpathEntries = null;/* w w  w.  j ava  2 s  .  com*/
    ILaunchConfiguration configuration = null;
    try {
        if (BootPropertyTester.isBootProject(javaProject.getProject())) {
            configuration = BootLaunchConfigurationDelegate.createConf(javaProject);
            Set<String> modes = new HashSet<String>();
            modes.add(ILaunchManager.RUN_MODE);

            ILaunchDelegate[] delegates = configuration.getType().getDelegates(modes);
            if (delegates != null && delegates.length > 0) {

                JavaLaunchDelegate javaDelegate = null;

                for (ILaunchDelegate del : delegates) {
                    if (BootLaunchConfigurationDelegate.TYPE_ID.equals(del.getId())
                            && del.getDelegate() instanceof JavaLaunchDelegate) {

                        javaDelegate = (JavaLaunchDelegate) del.getDelegate();
                        break;
                    }
                }

                if (javaDelegate != null) {
                    String[] pathValues = javaDelegate.getClasspath(configuration);
                    if (pathValues != null) {
                        classpathEntries = new IPath[pathValues.length];
                        for (int i = 0; i < pathValues.length && i < classpathEntries.length; i++) {
                            classpathEntries[i] = new Path(pathValues[i]);
                        }
                    }
                }
            }

        } else {
            throw ExceptionUtil.coreException("The project : " + javaProject.getProject().getName()
                    + " does not appear to be a Spring Boot project. Only Spring Boot projects can be deployed through the Boot Dashboard.");
        }

    } finally {
        if (configuration != null) {
            configuration.delete();
        }
    }

    if (classpathEntries != null && classpathEntries.length > 0) {
        List<IPackageFragmentRoot> pckRoots = new ArrayList<IPackageFragmentRoot>();

        // Since the java project may have other required projects, fetch
        // the
        // ordered
        // list of required projects that will be used to search for package
        // fragment roots
        // corresponding to the resolved class paths. The order of the java
        // projects to search in should
        // start with the most immediate list of required projects of the
        // java
        // project.
        List<IJavaProject> javaProjectsToSearch = getOrderedJavaProjects(javaProject);

        // Find package fragment roots corresponding to the path entries.
        // Search through all java projects, not just the immediate java
        // project
        // for the application that is being pushed to CF.
        for (IPath path : classpathEntries) {

            for (IJavaProject javaProject : javaProjectsToSearch) {

                IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();

                if (roots != null) {
                    List<IPackageFragmentRoot> foundRoots = new ArrayList<IPackageFragmentRoot>();

                    for (IPackageFragmentRoot packageFragmentRoot : roots) {
                        // Note that a class path entry may correspond to a
                        // Java project's target directory.
                        // Different fragment roots may use the same target
                        // directory, so relationship between fragment roots
                        // to a class path entry may be many-to-one.

                        if (isRootAtEntry(packageFragmentRoot, path)) {
                            foundRoots.add(packageFragmentRoot);
                        }
                    }

                    // Stop after the first successful search
                    if (!foundRoots.isEmpty()) {
                        pckRoots.addAll(foundRoots);
                        break;
                    }
                }
            }

        }

        return pckRoots.toArray(new IPackageFragmentRoot[pckRoots.size()]);
    } else {
        return null;
    }
}

From source file:org.springframework.ide.eclipse.internal.bestpractices.quickfix.CreateNewClassMarkerResolution.java

License:Open Source License

/**
 * Create a package fragment for the given package name. This currently
 * guesses the package root from the available package roots. It currently
 * selects the first package root that isn't for a jar'ed package.
 *///from  ww w.  j a  v  a  2s . co m
private IPackageFragmentRoot inferPackageFragmentRoot(IJavaProject javaProject, String packageName)
        throws CoreException {
    try {
        IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots();
        for (int i = 0; i < packageFragmentRoots.length; i++) {
            if (!(packageFragmentRoots[i] instanceof JarPackageFragmentRoot)) {
                return packageFragmentRoots[i];
            }
        }
    } catch (JavaModelException e) {
        throw new CoreException(e.getStatus());
    }

    return null;
}

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

License:Open Source License

private void projectClasspathChanged(IJavaProject source) {
    IProject project = source.getProject();
    List<ProductMatch> productMatches = new ArrayList<ProductMatch>();
    try {/*w  ww. ja  va 2 s.c  o m*/
        IPackageFragmentRoot[] classpath = source.getPackageFragmentRoots();
        for (IPackageFragmentRoot entry : classpath) {
            // Obtain the ProductMatch from the classpath entry
            ProductMatch productMatch = readPackageFragmentRoot(source, entry);

            if (productMatch != null) {

                // We only want the highest version per product; therefore check if one has
                // already been registered and compare the versions
                int ix = productMatches.indexOf(productMatch);
                if (ix >= 0) {
                    String newVersion = productMatch.getVersion();
                    String oldVersion = productMatches.get(ix).getVersion();
                    if (newVersion != null && newVersion.compareTo(oldVersion) > 0) {
                        productMatches.remove(ix);
                        productMatches.add(productMatch);
                    }
                } else {
                    productMatches.add(productMatch);
                }
            }

        }
    } catch (Exception e) {
        // Intentionally only onto the console
        e.printStackTrace();
    } finally {
        for (ProductMatch productMatch : productMatches) {
            recordEvent(productMatch, project.getName());
        }
    }
}

From source file:org.summer.dsl.builder.impl.javasupport.JdtToBeBuiltComputer.java

License:Open Source License

public void updateProject(ToBeBuilt toBeBuilt, IProject project, IProgressMonitor monitor)
        throws CoreException {
    SubMonitor progress = SubMonitor.convert(monitor, 2);
    if (!project.isAccessible() || progress.isCanceled())
        return;//  ww  w .  j a v  a 2  s  . c om
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject.exists()) {
        IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
        progress.setWorkRemaining(roots.length);
        final Map<String, Long> updated = Maps.newHashMap();
        ProjectOrder orderedProjects = workspace.computeProjectOrder(workspace.getRoot().getProjects());
        for (final IPackageFragmentRoot root : roots) {
            if (progress.isCanceled())
                return;
            if (shouldHandle(root) && !isBuiltByUpstream(root, project, orderedProjects.projects)) {
                Map<URI, IStorage> rootData = jdtUriMapperExtension.getAllEntries(root);
                for (Map.Entry<URI, IStorage> e : rootData.entrySet())
                    if (uriValidator.canBuild(e.getKey(), e.getValue())) {
                        toBeBuilt.getToBeDeleted().add(e.getKey());
                        toBeBuilt.getToBeUpdated().add(e.getKey());
                    }
            }
            progress.worked(1);
        }
        synchronized (modificationStampCache) {
            modificationStampCache.projectToModificationStamp.putAll(updated);
        }
    }
}

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

License:Open Source License

protected URI resolvePath(IJavaProject javaProject, URI path) {
    try {/*ww w. ja v  a2s  .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;
}