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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.pde.internal.core.builders.BundleErrorReporter.java

License:Open Source License

private void validateRequiredExecutionEnvironment() {
    int sev = CompilerFlags.getFlag(fProject, CompilerFlags.P_INCOMPATIBLE_ENV);
    if (sev == CompilerFlags.IGNORE)
        return;//from w  w w  .ja  v  a2 s .  co m
    BundleDescription desc = fModel.getBundleDescription();
    if (desc == null)
        return;

    // if we aren't a java project, let's not check for a BREE
    try {
        if (!fProject.hasNature(JavaCore.NATURE_ID))
            return;
    } catch (CoreException e) {
        return;
    }

    String[] bundleEnvs = desc.getExecutionEnvironments();
    if (bundleEnvs == null || bundleEnvs.length == 0) {
        // No EE specified
        IJavaProject javaProject = JavaCore.create(fProject);

        // See if the project has an EE classpath entry
        if (javaProject.exists()) {
            try {
                IClasspathEntry[] entries = javaProject.getRawClasspath();

                for (int i = 0; i < entries.length; i++) {
                    if (entries[i].getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                        IPath currentPath = entries[i].getPath();
                        if (JavaRuntime.newDefaultJREContainerPath().matchingFirstSegments(currentPath) > 0) {
                            String eeId = JavaRuntime.getExecutionEnvironmentId(currentPath);
                            if (eeId != null) {
                                IMarker marker = report(
                                        PDECoreMessages.BundleErrorReporter_noExecutionEnvironmentSet, 1, sev,
                                        PDEMarkerFactory.M_EXECUTION_ENVIRONMENT_NOT_SET,
                                        PDEMarkerFactory.CAT_EE);
                                addMarkerAttribute(marker, "ee_id", eeId); //$NON-NLS-1$
                                return;
                            }
                        }
                    }
                }
            } catch (JavaModelException e) {
                PDECore.log(e);
            }
        }

        // If no EE classpath entry, get a matching EE for the project JRE (or the default JRE)
        IExecutionEnvironment[] systemEnvs = JavaRuntime.getExecutionEnvironmentsManager()
                .getExecutionEnvironments();
        IVMInstall vm = JavaRuntime.getDefaultVMInstall();
        if (javaProject.exists()) {
            try {
                vm = JavaRuntime.getVMInstall(javaProject);
            } catch (CoreException e) {
                PDECore.log(e);
            }
        }

        if (vm != null) {
            for (int i = 0; i < systemEnvs.length; i++) {
                // Get strictly compatible EE for the default VM
                if (systemEnvs[i].isStrictlyCompatible(vm)) {
                    IMarker marker = report(PDECoreMessages.BundleErrorReporter_noExecutionEnvironmentSet, 1,
                            sev, PDEMarkerFactory.M_EXECUTION_ENVIRONMENT_NOT_SET, PDEMarkerFactory.CAT_EE);
                    addMarkerAttribute(marker, "ee_id", systemEnvs[i].getId()); //$NON-NLS-1$
                    break;
                }
            }
        }
        return;
    }

    IHeader header = getHeader(Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT);
    if (header == null)
        return;

    IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment(bundleEnvs[0]);
    if (env != null) {
        IJavaProject jproject = JavaCore.create(fProject);
        IClasspathEntry[] entries;
        try {
            entries = jproject.getRawClasspath();
            for (int i = 0; i < entries.length; i++) {
                if (entries[i].getEntryKind() != IClasspathEntry.CPE_CONTAINER)
                    continue;
                IPath currentPath = entries[i].getPath();
                if (JavaRuntime.newDefaultJREContainerPath().matchingFirstSegments(currentPath) == 0)
                    continue;

                IPath validPath = JavaRuntime.newJREContainerPath(env);
                if (!validPath.equals(currentPath)) {
                    // Check if the user is using a perfect match JRE
                    IVMInstall vm = JavaRuntime.getVMInstall(currentPath);
                    if (vm == null || !env.isStrictlyCompatible(vm)) {
                        report(NLS.bind(PDECoreMessages.BundleErrorReporter_reqExecEnv_conflict, bundleEnvs[0]),
                                getLine(header, bundleEnvs[0]), sev, PDEMarkerFactory.M_MISMATCHED_EXEC_ENV,
                                PDEMarkerFactory.CAT_EE);
                    }
                }
            }
        } catch (JavaModelException e) {
        }
    }
    IExecutionEnvironment[] systemEnvs = JavaRuntime.getExecutionEnvironmentsManager()
            .getExecutionEnvironments();
    for (int i = 0; i < bundleEnvs.length; i++) {
        boolean found = false;
        for (int j = 0; j < systemEnvs.length; j++) {
            if (bundleEnvs[i].equals(systemEnvs[j].getId())) {
                found = true;
                break;
            }
        }
        if (!found) {
            report(NLS.bind(PDECoreMessages.BundleErrorReporter_reqExecEnv_unknown, bundleEnvs[i]),
                    getLine(header, bundleEnvs[i]), sev, PDEMarkerFactory.M_UNKNOW_EXEC_ENV,
                    PDEMarkerFactory.CAT_EE);
            break;
        }
    }
}

From source file:org.eclipse.pde.internal.core.exports.WorkspaceExportHelper.java

License:Open Source License

/**
 * Returns a map containing information associating libraries to the output locations the
 * workspace compiles them to.  Uses information in the build.properties and the classpath.
 * The map will be of the following form: 
 * String symbolic name > lib output map
 * The lib output map will be of the following form:
 * String lib name > Set of IPath output folders
 *
 * @param exportedItems the plugins or features being exported
 * @return a map of library output folders for each plugin in the workspace
 *//*w ww  . j av a  2 s  .  co  m*/
public Map<String, Map<String, Set<IPath>>> getWorkspaceOutputFolders(Object[] exportedItems)
        throws CoreException {
    IProject[] projects = getExportedWorkspaceProjects(exportedItems);
    Map<String, Map<String, Set<IPath>>> result = new HashMap<String, Map<String, Set<IPath>>>(projects.length);
    for (int i = 0; i < projects.length; i++) {
        IFile buildFile = PDEProject.getBuildProperties(projects[i]);
        if (buildFile.exists()) {
            IBuildModel buildModel = new WorkspaceBuildModel(buildFile);
            buildModel.load();
            IJavaProject javaProject = JavaCore.create(projects[i]);
            if (javaProject.exists()) {
                Map<String, Set<IPath>> modelOutput = getPluginOutputFolders(buildModel, javaProject);
                if (!modelOutput.isEmpty()) {
                    IPluginModelBase model = PDECore.getDefault().getModelManager().findModel(projects[i]);
                    if (model != null) {
                        result.put(model.getBundleDescription().getSymbolicName(), modelOutput);
                    }
                }
            }
        }
    }
    return result;
}

From source file:org.eclipse.pde.internal.core.project.BundleProjectDescription.java

License:Open Source License

/**
 * Initialize settings from the given project.
 * /* w w w . jav a  2 s.c  o m*/
 * @param project project
 * @exception CoreException if unable to initialize
 */
private void initialize(IProject project) throws CoreException {
    IContainer root = PDEProject.getBundleRoot(project);
    if (root != project) {
        setBundleRoot(root.getProjectRelativePath());
    }
    IEclipsePreferences node = new ProjectScope(project).getNode(PDECore.PLUGIN_ID);
    if (node != null) {
        setExtensionRegistry(node.getBoolean(ICoreConstants.EXTENSIONS_PROPERTY, true));
        setEquinox(node.getBoolean(ICoreConstants.EQUINOX_PROPERTY, true));
    }
    // export wizard and launch shortcuts
    setExportWizardId(PDEProject.getExportWizard(project));
    setLaunchShortcuts(PDEProject.getLaunchShortcuts(project));
    // location and natures
    setLocationURI(project.getDescription().getLocationURI());
    setNatureIds(project.getDescription().getNatureIds());

    IFile manifest = PDEProject.getManifest(project);
    if (manifest.exists()) {
        Map<?, ?> headers;
        try {
            headers = ManifestElement.parseBundleManifest(manifest.getContents(), null);
            fReadHeaders = headers;
        } catch (IOException e) {
            throw new CoreException(new Status(IStatus.ERROR, PDECore.PLUGIN_ID, e.getMessage(), e));
        } catch (BundleException e) {
            throw new CoreException(new Status(IStatus.ERROR, PDECore.PLUGIN_ID, e.getMessage(), e));
        }
        setActivator(getHeaderValue(headers, Constants.BUNDLE_ACTIVATOR));
        setBundleName(getHeaderValue(headers, Constants.BUNDLE_NAME));
        setBundleVendor(getHeaderValue(headers, Constants.BUNDLE_VENDOR));
        String version = getHeaderValue(headers, Constants.BUNDLE_VERSION);
        if (version != null) {
            setBundleVersion(new Version(version));
        }
        IJavaProject jp = JavaCore.create(project);
        if (jp.exists()) {
            setDefaultOutputFolder(jp.getOutputLocation().removeFirstSegments(1));
        }
        ManifestElement[] elements = parseHeader(headers, Constants.FRAGMENT_HOST);
        if (elements != null && elements.length > 0) {
            setHost(getBundleProjectService().newHost(elements[0].getValue(),
                    getRange(elements[0].getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE))));
        }
        String value = getHeaderValue(headers, Constants.BUNDLE_LOCALIZATION);
        if (value != null) {
            setLocalization(new Path(value));
        }
        elements = parseHeader(headers, Constants.BUNDLE_REQUIREDEXECUTIONENVIRONMENT);
        if (elements != null && elements.length > 0) {
            String[] keys = new String[elements.length];
            for (int i = 0; i < elements.length; i++) {
                keys[i] = elements[i].getValue();
            }
            setExecutionEnvironments(keys);
        }
        IBuild build = getBuildModel(project);
        elements = parseHeader(headers, Constants.BUNDLE_CLASSPATH);
        IBundleClasspathEntry[] classpath = null;
        if (elements != null && elements.length > 0) {
            List<IBundleClasspathEntry> collect = new ArrayList<IBundleClasspathEntry>();
            for (int i = 0; i < elements.length; i++) {
                String libName = elements[i].getValue();
                IBundleClasspathEntry[] entries = getClasspathEntries(project, build, libName);
                if (entries != null) {
                    for (int j = 0; j < entries.length; j++) {
                        collect.add(entries[j]);
                    }
                }
            }
            classpath = collect.toArray(new IBundleClasspathEntry[collect.size()]);
        } else if (elements == null) {
            // default bundle classpath of '.'
            classpath = getClasspathEntries(project, build, "."); //$NON-NLS-1$
        }
        setBundleClasspath(classpath);
        elements = parseHeader(headers, Constants.BUNDLE_SYMBOLICNAME);
        if (elements != null && elements.length > 0) {
            setSymbolicName(elements[0].getValue());
            String directive = elements[0].getDirective(Constants.SINGLETON_DIRECTIVE);
            if (directive == null) {
                directive = elements[0].getAttribute(Constants.SINGLETON_DIRECTIVE);
            }
            setSingleton("true".equals(directive)); //$NON-NLS-1$
        }
        elements = parseHeader(headers, Constants.IMPORT_PACKAGE);
        if (elements != null) {
            if (elements.length > 0) {
                IPackageImportDescription[] imports = new IPackageImportDescription[elements.length];
                for (int i = 0; i < elements.length; i++) {
                    boolean optional = Constants.RESOLUTION_OPTIONAL
                            .equals(elements[i].getDirective(Constants.RESOLUTION_DIRECTIVE))
                            || "true".equals(elements[i].getAttribute(ICoreConstants.OPTIONAL_ATTRIBUTE)); //$NON-NLS-1$
                    String pv = elements[i].getAttribute(ICoreConstants.PACKAGE_SPECIFICATION_VERSION);
                    if (pv == null) {
                        pv = elements[i].getAttribute(Constants.VERSION_ATTRIBUTE);
                    }
                    imports[i] = getBundleProjectService().newPackageImport(elements[i].getValue(),
                            getRange(pv), optional);
                }
                setPackageImports(imports);
            } else {
                // empty header - should be maintained
                setHeader(Constants.IMPORT_PACKAGE, ""); //$NON-NLS-1$
            }
        }
        elements = parseHeader(headers, Constants.EXPORT_PACKAGE);
        if (elements != null && elements.length > 0) {
            IPackageExportDescription[] exports = new IPackageExportDescription[elements.length];
            for (int i = 0; i < elements.length; i++) {
                ManifestElement exp = elements[i];
                String pv = exp.getAttribute(ICoreConstants.PACKAGE_SPECIFICATION_VERSION);
                if (pv == null) {
                    pv = exp.getAttribute(Constants.VERSION_ATTRIBUTE);
                }
                String directive = exp.getDirective(ICoreConstants.FRIENDS_DIRECTIVE);
                boolean internal = "true".equals(exp.getDirective(ICoreConstants.INTERNAL_DIRECTIVE)) //$NON-NLS-1$
                        || directive != null;
                String[] friends = null;
                if (directive != null) {
                    friends = ManifestElement.getArrayFromList(directive);
                }
                exports[i] = getBundleProjectService().newPackageExport(exp.getValue(), getVersion(pv),
                        !internal, friends);
            }
            setPackageExports(exports);
        }
        elements = parseHeader(headers, Constants.REQUIRE_BUNDLE);
        if (elements != null && elements.length > 0) {
            IRequiredBundleDescription[] req = new IRequiredBundleDescription[elements.length];
            for (int i = 0; i < elements.length; i++) {
                ManifestElement rb = elements[i];
                boolean reexport = Constants.VISIBILITY_REEXPORT
                        .equals(rb.getDirective(Constants.VISIBILITY_DIRECTIVE))
                        || "true".equals(rb.getAttribute(ICoreConstants.REPROVIDE_ATTRIBUTE)); //$NON-NLS-1$
                boolean optional = Constants.RESOLUTION_OPTIONAL
                        .equals(rb.getDirective(Constants.RESOLUTION_DIRECTIVE))
                        || "true".equals(rb.getAttribute(ICoreConstants.OPTIONAL_ATTRIBUTE)); //$NON-NLS-1$
                req[i] = getBundleProjectService().newRequiredBundle(rb.getValue(),
                        getRange(rb.getAttribute(Constants.BUNDLE_VERSION_ATTRIBUTE)), optional, reexport);
            }
            setRequiredBundles(req);
        }
        String lazy = getHeaderValue(headers, ICoreConstants.ECLIPSE_AUTOSTART);
        if (lazy == null) {
            lazy = getHeaderValue(headers, ICoreConstants.ECLIPSE_LAZYSTART);
            if (lazy == null) {
                setActivationPolicy(getHeaderValue(headers, Constants.BUNDLE_ACTIVATIONPOLICY));
            }
        }
        if ("true".equals(lazy)) { //$NON-NLS-1$
            setActivationPolicy(Constants.ACTIVATION_LAZY);
        }
        String latest = TargetPlatformHelper.getTargetVersionString();
        IPluginModelBase model = PluginRegistry.findModel(project);
        if (model != null) {
            IPluginBase base = model.getPluginBase();
            String tv = TargetPlatformHelper.getTargetVersionForSchemaVersion(base.getSchemaVersion());
            if (!tv.equals(latest)) {
                setTargetVersion(tv);
            }
        }
        if (build != null) {
            IBuildEntry entry = build.getEntry(IBuildEntry.BIN_INCLUDES);
            if (entry != null) {
                String[] tokens = entry.getTokens();
                if (tokens != null && tokens.length > 0) {
                    List<String> strings = new ArrayList<String>();
                    for (int i = 0; i < tokens.length; i++) {
                        strings.add(tokens[i]);
                    }
                    // remove the default entries
                    strings.remove("META-INF/"); //$NON-NLS-1$
                    String[] names = ProjectModifyOperation.getLibraryNames(this);
                    if (names != null) {
                        for (int i = 0; i < names.length; i++) {
                            strings.remove(names[i]);
                            // if the library is a folder, account for trailing slash - see bug 306991
                            IPath path = new Path(names[i]);
                            if (path.getFileExtension() == null) {
                                strings.remove(names[i] + "/"); //$NON-NLS-1$
                            }
                        }
                    }
                    // set left overs
                    if (!strings.isEmpty()) {
                        IPath[] paths = new IPath[strings.size()];
                        for (int i = 0; i < strings.size(); i++) {
                            paths[i] = new Path(strings.get(i));
                        }
                        setBinIncludes(paths);
                    }
                }
            }
        }
    }
}

From source file:org.eclipse.pde.internal.core.project.ProjectModifyOperation.java

License:Open Source License

/**
 * Creates or modifies a project based on the given description.
 * //  www  .j a  v  a  2  s. c  o m
 * @param monitor progress monitor or <code>null</code>
 * @param description project description
 * @throws CoreException if project creation fails
 */
public void execute(IProgressMonitor monitor, IBundleProjectDescription description) throws CoreException {
    // retrieve current description of the project to detect differences
    IProject project = description.getProject();
    IBundleProjectService service = (IBundleProjectService) PDECore.getDefault()
            .acquireService(IBundleProjectService.class.getName());
    IBundleProjectDescription before = service.getDescription(project);
    boolean considerRoot = !project.exists();
    String taskName = null;
    boolean jpExisted = false;
    if (project.exists()) {
        taskName = Messages.ProjectModifyOperation_0;
        jpExisted = before.hasNature(JavaCore.NATURE_ID);
    } else {
        taskName = Messages.ProjectModifyOperation_1;
        // new bundle projects get Java and Plug-in natures
        if (description.getNatureIds().length == 0) {
            description
                    .setNatureIds(new String[] { IBundleProjectDescription.PLUGIN_NATURE, JavaCore.NATURE_ID });
        }
    }
    boolean becomeBundle = !before.hasNature(IBundleProjectDescription.PLUGIN_NATURE)
            && description.hasNature(IBundleProjectDescription.PLUGIN_NATURE);

    // set default values when migrating from Java project to bundle project
    if (jpExisted && becomeBundle) {
        if (description.getExecutionEnvironments() == null) {
            // use EE from Java project when unspecified in the description, and a bundle nature is being added
            IJavaProject jp = JavaCore.create(project);
            if (jp.exists()) {
                IClasspathEntry[] classpath = jp.getRawClasspath();
                for (int i = 0; i < classpath.length; i++) {
                    IClasspathEntry entry = classpath[i];
                    if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
                        String id = JavaRuntime.getExecutionEnvironmentId(entry.getPath());
                        if (id != null) {
                            description.setExecutionEnvironments(new String[] { id });
                            break;
                        }
                    }
                }
            }
        }
    }
    // other default values when becoming a bundle
    if (becomeBundle) {
        // set default values for where unspecified
        if (description.getBundleVersion() == null) {
            description.setBundleVersion(new Version(1, 0, 0, "qualifier")); //$NON-NLS-1$
        }
    }

    SubMonitor sub = SubMonitor.convert(monitor, taskName, 6);
    // create and open project
    createProject(description);
    // set bundle root for new projects
    if (considerRoot) {
        IFolder folder = null;
        IPath root = description.getBundleRoot();
        if (root != null && !root.isEmpty()) {
            folder = project.getFolder(root);
            CoreUtility.createFolder(folder);
        }
        PDEProject.setBundleRoot(project, folder);
    }
    sub.worked(1);
    configureNatures(description);
    sub.worked(1);
    if (project.hasNature(JavaCore.NATURE_ID)) {
        configureJavaProject(description, before, jpExisted);
    }
    sub.worked(1);
    configureManifest(description, before);
    sub.worked(1);
    configureBuildPropertiesFile(description, before);
    sub.worked(1);

    // project settings for Equinox, Extension Registry, Automated dependency policy,
    // manifest editor launch shortcuts and export wizard
    IEclipsePreferences pref = new ProjectScope(project).getNode(PDECore.PLUGIN_ID);
    if (pref != null) {
        // best guess for automated dependency management: Equinox + Extensions = use required bundle
        if (description.isEquinox() && description.isExtensionRegistry()) {
            pref.remove(ICoreConstants.RESOLVE_WITH_REQUIRE_BUNDLE); // i.e. use required bundle
        } else {
            pref.putBoolean(ICoreConstants.RESOLVE_WITH_REQUIRE_BUNDLE, false);
        }
        if (description.isExtensionRegistry()) {
            pref.remove(ICoreConstants.EXTENSIONS_PROPERTY); // i.e. support extensions
        } else {
            pref.putBoolean(ICoreConstants.EXTENSIONS_PROPERTY, false);
        }
        if (description.isEquinox()) {
            pref.remove(ICoreConstants.EQUINOX_PROPERTY); // i.e. using Equinox
        } else {
            pref.putBoolean(ICoreConstants.EQUINOX_PROPERTY, false);
        }
        String[] shorts = description.getLaunchShortcuts();
        if (shorts == null || shorts.length == 0) {
            pref.remove(ICoreConstants.MANIFEST_LAUNCH_SHORTCUTS); // use defaults
        } else {
            StringBuffer value = new StringBuffer();
            for (int i = 0; i < shorts.length; i++) {
                if (i > 0) {
                    value.append(',');
                }
                value.append(shorts[i]);
            }
            pref.put(ICoreConstants.MANIFEST_LAUNCH_SHORTCUTS, value.toString());
        }
        if (description.getExportWizardId() == null) {
            pref.remove(ICoreConstants.MANIFEST_EXPORT_WIZARD);
        } else {
            pref.put(ICoreConstants.MANIFEST_EXPORT_WIZARD, description.getExportWizardId());
        }
        try {
            pref.flush();
        } catch (BackingStoreException e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, PDECore.PLUGIN_ID, Messages.ProjectModifyOperation_2, e));
        }
    }

    if (fModel.isDirty()) {
        fModel.save();
    }
    sub.worked(1);
    sub.done();
    if (monitor != null) {
        monitor.done();
    }
}

From source file:org.eclipse.pde.internal.core.util.PDEJavaHelper.java

License:Open Source License

/**
 * Precedence order from high to low:  (1) Project specific option;
 * (2) General preference option; (3) Default option; (4) Java 1.3
 * @param project/*  w  w w .ja  v a 2 s  .com*/
 * @param optionName
 */
public static String getJavaLevel(IProject project, String optionName) {
    // Returns the corresponding java project
    // No need to check for null, will return null      
    IJavaProject javaProject = JavaCore.create(project);
    String value = null;
    // Preferred to use the project
    if ((javaProject != null) && javaProject.exists()) {
        // Get the project specific option if one exists. Rolls up to the 
        // general preference option if no project specific option exists.
        value = javaProject.getOption(optionName, true);
        if (value != null) {
            return value;
        }
    }
    // Get the general preference option
    value = new PDEPreferencesManager(JavaCore.PLUGIN_ID).getString(optionName);
    if (value != null) {
        return value;
    }
    // Get the default option
    value = JavaCore.getOption(optionName);
    if (value != null) {
        return value;
    }
    // Return the default
    return JavaCore.VERSION_1_3;
}

From source file:org.eclipse.pde.internal.ui.correction.java.FindClassResolutionsOperation.java

License:Open Source License

/**
 * Finds all exported packages containing the simple type aTypeName. The packages
 * will be filtered from the given packages which are already imported, and all 
 * system packages.//  w  w w . j av a 2s.  c  o m
 * 
 * If no exported package is left, packagesToExport will be filled with those
 * packages that would have been returned, if they were exported.  
 * @param aTypeName the simple type to search for
 * @param importPkgs the packages which are already imported
 * @param packagesToExport return parameter that will be filled with packages to export
 *        if no valid package to import was found
 * @param monitor
 * @return the set of packages to import
 */
private Collection<ExportPackageDescription> findValidPackagesContainingSimpleType(String aTypeName,
        ImportPackageSpecification[] importPkgs, Set<IPackageFragment> packagesToExport,
        IProgressMonitor monitor) {
    SubMonitor subMonitor = SubMonitor.convert(monitor);

    IPluginModelBase[] activeModels = PluginRegistry.getActiveModels();
    Set<IJavaProject> javaProjects = new HashSet<IJavaProject>(activeModels.length * 2);

    for (int i = 0; i < activeModels.length; i++) {
        IResource resource = activeModels[i].getUnderlyingResource();
        if (resource != null && resource.isAccessible()) {
            IJavaProject javaProject = JavaCore.create(resource.getProject());
            if (javaProject.exists()) {
                javaProjects.add(javaProject);
            }
        }
    }
    final IJavaProject currentJavaProject = JavaCore.create(fProject);
    javaProjects.remove(currentJavaProject); // no need to search in current project itself

    try {
        IJavaSearchScope searchScope = SearchEngine
                .createJavaSearchScope(javaProjects.toArray(new IJavaElement[javaProjects.size()]));

        final Map<String, IPackageFragment> packages = new HashMap<String, IPackageFragment>();
        SearchRequestor requestor = new SearchRequestor() {

            public void acceptSearchMatch(SearchMatch aMatch) throws CoreException {
                Object element = aMatch.getElement();
                if (element instanceof IType) {
                    IType type = (IType) element;
                    // Only try to import types we can access (Bug 406232)
                    if (Flags.isPublic(type.getFlags())) {
                        if (!currentJavaProject.equals(type.getJavaProject())) {
                            IPackageFragment packageFragment = type.getPackageFragment();
                            if (packageFragment.exists()) {
                                packages.put(packageFragment.getElementName(), packageFragment);
                            }
                        }
                    }
                }
            }
        };

        SearchPattern typePattern = SearchPattern.createPattern(aTypeName, IJavaSearchConstants.TYPE,
                IJavaSearchConstants.DECLARATIONS,
                SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
        new SearchEngine().search(typePattern,
                new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, searchScope, requestor,
                subMonitor.newChild(1));

        if (!packages.isEmpty()) {
            // transform to ExportPackageDescriptions
            Map<String, ExportPackageDescription> exportDescriptions = new HashMap<String, ExportPackageDescription>(
                    packages.size());

            // remove system packages if they happen to be included. Adding a system package won't resolve anything, since package package already comes from JRE
            ExportPackageDescription[] systemPackages = PDECore.getDefault().getModelManager().getState()
                    .getState().getSystemPackages();
            for (int i = 0; i < systemPackages.length; i++) {
                packages.remove(systemPackages[i].getName());
            }
            // also remove packages that are already imported
            for (int i = 0; i < importPkgs.length; i++) {
                packages.remove(importPkgs[i].getName());
            }

            // finally create the list of ExportPackageDescriptions
            ExportPackageDescription[] knownPackages = PDECore.getDefault().getModelManager().getState()
                    .getState().getExportedPackages();
            for (int i = 0; i < knownPackages.length; i++) {
                if (packages.containsKey(knownPackages[i].getName())) {
                    exportDescriptions.put(knownPackages[i].getName(), knownPackages[i]);
                }
            }
            if (exportDescriptions.isEmpty()) {
                // no packages to import found, maybe there are packages to export
                packagesToExport.addAll(packages.values());
            }

            return exportDescriptions.values();
        }

        return Collections.emptySet();
    } catch (CoreException ex) {
        // ignore, return an empty set
        return Collections.emptySet();
    }
}

From source file:org.eclipse.pde.ui.tests.ee.ExecutionEnvironmentTests.java

License:Open Source License

/**
 * Creates a plug-in project with a custom execution environment. Validates that
 * compiler compliance settings and build path are correct and that class files
 * are generated with correct target level.
 * //from  w  w  w  . j a v a2s.  c o  m
 * TODO The VM this is run on must be included in the compatible JREs for the custom 
 * environment. See {@link EnvironmentAnalyzerDelegate#analyze(org.eclipse.jdt.launching.IVMInstall, IProgressMonitor)}
 * 
 * @throws Exception
 */
public void testCustomEnvironment() throws Exception {
    try {
        IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager()
                .getEnvironment(EnvironmentAnalyzerDelegate.EE_NO_SOUND);
        IJavaProject project = ProjectUtils.createPluginProject("no.sound", env);
        assertTrue("Project was not created", project.exists());

        validateOption(project, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.ERROR);
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.ERROR);

        validateSystemLibrary(project, JavaRuntime.newJREContainerPath(env));

        // ensure class files are build with correct target level
        project.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
        waitForBuild();
        IFile file = project.getProject().getFile("/bin/no/sound/Activator.class");
        assertTrue("Activator class missing", file.exists());
        validateTargetLevel(file.getLocation().toOSString(), 47);
    } finally {
        deleteProject("no.sound");
    }
}

From source file:org.eclipse.pde.ui.tests.ee.ExecutionEnvironmentTests.java

License:Open Source License

/**
 * Creates a plug-in project with a J2SE-1.4 execution environment. Validates that
 * compiler compliance settings and build path are correct and that class files
 * are generated with correct target level.
 * //from  w w  w  .  j ava2  s  . c  o m
 * @throws Exception
 */
public void testJava4Environment() throws Exception {
    try {
        IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("J2SE-1.4");
        IJavaProject project = ProjectUtils.createPluginProject("j2se14.plug", env);
        assertTrue("Project was not created", project.exists());

        validateOption(project, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2);
        validateOption(project, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.WARNING);
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.WARNING);

        validateSystemLibrary(project, JavaRuntime.newJREContainerPath(env));

        project.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null);
        waitForBuild();
        IFile file = project.getProject().getFile("/bin/j2se14/plug/Activator.class");
        assertTrue("Activator class missing", file.exists());
        validateTargetLevel(file.getLocation().toOSString(), 46);
    } finally {
        deleteProject("j2se14.plug");
    }
}

From source file:org.eclipse.pde.ui.tests.ee.ExecutionEnvironmentTests.java

License:Open Source License

/**
 * Creates a plug-in project without an execution environment. Validates that
 * compiler compliance settings and build path reflect default workspace settings.
 * /*w w w.ja  v  a2s. c  o  m*/
 * @throws Exception
 */
public void testNoEnvironment() throws Exception {
    try {
        IJavaProject project = ProjectUtils.createPluginProject("no.env", null);
        assertTrue("Project was not created", project.exists());

        Hashtable options = JavaCore.getOptions();
        validateOption(project, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
                (String) options.get(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM));
        validateOption(project, JavaCore.COMPILER_SOURCE, (String) options.get(JavaCore.COMPILER_SOURCE));
        validateOption(project, JavaCore.COMPILER_COMPLIANCE,
                (String) options.get(JavaCore.COMPILER_COMPLIANCE));
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER,
                (String) options.get(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER));
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER,
                (String) options.get(JavaCore.COMPILER_PB_ENUM_IDENTIFIER));

        validateSystemLibrary(project, JavaRuntime.newDefaultJREContainerPath());
    } finally {
        deleteProject("no.env");
    }
}

From source file:org.eclipse.pde.ui.tests.ee.ExecutionEnvironmentTests.java

License:Open Source License

/**
 * Creates a plug-in project with a J2SE-1.4 execution environment. Validates that
 * compiler compliance settings and build path are correct. Modifies the compliance
 * options and then updates the class path again. Ensures that the enum and assert
 * identifier options get overwritten with minimum 'warning' severity.
 * // ww  w  .  ja va 2s . co m
 * @throws Exception
 */
public void testMinimumComplianceOverwrite() throws Exception {
    try {
        IExecutionEnvironment env = JavaRuntime.getExecutionEnvironmentsManager().getEnvironment("J2SE-1.4");
        IJavaProject project = ProjectUtils.createPluginProject("j2se14.ignore", env);
        assertTrue("Project was not created", project.exists());

        validateOption(project, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2);
        validateOption(project, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.WARNING);
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.WARNING);

        validateSystemLibrary(project, JavaRuntime.newJREContainerPath(env));

        // set to ignore assert/enum options
        project.setOption(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.IGNORE);
        project.setOption(JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.IGNORE);
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.IGNORE);
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.IGNORE);

        // updating class path should increase severity to warning
        IPluginModelBase model = PluginRegistry.findModel(project.getProject());
        UpdateClasspathJob job = new UpdateClasspathJob(new IPluginModelBase[] { model });
        job.schedule();
        job.join();

        // re-validate options
        validateOption(project, JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_2);
        validateOption(project, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
        validateOption(project, JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
        validateOption(project, JavaCore.COMPILER_PB_ASSERT_IDENTIFIER, JavaCore.WARNING);
        validateOption(project, JavaCore.COMPILER_PB_ENUM_IDENTIFIER, JavaCore.WARNING);

    } finally {
        deleteProject("j2se14.ignore");
    }
}