Example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath

List of usage examples for org.eclipse.jdt.core IJavaProject getResolvedClasspath

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IJavaProject getResolvedClasspath.

Prototype

IClasspathEntry[] getResolvedClasspath(boolean ignoreUnresolvedEntry) throws JavaModelException;

Source Link

Document

This is a helper method returning the resolved classpath for the project as a list of simple (non-variable, non-container) classpath entries.

Usage

From source file:org.eclipse.pde.internal.launching.launcher.LauncherUtils.java

License:Open Source License

private static String getTimeStamp(IProject project) {
    IJavaProject jp = JavaCore.create(project);
    try {//w  w  w . j  a  va 2  s .c  o  m
        long timeStamp = 0;
        IClasspathEntry[] entries = jp.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                File file;
                IPath location = entries[i].getOutputLocation();
                if (location == null)
                    location = jp.getOutputLocation();
                IResource res = project.getWorkspace().getRoot().findMember(location);
                IPath path = res == null ? null : res.getLocation();
                if (path == null)
                    continue;
                file = path.toFile();
                Stack<File> files = new Stack<File>();
                files.push(file);
                while (!files.isEmpty()) {
                    file = files.pop();
                    if (file.isDirectory()) {
                        File[] children = file.listFiles();
                        if (children != null) {
                            for (int j = 0; j < children.length; j++)
                                files.push(children[j]);
                        }
                    } else if (file.getName().endsWith(".class") && timeStamp < file.lastModified()) //$NON-NLS-1$
                        timeStamp = file.lastModified();
                }
            }
        }
        IFile[] otherFiles = new IFile[] { PDEProject.getManifest(project),
                PDEProject.getBuildProperties(project) };
        for (int i = 0; i < otherFiles.length; i++) {
            IFile file = otherFiles[i];
            if (file != null) {
                long fileTimeStamp = file.getRawLocation().toFile().lastModified();
                if (timeStamp < fileTimeStamp)
                    timeStamp = fileTimeStamp;
            }
        }
        return Long.toString(timeStamp);
    } catch (JavaModelException e) {
    }
    return "0"; //$NON-NLS-1$
}

From source file:org.eclipse.pde.nls.internal.ui.model.ResourceBundleModel.java

License:Open Source License

/**
 * @param monitor/*from  w  w  w . jav  a2 s  .c o m*/
 * @throws CoreException
 */
private void populateFromWorkspace(IProgressMonitor monitor) throws CoreException {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot root = workspace.getRoot();
    IProject[] projects = root.getProjects();
    for (IProject project : projects) {
        try {
            if (!project.isOpen())
                continue;

            IJavaProject javaProject = (IJavaProject) project.getNature(JAVA_NATURE);
            String pluginId = null;

            try {
                Class IFragmentModel = Class.forName("org.eclipse.pde.core.plugin.IFragmentModel");
                Class IPluginModelBase = Class.forName("org.eclipse.pde.core.plugin.IPluginModelBase");
                Class PluginRegistry = Class.forName("org.eclipse.pde.core.plugin.PluginRegistry");
                Class IPluginBase = Class.forName("org.eclipse.pde.core.plugin.IPluginBase");
                Class PluginFragmentModel = Class.forName("org.eclipse.core.runtime.model.PluginFragmentModel");

                // Plugin and fragment projects
                Class pluginModel = (Class) PluginRegistry.getMethod("findModel", IProject.class).invoke(null,
                        project);
                if (pluginModel != null) {
                    // Get plugin id
                    BundleDescription bd = (BundleDescription) IPluginModelBase
                            .getMethod("getBundleDescription").invoke(pluginModel);
                    pluginId = bd.getName();
                    // OSGi bundle name
                    if (pluginId == null) {
                        Object pluginBase = IPluginModelBase.getMethod("getPluginBase").invoke(pluginModel);
                        pluginId = (String) IPluginBase.getMethod("getId").invoke(pluginBase); // non-OSGi
                        // plug-in id
                    }

                    boolean isFragment = IFragmentModel.isInstance(pluginModel);
                    if (isFragment) {
                        Object pfm = IFragmentModel.getMethod("getFragment");
                        pluginId = (String) PluginFragmentModel.getMethod("getPluginId").invoke(pfm);
                    }

                    // Look for additional 'nl' resources
                    IFolder nl = project.getFolder("nl"); //$NON-NLS-1$
                    if (isFragment && nl.exists()) {
                        IResource[] members = nl.members();
                        for (IResource member : members) {
                            if (member instanceof IFolder) {
                                IFolder langFolder = (IFolder) member;
                                String language = langFolder.getName();

                                // Collect property files
                                IFile[] propertyFiles = collectPropertyFiles(langFolder);
                                for (IFile file : propertyFiles) {
                                    // Compute path name
                                    IPath path = file.getProjectRelativePath();
                                    String country = ""; //$NON-NLS-1$
                                    String packageName = null;
                                    int segmentCount = path.segmentCount();
                                    if (segmentCount > 1) {
                                        StringBuilder builder = new StringBuilder();

                                        // Segment 0: 'nl'
                                        // Segment 1: language code
                                        // Segment 2: (country code)
                                        int begin = 2;
                                        if (segmentCount > 2 && isCountry(path.segment(2))) {
                                            begin = 3;
                                            country = path.segment(2);
                                        }

                                        for (int i = begin; i < segmentCount - 1; i++) {
                                            if (i > begin)
                                                builder.append('.');
                                            builder.append(path.segment(i));
                                        }
                                        packageName = builder.toString();
                                    }

                                    String baseName = getBaseName(file.getName());

                                    ResourceBundleFamily family = getOrCreateFamily(project.getName(), pluginId,
                                            packageName, baseName);
                                    addBundle(family, getLocale(language, country), file);
                                }
                            }
                        }
                    }

                    // Collect property files
                    if (isFragment || javaProject == null) {
                        IFile[] propertyFiles = collectPropertyFiles(project);
                        for (IFile file : propertyFiles) {
                            IPath path = file.getProjectRelativePath();
                            int segmentCount = path.segmentCount();

                            if (segmentCount > 0 && path.segment(0).equals("nl")) //$NON-NLS-1$
                                continue; // 'nl' resource have been
                            // processed
                            // above

                            // Guess package name
                            String packageName = null;
                            if (segmentCount > 1) {
                                StringBuilder builder = new StringBuilder();
                                for (int i = 0; i < segmentCount - 1; i++) {
                                    if (i > 0)
                                        builder.append('.');
                                    builder.append(path.segment(i));
                                }
                                packageName = builder.toString();
                            }

                            String baseName = getBaseName(file.getName());
                            String language = getLanguage(file.getName());
                            String country = getCountry(file.getName());

                            ResourceBundleFamily family = getOrCreateFamily(project.getName(), pluginId,
                                    packageName, baseName);
                            addBundle(family, getLocale(language, country), file);
                        }
                    }

                }
            } catch (Throwable e) {
                // MessagesEditorPlugin.log(e);
            }

            // Look for resource bundles in Java packages (output folders,
            // e.g. 'bin', will be ignored)
            if (javaProject != null) {
                IClasspathEntry[] classpathEntries = javaProject.getResolvedClasspath(true);
                for (IClasspathEntry entry : classpathEntries) {
                    if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                        IPath path = entry.getPath();
                        IFolder folder = workspace.getRoot().getFolder(path);
                        IFile[] propertyFiles = collectPropertyFiles(folder);

                        for (IFile file : propertyFiles) {
                            String name = file.getName();
                            String baseName = getBaseName(name);
                            String language = getLanguage(name);
                            String country = getCountry(name);
                            IPackageFragment pf = javaProject
                                    .findPackageFragment(file.getParent().getFullPath());
                            String packageName = pf.getElementName();

                            ResourceBundleFamily family = getOrCreateFamily(project.getName(), pluginId,
                                    packageName, baseName);

                            addBundle(family, getLocale(language, country), file);
                        }
                    } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        IPackageFragmentRoot[] findPackageFragmentRoots = javaProject
                                .findPackageFragmentRoots(entry);
                        for (IPackageFragmentRoot packageFragmentRoot : findPackageFragmentRoots) {
                            IJavaElement[] children = packageFragmentRoot.getChildren();
                            for (IJavaElement child : children) {
                                IPackageFragment pf = (IPackageFragment) child;
                                Object[] nonJavaResources = pf.getNonJavaResources();

                                for (Object resource : nonJavaResources) {
                                    if (resource instanceof IJarEntryResource) {
                                        IJarEntryResource jarEntryResource = (IJarEntryResource) resource;
                                        String name = jarEntryResource.getName();
                                        if (name.endsWith(PROPERTIES_SUFFIX)) {
                                            String baseName = getBaseName(name);
                                            String language = getLanguage(name);
                                            String country = getCountry(name);
                                            String packageName = pf.getElementName();

                                            ResourceBundleFamily family = getOrCreateFamily(project.getName(),
                                                    pluginId, packageName, baseName);

                                            addBundle(family, getLocale(language, country), jarEntryResource);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                // Collect non-Java resources
                Object[] nonJavaResources = javaProject.getNonJavaResources();
                ArrayList<IFile> files = new ArrayList<IFile>();
                for (Object resource : nonJavaResources) {
                    if (resource instanceof IContainer) {
                        IContainer container = (IContainer) resource;
                        collectPropertyFiles(container, files);
                    } else if (resource instanceof IFile) {
                        IFile file = (IFile) resource;
                        String name = file.getName();
                        if (isIgnoredFilename(name))
                            continue;
                        if (name.endsWith(PROPERTIES_SUFFIX)) {
                            files.add(file);
                        }
                    }
                }
                for (IFile file : files) {

                    // Convert path to package name format
                    IPath path = file.getProjectRelativePath();
                    String packageName = null;
                    int segmentCount = path.segmentCount();
                    if (segmentCount > 1) {
                        StringBuilder builder = new StringBuilder();
                        for (int i = 0; i < segmentCount - 1; i++) {
                            if (i > 0)
                                builder.append('.');
                            builder.append(path.segment(i));
                        }
                        packageName = builder.toString();
                    }

                    String baseName = getBaseName(file.getName());
                    String language = getLanguage(file.getName());
                    String country = getCountry(file.getName());

                    ResourceBundleFamily family = getOrCreateFamily(project.getName(), pluginId, packageName,
                            baseName);
                    addBundle(family, getLocale(language, country), file);
                }

            }
        } catch (Exception e) {
            MessagesEditorPlugin.log(e);
        }
    }
}

From source file:org.eclipse.sirius.common.xtext.internal.ResourceSetClasspathConfigurator.java

License:Open Source License

private Map<URI, URI> computePlatformURIMap(IJavaProject javaProject) {
    HashMap<URI, URI> hashMap = newHashMap(EcorePlugin.computePlatformURIMap());
    try {//from w w w . ja va 2 s.co m
        if (!javaProject.exists())
            return hashMap;
        IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
        for (IClasspathEntry classPathEntry : classpath) {
            IPath path = classPathEntry.getPath();
            if (path != null && "jar".equals(path.getFileExtension())) { //$NON-NLS-1$
                try {
                    final File file = path.toFile();
                    if (file != null && file.exists()) {
                        try (JarFile jarFile = new JarFile(file)) {
                            Manifest manifest = jarFile.getManifest();
                            if (manifest != null) {
                                handleManifest(hashMap, file, manifest);
                            }
                        }
                    }
                } catch (IOException e) {
                    DslCommonPlugin.getDefault().error(e.getMessage(), e);
                }
            }
        }
    } catch (JavaModelException e) {
        DslCommonPlugin.getDefault().error(e.getMessage(), e);
    }
    return hashMap;
}

From source file:org.eclipse.sirius.common.xtext.internal.XTextResourceSetFactory.java

License:Open Source License

private Map<URI, URI> computePlatformURIMap(IJavaProject javaProject) {
    HashMap<URI, URI> hashMap = newHashMap(EcorePlugin.computePlatformURIMap());
    try {/*w  w  w . j  ava 2s .  c o m*/
        if (!javaProject.exists())
            return hashMap;
        IClasspathEntry[] classpath = javaProject.getResolvedClasspath(true);
        for (IClasspathEntry classPathEntry : classpath) {
            IPath path = classPathEntry.getPath();
            if (path != null && "jar".equals(path.getFileExtension())) {
                try {
                    final File file = path.toFile();
                    if (file != null && file.exists()) {
                        JarFile jarFile = new JarFile(file);
                        Manifest manifest = jarFile.getManifest();
                        if (manifest != null) {
                            handleManifest(hashMap, file, manifest);
                        }
                    }
                } catch (IOException e) {
                    DslCommonPlugin.getDefault().error(e.getMessage(), e);
                }
            }
        }
    } catch (JavaModelException e) {
        DslCommonPlugin.getDefault().error(e.getMessage(), e);
    }
    return hashMap;
}

From source file:org.eclipse.sirius.editor.utils.WorkspaceClassLoading.java

License:Open Source License

private void computeURLs(IProject project, List<URL> uRLs) {
    final IJavaProject javaProject = JavaCore.create(project);
    try {//from w ww  .j a va2s. co m
        for (IClasspathEntry entry : javaProject.getResolvedClasspath(true)) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                final IPath output = entry.getOutputLocation();
                if (output != null) {
                    IFile reference = ResourcesPlugin.getWorkspace().getRoot().getFile(output);
                    if (reference.exists()) {
                        URL url;
                        try {
                            url = reference.getLocation().toFile().toURI().toURL();
                            uRLs.add(url);
                        } catch (MalformedURLException e) {
                            /*
                             * We don't know how to handle this class path
                             * entry.
                             */
                        }
                    }

                }
            }
        }
        /*
         * Add the default output location to the classpath anyway since
         * source folders are not required to have their own
         */
        final IPath output = javaProject.getOutputLocation();
        if (output != null) {
            IFolder reference = ResourcesPlugin.getWorkspace().getRoot().getFolder(output);
            if (reference.exists() && reference.getLocation() != null) {
                URL url;
                File file = reference.getLocation().toFile();
                try {
                    if (file != null && file.exists()) {
                        url = file.toURI().toURL();
                        uRLs.add(url);
                    }
                } catch (MalformedURLException e) {
                    /*
                     * the given path does not map to a file which can
                     * actually be mapped to an url, ignore it.
                     */
                }
            }

        }
    } catch (JavaModelException e) {
    }
}

From source file:org.eclipse.stardust.modeling.validation.util.ProjectClassLoader.java

License:Open Source License

private List resolveClasspath(IProject project, Set compareStrings) {
    List classpath = new ArrayList();
    IJavaProject javaProject = JavaCore.create(project);
    if (javaProject.exists()) {
        IPath projectPath = project.getFullPath();
        IPath projectLocation = project.getLocation().removeLastSegments(projectPath.segmentCount());
        try {/*from w  w  w .  ja  va2 s . c  o m*/
            IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
            // we are guaranteed that no variables or containers are present in the classpath entries
            for (int i = 0; i < entries.length; i++) {
                if (entries[i].getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                    // add recursively the entries from the referenced projects
                    classpath.addAll(resolveClasspath(findProject(entries[i].getPath()), compareStrings));
                } else {
                    IPath entryPath = entries[i].getPath();
                    if (projectPath.isPrefixOf(entryPath)) {
                        // if it's a project relative location, prepend it with the project location
                        entryPath = projectLocation.append(entryPath);
                    }
                    addClasspathEntry(classpath, compareStrings, entryPath);
                }
            }
        } catch (JavaModelException e) {
            //         e.printStackTrace();
        }
    }
    return classpath;
}

From source file:org.eclipse.swt.tools.builders.Check64CompilationParticipant.java

License:Open Source License

void build(IJavaProject project, String root) throws CoreException {
    PrintWriter writer = null;/*from   w  ww  .  ja va2  s . c  o m*/
    try {
        StringBuffer sourcePath = new StringBuffer(), cp = new StringBuffer();
        IClasspathEntry[] entries = project.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            String path = entry.getPath().toPortableString();
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (path.startsWith(pluginDir)) {
                    if (sourcePath.length() > 0)
                        sourcePath.append(File.pathSeparatorChar);
                    String dir = root + path.substring(pluginDir.length());
                    sourcePath.append(dir);
                }
            } else {
                if (cp.length() > 0)
                    cp.append(File.pathSeparator);
                cp.append(path);
            }
        }
        String bin = root + "/bin";
        if (cp.length() > 0)
            cp.append(File.pathSeparator);
        cp.append(bin);
        ArrayList<String> args = new ArrayList<String>();
        args.addAll(Arrays.asList(new String[] { "-nowarn", "-1.5",
                //         "-verbose",
                "-d", bin, "-cp", cp.toString(), "-log", root + "/log.xml", "-sourcepath",
                sourcePath.toString(), }));
        args.addAll(sources);
        writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(root + "/out.txt")));
        BatchCompiler.compile(args.toArray(new String[args.size()]), writer, writer, null);
        writer.close();
        writer = null;
        project.getProject().findMember(new Path(buildDir)).refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (Exception e) {
        throw new CoreException(
                new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Problem building 64-bit code", e));
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:org.eclipse.swt.tools.builders.Check64CompilationParticipant.java

License:Open Source License

boolean is64bit(IJavaProject project) {
    try {/*from  ww w . j a v  a2  s.  co m*/
        IClasspathEntry[] entries = project.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                String path = entry.getPath().toPortableString();
                if (path.equals(pluginDir + "Eclipse SWT PI/win32")
                        || path.equals(pluginDir + "Eclipse SWT PI/cocoa")
                        || path.equals(pluginDir + "Eclipse SWT PI/gtk")) {
                    return true;
                }
            }
        }
    } catch (JavaModelException e) {
    }
    return false;
}

From source file:org.eclipse.vjet.eclipse.javalaunch.utils.EclipseResourceUtils.java

License:Open Source License

/**
 * Searches through the tree of dependencies and adds to a list of projects.
 * @param javaProject - The Java project to search
 * @param transitiveClosureProjectList - The list to store the projects
 * @throws JavaModelException/*  w ww  . j a  v a2s.c o m*/
 */
public static void getTransitiveClosureDependencies(IJavaProject javaProject,
        Map<String, IJavaProject> transitiveClosureProjectList, Map<String, IPath> transitiveLibrarySet)
        throws JavaModelException {

    IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);

    if (classPathEntries != null) {

        for (IClasspathEntry classPathEntry : classPathEntries) {

            if (classPathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
                IResource classPathProject = ResourcesPlugin.getWorkspace().getRoot()
                        .findMember(classPathEntry.getPath());
                if (classPathProject != null) {
                    if (transitiveClosureProjectList.containsKey(classPathProject.getName()) == false) {

                        IJavaProject subJavaProject = getJavaProject(classPathProject);
                        transitiveClosureProjectList.put(classPathProject.getName(), subJavaProject);

                        getTransitiveClosureDependencies(subJavaProject, transitiveClosureProjectList,
                                transitiveLibrarySet);
                    }
                }
            } else if (classPathEntry != null && classPathEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                if (classPathEntry.getSourceAttachmentPath() != null) {
                    String key = classPathEntry.getSourceAttachmentPath().toString();
                    transitiveLibrarySet.put(key, classPathEntry.getSourceAttachmentPath());
                }
            }
        }
    }

}

From source file:org.eclipse.vjet.eclipse.javalaunch.utils.SourcePathUtil.java

License:Open Source License

/**
 * Creates a string list of the source paths needed to build in this project.
 * @param launchProject/*from ww w  .j  a  v a  2  s . com*/
 * @return 
 * @throws CoreException
 */
public static String getSourcePathString(IProject launchProject) throws CoreException {

    IJavaProject javaProject = EclipseResourceUtils.getJavaProject(launchProject);
    List<File> sourcePaths = new ArrayList<File>(100);

    if (javaProject != null) {

        // Create a list to store all the projects
        Map<String, IJavaProject> transitiveClosureProjectList = new LinkedHashMap<String, IJavaProject>();
        Map<String, IPath> transitiveLibrary = new LinkedHashMap<String, IPath>();

        // Start with the passed in project
        transitiveClosureProjectList.put(javaProject.getElementName(), javaProject);

        // Get the transitive clousure of all the projects
        EclipseResourceUtils.getTransitiveClosureDependencies(javaProject, transitiveClosureProjectList,
                transitiveLibrary);

        IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();

        // Add all the source paths of all the projects
        for (IJavaProject project : transitiveClosureProjectList.values()) {

            IClasspathEntry[] classPathEntries = project.getResolvedClasspath(true);

            EclipseResourceUtils.getProjectSourcePaths(sourcePaths, workspaceRoot, classPathEntries);

        }
        for (IPath path : transitiveLibrary.values()) {
            sourcePaths.add(path.toFile());
        }
    } else {
        return "";
    }

    // Convert to semi-colon delimeted string
    StringBuilder sb = new StringBuilder(512);
    for (File sourcePath : sourcePaths) {

        sb.append(sourcePath.getAbsolutePath());
        sb.append(File.pathSeparator);

    }

    // Return the semi-colon list minus the last semi-colon
    return sb.substring(0, sb.length() - 1);
}