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:com.siteview.mde.internal.core.project.BundleProjectDescription.java

License:Open Source License

/**
 * Initialize settings from the given project.
 * //ww  w  . j  ava 2s .c  om
 * @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(MDECore.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, MDECore.PLUGIN_ID, e.getMessage(), e));
        } catch (BundleException e) {
            throw new CoreException(new Status(IStatus.ERROR, MDECore.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 collect = new ArrayList();
            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 = (IBundleClasspathEntry[]) 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();
        IMonitorModelBase model = MonitorRegistry.findModel(project);
        if (model != null) {
            IMonitorBase base = model.getMonitorBase();
            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 strings = new ArrayList();
                    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((String) strings.get(i));
                        }
                        setBinIncludes(paths);
                    }
                }
            }
        }
    }
}

From source file:com.siteview.mde.internal.core.project.BundleProjectDescription.java

License:Open Source License

/**
 * Creates and returns a bundle claspath specifications for the given source.<library> build
 * entry//  w w w . j  ava 2  s .  co  m
 * 
 * @param project
 * @param entry
 * @param binary whether a binary folder (<code>true</code>) or source folder (<code>false</code>)
 * @return associated bundle classpath specifications or <code>null</code> if a malformed entry
 * @throws CoreException if unable to access Java build path
 */
private IBundleClasspathEntry[] getClasspathEntries(IProject project, IBuildEntry entry, boolean binary)
        throws CoreException {
    String[] tokens = entry.getTokens();
    IPath lib = null;
    if (binary) {
        lib = new Path(entry.getName().substring(IBuildEntry.OUTPUT_PREFIX.length()));
    } else {
        lib = new Path(entry.getName().substring(IBuildEntry.JAR_PREFIX.length()));
    }
    if (tokens != null && tokens.length > 0) {
        IBundleClasspathEntry[] bces = new IBundleClasspathEntry[tokens.length];
        for (int i = 0; i < tokens.length; i++) {
            IPath path = new Path(tokens[i]);
            IBundleClasspathEntry spec = null;
            if (binary) {
                spec = getBundleProjectService().newBundleClasspathEntry(null, path, lib);
            } else {
                IJavaProject jp = JavaCore.create(project);
                IPath output = null;
                if (jp.exists()) {
                    IClasspathEntry[] rawClasspath = jp.getRawClasspath();
                    for (int j = 0; j < rawClasspath.length; j++) {
                        IClasspathEntry cpe = rawClasspath[j];
                        if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                            if (cpe.getPath().removeFirstSegments(1).equals(path)) {
                                output = cpe.getOutputLocation();
                                if (output != null) {
                                    output = output.removeFirstSegments(1);
                                }
                                break;
                            }
                        }
                    }
                }
                spec = getBundleProjectService().newBundleClasspathEntry(path, output, lib);
            }
            bces[i] = spec;
        }
        return bces;
    }
    return null;
}

From source file:com.siteview.mde.internal.core.project.ProjectModifyOperation.java

License:Open Source License

/**
 * Creates or modifies a project based on the given description.
 * /* w w  w  . j  a v a 2s  .c om*/
 * @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) MDECore.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(MDECore.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, MDECore.PLUGIN_ID, Messages.ProjectModifyOperation_2, e));
        }
    }

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

From source file:com.siteview.mde.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//from   w ww . j  ava2s  . c om
 * @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 MDEPreferencesManager(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:com.sureassert.uc.builder.SAUCBuildWorker.java

License:Open Source License

public synchronized void processJavaProject(ProjectProcessEntity projectProcessEntity, //
        Set<ProjectProcessEntity> alreadyProcessed, boolean hasProjectChanged,
        IProgressMonitor progressMonitor) {

    // if (!isStandaloneBuild) {
    // try {/*w ww  .j  av  a2s  .c om*/
    // BasicUtils.debug("Starting build...");
    // int numErrors = BuildClient.getInstance().sendMessage(//
    // new StartBuildPPEMessage(new SerializableProjectProcessEntity(projectProcessEntity)));
    // } catch (Exception e) {
    // throw new RuntimeException(e);
    // } finally {
    // BasicUtils.debug("Build complete");
    // }
    // return;
    // }

    // JaCoCoClient jacocoClient = new JaCoCoClient(new SAUCEditorCoverageListenner());
    CoveragePrinter coveragePrinter = new CoveragePrinter(new SAUCEditorCoverageListenner());

    alreadyProcessed.add(projectProcessEntity);
    AspectJSigCache.clear();
    Map<IJavaProject, Set<ProcessEntity>> pEsByProject = null;
    IJavaProject javaProject = projectProcessEntity.getJavaProject();
    Map<IPath, Set<Signature>> affectedFileSigs = projectProcessEntity.getAffectedFileSigs();
    Set<IPath> affectedFiles = null;
    if (affectedFileSigs != null) {
        affectedFiles = affectedFileSigs.keySet();
        if (affectedFiles != null && affectedFiles.isEmpty())
            affectedFiles = null;
    }
    IWorkspace workspace = javaProject.getProject().getWorkspace();
    ProjectClassLoaders projectCLs = null;
    IFile file = null;
    IResource resource = javaProject.getResource();
    long startTime = System.nanoTime();
    sfFactory = new SourceFileFactory();
    javaPathData = new JavaPathData();
    InstrumentationSession jaCoCoSession = new InstrumentationSession(SaUCPreferences.getIsCoverageEnabled());
    boolean fullBuild = (affectedFiles == null);
    Set<ProcessEntity> allProcessEntities = null;
    IProject project = (IProject) resource;
    progressMonitor.beginTask("Processing " + project.getName(), 2000);
    try {
        BasicUtils.debug("-------------------------------------------------");
        BasicUtils.debug("Sureassert UC building project " + project.getName());
        BasicUtils.debug("ProcessEntities: " + projectProcessEntity.toString());

        // Get classloader using classpath of this project
        jaCoCoSession.start();
        projectCLs = ProjectClassLoaders.getClassLoaders(javaProject, affectedFiles == null, jaCoCoSession);
        PersistentDataFactory.getInstance().setCurrentUseCase(null, null, null, null, null, false, null, false);
        PersistentDataFactory.getInstance().setCurrentProject(project.getName(), //
                EclipseUtils.getRawPath(project).toString());
        PropertyFile propertyFile = new PropertyFile(new File(project.getLocation().toFile(), //
                PropertyFile.DEFAULT_PROPERTY_FILENAME));
        propertyFile.loadExtensions(projectCLs.projectCL);
        SourceModelFactory smFactory = new SourceModelFactory(projectCLs);
        UseCaseExecutionDelegate.INSTANCE.init(javaPathData, sfFactory, projectCLs.transformedCL);

        long getPEsStartTime = System.nanoTime();
        // Delete markers for all changed files
        if (hasProjectChanged)
            MarkerUtils.deleteAllMarkers(affectedFiles, project, sfFactory, javaPathData);
        ProcessEntityFactory peFactory = new ProcessEntityFactory(javaPathData, this);
        // Get ProcessEntities
        // Stage 1
        if (fullBuild) {
            ProjectClassLoaders.cleanTransformedDirs(javaProject);
            pEsByProject = peFactory.getProcessEntitiesFullBuild(resource, project, //
                    javaProject, projectCLs, hasProjectChanged, smFactory, sfFactory, //
                    new SubProgressMonitor(progressMonitor, 1000));
        } else {
            pEsByProject = peFactory.getProcessEntitiesIncBuild(affectedFileSigs, resource, project, //
                    javaProject, projectCLs, hasProjectChanged, smFactory, sfFactory, //
                    new SubProgressMonitor(progressMonitor, 1000));
        }
        BasicUtils.debug("Got ProcessEntities in " + ((System.nanoTime() - getPEsStartTime) / 1000000) + //
                "ms");
        Set<ProcessEntity> unprocessedEntities = pEsByProject.get(javaProject);
        if (unprocessedEntities == null)
            unprocessedEntities = new HashSet<ProcessEntity>();
        allProcessEntities = new HashSet<ProcessEntity>(unprocessedEntities);

        // Pre-process 1
        for (ProcessEntity processEntity : unprocessedEntities) {
            file = processEntity.getFile();
            SourceFile sourceFile = sfFactory.getSourceFile(file);
            // Delete internal/class level error markers
            MarkerUtils.deleteUCMarkers(sourceFile, -1, 1, null, null);
            MarkerUtils.deleteJUnitMarkers(sourceFile, -1, 1, null, null);

            executeNamedInstances(processEntity, projectCLs.transformedCL, smFactory, sfFactory);
            registerSINTypes(processEntity, projectCLs.transformedCL, smFactory, sfFactory);
        }

        // Set default values in UseCases and sort the PEs according to dependencies
        List<ProcessEntity> currentProcessEntities = new ArrayList<ProcessEntity>(unprocessedEntities);
        // System.out.println(">Unsorted: " + currentProcessEntities.toString());
        currentProcessEntities = ProcessEntity.setDefaultsAndSort(currentProcessEntities, //
                projectCLs.transformedCL, smFactory, sfFactory);
        // System.out.println(">Sorted: " + currentProcessEntities.toString());

        // Process
        // Stage 2
        // Iterate over unprocessed java files

        // jacocoClient.startSession();

        boolean lastPass = false;
        IProgressMonitor processStageMonitor = new SubProgressMonitor(progressMonitor, 1000);
        try {
            while (!currentProcessEntities.isEmpty()) {

                int peIndex = 0;
                processStageMonitor.beginTask("Executing", currentProcessEntities.size());
                for (ProcessEntity processEntity : currentProcessEntities) {
                    processStageMonitor.worked(1);
                    int percentComplete = (int) (((double) peIndex / (double) currentProcessEntities.size())
                            * 100);
                    file = processEntity.getFile();
                    SourceFile sourceFile = sfFactory.getSourceFile(file);
                    try {
                        if (javaProject != null && javaProject.exists()) {
                            processJavaType(processEntity, projectCLs, javaProject, smFactory, //
                                    sourceFile, processStageMonitor, percentComplete);
                        }
                        // File processed successfully, remove from list.
                        unprocessedEntities.remove(processEntity);

                    } catch (NamedInstanceNotFoundException ninfe) {
                        if (lastPass) {
                            // The last pass is activated when all files remain in the list; on
                            // this last pass we must report the error.
                            int lineNum = sourceFile.getLineNum(ninfe.getSourceLocation());
                            MarkerUtils.addMarker(sfFactory, javaPathData, sourceFile, ninfe.getMessage(),
                                    lineNum, //
                                    IMarker.SEVERITY_ERROR, false);
                            unprocessedEntities.remove(processEntity);
                        } else {
                            // The named instance may be loaded in a subsequent file,
                            // leave this file in the list.
                        }

                    } catch (SAUCBuildInterruptedError e) {
                        throw e;
                    } catch (LicenseBreachException e) {
                        throw e;
                    } catch (Throwable e) {
                        String msg = e instanceof CircularDependencyException ? "" : "Sureassert UC error: ";
                        MarkerUtils.addMarker(sfFactory, javaPathData, sourceFile,
                                msg + BasicUtils.toDisplayStr(e), -1, IMarker.SEVERITY_ERROR, false);

                        // iretrievable error, remove from list.
                        unprocessedEntities.remove(processEntity);
                    }
                    peIndex++;
                } // end execute process entity loop

                if (lastPass)
                    break;

                if (unprocessedEntities.size() == currentProcessEntities.size()) {
                    // Every file resulted in a retry request for the next pass;
                    // therefore on the next and last pass they must report their errors.
                    lastPass = true;
                }

                // Replace working list with cut-down list
                currentProcessEntities = new ArrayList<ProcessEntity>(unprocessedEntities);
            }
        } finally {
            processStageMonitor.done();
        }

        addSourceModelErrors(smFactory);

    } catch (SAUCBuildInterruptedError e) {
        throw e;
    } catch (Throwable e) {
        if (e instanceof LicenseBreachException) {
            PersistentDataFactory.getInstance().registerLicenseBreached();
        } else if (e instanceof CompileErrorsException) {
            try {
                handleCompileErrors((CompileErrorsException) e, sfFactory);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        } else {
            if (e instanceof SAException)
                file = ((SAException) e).getFile();
            EclipseUtils.reportError(e);
            if (file != null) {
                String msg = e instanceof CircularDependencyException ? "" : "Sureassert UC error: ";
                try {
                    MarkerUtils.addMarker(sfFactory, javaPathData, sfFactory.getSourceFile(file),
                            msg + BasicUtils.toDisplayStr(e), -1, IMarker.SEVERITY_ERROR, false);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }
        // PersistentDataFactory.getInstance().setNewPersistentStore(javaProject.getProject().getName());

    } finally {

        // Add coverage markers

        jaCoCoSession.end(sfFactory, javaPathData, new SubProgressMonitor(progressMonitor, 1000), this);

        // jacocoClient.dumpExecData();
        // jacocoClient.printInfo(sfFactory, javaPathData, new
        // SubProgressMonitor(progressMonitor, 1000), this);
        // coveragePrinter.printInfo(sfFactory, javaPathData, new
        // SubProgressMonitor(progressMonitor, 1000), this, null);

        // Update coverage report
        Set<IPath> checkPaths = javaPathData.getAllCachedFilePaths();
        checkPaths.addAll(EclipseUtils.toPaths(PersistentDataFactory.getInstance().getMarkedFilePaths()));
        if (allProcessEntities != null)
            checkPaths.addAll(ProcessEntity.getPaths(allProcessEntities));
        // new CoverageReporter().reportCoverage(checkPaths, javaPathData, workspace,
        // sfFactory);

        // Clear caches
        NamedInstanceFactory.getInstance().clear();
        PersistentDataFactory.getInstance().clearMarkedFilePaths();
        UseCaseExecutionDelegate.INSTANCE.dispose();
        if (projectCLs != null)
            projectCLs.clear();
        sfFactory = null;
        BasicUtils.debug("-------------------------------------------------");
        BasicUtils.debug("Sureassert UC builder finished \"" + javaProject.getElementName() + //
                "\" in " + ((System.nanoTime() - startTime) / 1000000) + "ms");

        // Get foreign client project process entities that now require building
        if (pEsByProject != null) {
            for (Entry<IJavaProject, Set<ProcessEntity>> projectPEs : pEsByProject.entrySet()) {
                if (!projectPEs.getKey().equals(javaProject)) {
                    ProjectProcessEntity ppe = ProjectProcessEntity.newFromProcessEntities(//
                            projectPEs.getKey(), projectPEs.getValue());
                    if (!alreadyProcessed.contains(ppe))
                        processJavaProject(ppe, alreadyProcessed, false,
                                new SubProgressMonitor(progressMonitor, 0));
                }
            }
        }
        progressMonitor.setTaskName("Building workspace"); // occasional Eclipse bug workaround
        progressMonitor.done();
    }
}

From source file:com.sympedia.genfw.util.ClasspathHelper.java

License:Open Source License

public static ClassLoader getJavaProjectClassLoader(String projectName, ClassLoader parentClassLoader) {
    IJavaProject javaProject = getJavaProject(projectName);
    if (javaProject == null || !javaProject.exists()) {
        return null;
    }//from w ww.j a  v a  2 s. co  m

    ClassLoader result = createJavaProjectClassLoader(javaProject, parentClassLoader);
    return result;
}

From source file:com.technophobia.substeps.junit.action.OpenEditorAction.java

License:Open Source License

private IType internalFindType(final IJavaProject project, final String testClassName,
        final Set<IJavaProject> visitedProjects, final IProgressMonitor monitor) throws JavaModelException {
    try {//  w  w  w  .  java 2 s  . c o m
        if (visitedProjects.contains(project))
            return null;
        monitor.beginTask("", 2); //$NON-NLS-1$
        IType type = project.findType(testClassName, new SubProgressMonitor(monitor, 1));
        if (type != null)
            return type;
        // fix for bug 87492: visit required projects explicitly to also
        // find not exported types
        visitedProjects.add(project);
        final IJavaModel javaModel = project.getJavaModel();
        final String[] requiredProjectNames = project.getRequiredProjectNames();
        final IProgressMonitor reqMonitor = new SubProgressMonitor(monitor, 1);
        reqMonitor.beginTask("", requiredProjectNames.length); //$NON-NLS-1$
        for (final String requiredProjectName : requiredProjectNames) {
            final IJavaProject requiredProject = javaModel.getJavaProject(requiredProjectName);
            if (requiredProject.exists()) {
                type = internalFindType(requiredProject, testClassName, visitedProjects,
                        new SubProgressMonitor(reqMonitor, 1));
                if (type != null)
                    return type;
            }
        }
        return null;
    } finally {
        monitor.done();
    }
}

From source file:com.technophobia.substeps.junit.launcher.migration.SubstepsMigrationDelegate.java

License:Open Source License

/**
 * Returns a resource mapping for the given launch configuration, or
 * <code>null</code> if none.
 * /*ww  w .  j a v a  2  s.  co m*/
 * @param config
 *            working copy
 * @return resource or <code>null</code>
 * @throws CoreException
 *             if an exception occurs mapping resource
 */
private static IResource getResource(final ILaunchConfiguration config) throws CoreException {
    final String projName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
            (String) null);
    final String containerHandle = config.getAttribute(SubstepsLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
            (String) null);
    final String typeName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
            (String) null);
    IJavaElement element = null;
    if (containerHandle != null && containerHandle.length() > 0) {
        element = JavaCore.create(containerHandle);
    } else if (projName != null && Path.ROOT.isValidSegment(projName)) {
        final IJavaProject javaProject = getJavaModel().getJavaProject(projName);
        if (javaProject.exists()) {
            if (typeName != null && typeName.length() > 0) {
                element = javaProject.findType(typeName);
            }
            if (element == null) {
                element = javaProject;
            }
        } else {
            final IProject project = javaProject.getProject();
            if (project.exists() && !project.isOpen()) {
                return project;
            }
        }
    }
    IResource resource = null;
    if (element != null) {
        resource = element.getResource();
    }
    return resource;
}

From source file:com.technophobia.substeps.junit.launcher.SubstepsLaunchConfigurationDelegate.java

License:Open Source License

/**
 * Performs a check on the launch configuration's attributes. If an
 * attribute contains an invalid value, a {@link CoreException} with the
 * error is thrown.//from w  ww .j av  a  2s .c om
 * 
 * @param configuration
 *            the launch configuration to verify
 * @param launch
 *            the launch to verify
 * @param monitor
 *            the progress monitor to use
 * @throws CoreException
 *             an exception is thrown when the verification fails
 */
protected void preLaunchCheck(final ILaunchConfiguration configuration, final ILaunch launch,
        final IProgressMonitor monitor) throws CoreException {
    try {
        final IJavaProject javaProject = getJavaProject(configuration);
        if ((javaProject == null) || !javaProject.exists()) {
            abort(SubstepsFeatureMessages.SubstepsLaunchConfigurationDelegate_error_invalidproject, null,
                    IJavaLaunchConfigurationConstants.ERR_NOT_A_JAVA_PROJECT);
        }
    } finally {
        monitor.done();
    }
}

From source file:com.windowtester.eclipse.ui_tool.WTConvertAPIContextBuilderTool.java

License:Open Source License

/**
 * Recursively iterate over all elements in the project looking for WindowTester
 * classes and members./* w w  w  .ja v a 2s. c o  m*/
 * 
 * @param proj the java project (not <code>null</code>)
 */
private void scanProject(IProject proj) throws JavaModelException {
    if (!proj.exists())
        return;
    String projName = proj.getName();
    if (!projName.startsWith("com.windowtester.") || projName.indexOf('_') != -1)
        return;
    if (projName.endsWith(".recorder") || projName.endsWith(".help") || projName.endsWith(".codegen"))
        return;
    if (projName.equals("com.windowtester.eclipse.ui"))
        return;
    IJavaProject javaProject = JavaCore.create(proj);
    if (!javaProject.exists())
        return;
    IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
    for (int i = 0; i < roots.length; i++)
        scanPackageRoot(roots[i]);
}