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

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

Introduction

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

Prototype

IProject getProject();

Source Link

Document

Returns the IProject on which this IJavaProject was created.

Usage

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

@Override
public int aboutToBuild(IJavaProject project) {
    if (debug.isDebugging())
        debug.trace(String.format("About to build project: %s", project.getElementName())); //$NON-NLS-1$

    int result = READY_FOR_BUILD;

    ProjectState state = null;//w w  w .  j a v  a2  s  . c o  m
    try {
        Object value = project.getProject().getSessionProperty(PROP_STATE);
        if (value instanceof SoftReference<?>) {
            @SuppressWarnings("unchecked")
            SoftReference<ProjectState> ref = (SoftReference<ProjectState>) value;
            state = ref.get();
        }
    } catch (CoreException e) {
        Activator.getDefault().getLog().log(e.getStatus());
    }

    if (state == null) {
        try {
            state = loadState(project.getProject());
        } catch (IOException e) {
            Activator.getDefault().getLog()
                    .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error loading project state.", e)); //$NON-NLS-1$
        }

        if (state == null) {
            state = new ProjectState();
            result = NEEDS_FULL_BUILD;
        }

        try {
            project.getProject().setSessionProperty(PROP_STATE, new SoftReference<ProjectState>(state));
        } catch (CoreException e) {
            Activator.getDefault().getLog().log(e.getStatus());
        }
    }

    processingContext.put(project, new ProjectContext(state));

    String path = Platform.getPreferencesService().getString(Activator.PLUGIN_ID, Activator.PREF_PATH,
            Activator.DEFAULT_PATH,
            new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE });
    if (!path.equals(state.getPath())) {
        state.setPath(path);
        result = NEEDS_FULL_BUILD;
    }

    String errorLevelStr = Platform.getPreferencesService().getString(Activator.PLUGIN_ID,
            Activator.PREF_VALIDATION_ERROR_LEVEL, ValidationErrorLevel.error.name(),
            new IScopeContext[] { new ProjectScope(project.getProject()), InstanceScope.INSTANCE });
    ValidationErrorLevel errorLevel;
    try {
        errorLevel = ValidationErrorLevel.valueOf(errorLevelStr);
    } catch (IllegalArgumentException e) {
        errorLevel = ValidationErrorLevel.error;
    }

    if (errorLevel != state.getErrorLevel()) {
        state.setErrorLevel(errorLevel);
        result = NEEDS_FULL_BUILD;
    }

    return result;
}

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

@Override
public void buildFinished(IJavaProject project) {
    ProjectContext projectContext = processingContext.remove(project);
    if (projectContext != null) {
        ProjectState state = projectContext.getState();
        // check if unprocessed CUs still exist; if not, their mapped files are now abandoned
        Map<String, Collection<String>> cuMap = state.getMappings();
        HashSet<String> abandoned = new HashSet<String>(projectContext.getAbandoned());
        for (String cuKey : projectContext.getUnprocessed()) {
            boolean exists = false;
            try {
                IType cuType = project.findType(cuKey);
                IResource file;//  w  ww.ja va 2s .  c o m
                if (cuType != null && (file = cuType.getResource()) != null && file.exists())
                    exists = true;
            } catch (JavaModelException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }

            if (!exists) {
                if (debug.isDebugging())
                    debug.trace(String.format("Mapped CU %s no longer exists.", cuKey)); //$NON-NLS-1$

                Collection<String> dsKeys = cuMap.remove(cuKey);
                if (dsKeys != null)
                    abandoned.addAll(dsKeys);
            }
        }

        // remove CUs with no mapped DS models
        HashSet<String> retained = new HashSet<String>();
        for (Iterator<Map.Entry<String, Collection<String>>> i = cuMap.entrySet().iterator(); i.hasNext();) {
            Map.Entry<String, Collection<String>> entry = i.next();
            Collection<String> dsKeys = entry.getValue();
            if (dsKeys.isEmpty())
                i.remove();
            else
                retained.addAll(dsKeys);
        }

        // retain abandoned files that are still mapped elsewhere
        abandoned.removeAll(retained);

        if (projectContext.isChanged()) {
            try {
                saveState(project.getProject(), state);
            } catch (IOException e) {
                Activator.getDefault().getLog()
                        .log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error saving file mappings.", e)); //$NON-NLS-1$
            }
        }

        // delete all abandoned files
        ArrayList<IStatus> deleteStatuses = new ArrayList<IStatus>(2);
        for (String dsKey : abandoned) {
            IPath path = Path.fromPortableString(dsKey);

            if (debug.isDebugging())
                debug.trace(String.format("Deleting %s", path)); //$NON-NLS-1$

            IFile file = PDEProject.getBundleRelativeFile(project.getProject(), path);
            if (file.exists()) {
                try {
                    file.delete(true, null);
                } catch (CoreException e) {
                    deleteStatuses.add(e.getStatus());
                }
            }
        }

        if (!deleteStatuses.isEmpty())
            Activator.getDefault().getLog()
                    .log(new MultiStatus(Activator.PLUGIN_ID, 0,
                            deleteStatuses.toArray(new IStatus[deleteStatuses.size()]),
                            "Error deleting generated files.", null)); //$NON-NLS-1$

        writeManifest(project.getProject(), retained, abandoned);
        writeBuildProperties(project.getProject(), retained, abandoned);
    }

    if (debug.isDebugging())
        debug.trace(String.format("Build finished for project: %s", project.getElementName())); //$NON-NLS-1$
}

From source file:ca.ecliptical.pde.internal.ds.DSAnnotationCompilationParticipant.java

License:Open Source License

private void processAnnotations(IJavaProject javaProject, Map<ICompilationUnit, BuildContext> fileMap) {
    ASTParser parser = ASTParser.newParser(AST.JLS4);
    parser.setResolveBindings(true);/*from   ww  w  . j a v a 2 s.c o  m*/
    parser.setBindingsRecovery(true);
    parser.setProject(javaProject);
    parser.setKind(ASTParser.K_COMPILATION_UNIT);

    ProjectContext projectContext = processingContext.get(javaProject);
    ProjectState state = projectContext.getState();

    parser.setIgnoreMethodBodies(state.getErrorLevel() == ValidationErrorLevel.none);

    ICompilationUnit[] cuArr = fileMap.keySet().toArray(new ICompilationUnit[fileMap.size()]);
    Map<ICompilationUnit, Collection<IDSModel>> models = new HashMap<ICompilationUnit, Collection<IDSModel>>();
    parser.createASTs(cuArr, new String[0], new AnnotationProcessor(models, fileMap, state.getErrorLevel()),
            null);

    Map<String, Collection<String>> cuMap = state.getMappings();
    Collection<String> unprocessed = projectContext.getUnprocessed();
    Collection<String> abandoned = projectContext.getAbandoned();

    IPath outputPath = new Path(state.getPath()).addTrailingSeparator();

    // save each model to a file; track changes to mappings
    for (Map.Entry<ICompilationUnit, Collection<IDSModel>> entry : models.entrySet()) {
        ICompilationUnit cu = entry.getKey();
        IType cuType = cu.findPrimaryType();
        if (cuType == null) {
            if (debug.isDebugging())
                debug.trace(String.format("CU %s has no primary type!", cu.getElementName())); //$NON-NLS-1$

            continue; // should never happen
        }

        String cuKey = cuType.getFullyQualifiedName();

        unprocessed.remove(cuKey);
        Collection<String> oldDSKeys = cuMap.remove(cuKey);
        Collection<String> dsKeys = new HashSet<String>();
        cuMap.put(cuKey, dsKeys);

        for (IDSModel model : entry.getValue()) {
            String compName = model.getDSComponent().getAttributeName();
            IPath filePath = outputPath.append(compName).addFileExtension("xml"); //$NON-NLS-1$
            String dsKey = filePath.toPortableString();

            // exclude file from garbage collection
            if (oldDSKeys != null)
                oldDSKeys.remove(dsKey);

            // add file to CU mapping
            dsKeys.add(dsKey);

            // actually save the file
            IFile compFile = PDEProject.getBundleRelativeFile(javaProject.getProject(), filePath);
            model.setUnderlyingResource(compFile);

            try {
                ensureDSProject(compFile.getProject());
            } catch (CoreException e) {
                Activator.getDefault().getLog().log(e.getStatus());
            }

            IPath parentPath = compFile.getParent().getProjectRelativePath();
            if (!parentPath.isEmpty()) {
                IFolder folder = javaProject.getProject().getFolder(parentPath);
                try {
                    ensureExists(folder);
                } catch (CoreException e) {
                    Activator.getDefault().getLog().log(e.getStatus());
                    model.dispose();
                    continue;
                }
            }

            if (debug.isDebugging())
                debug.trace(String.format("Saving model: %s", compFile.getFullPath())); //$NON-NLS-1$

            model.save();
            model.dispose();
        }

        // track abandoned files (may be garbage)
        if (oldDSKeys != null)
            abandoned.addAll(oldDSKeys);
    }
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAJavaProjectHelper.java

License:Open Source License

/**
 * <p>/*www . j  a  va2 s  .  c o  m*/
 * Creates a Java project with an appropriate nature, classpath, and source
 * folder in the workspace.
 * </p>
 * 
 * @param projectName
 * @return
 * @throws Exception
 */
public IJavaProject setupJavaProject(String projectName) throws Exception {
    IJavaProject javaProject = null;

    IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
    if (!project.exists()) {
        try {
            //            workbenchLock.lock();
            fFirstPage = new NewJavaProjectWizardPageOne();
            fFirstPage.setProjectName(projectName);
            createProject();
            javaProject = fJavaProject;
        } finally {
            //            workbenchLock.unlock();
        }
    } else {
        javaProject = JavaCore.create(project);
    }

    javaProject.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);

    return javaProject;
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAJavaProjectHelper.java

License:Open Source License

protected void initializeBuildPath(IJavaProject javaProject) throws CoreException {

    try {/* www .j a  v  a 2  s  .  c o  m*/
        IClasspathEntry[] entries = null;
        IPath outputLocation = null;
        IProject project = javaProject.getProject();

        if (fKeepContent) {
            if (!project.getFile(FILENAME_CLASSPATH).exists()) {
                final ClassPathDetector detector = new ClassPathDetector(fCurrProject,
                        new NullProgressMonitor());
                entries = detector.getClasspath();
                outputLocation = detector.getOutputLocation();
                if (entries.length == 0) {
                    entries = null;
                }
            }
        } else {
            List cpEntries = new ArrayList();
            IWorkspaceRoot root = project.getWorkspace().getRoot();

            IClasspathEntry[] sourceClasspathEntries = fFirstPage.getSourceClasspathEntries();
            for (int i = 0; i < sourceClasspathEntries.length; i++) {
                IPath path = sourceClasspathEntries[i].getPath();
                if (path.segmentCount() > 1) {
                    IFolder folder = root.getFolder(path);
                    CoreUtility.createFolder(folder, true, true, new NullProgressMonitor());
                }
                cpEntries.add(sourceClasspathEntries[i]);
            }

            cpEntries.addAll(Arrays.asList(fFirstPage.getDefaultClasspathEntries()));

            entries = (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);

            outputLocation = fFirstPage.getOutputLocation();
            if (outputLocation.segmentCount() > 1) {
                IFolder folder = root.getFolder(outputLocation);
                CoreUtility.createDerivedFolder(folder, true, true, new NullProgressMonitor());
            }
        }

        init(javaProject, outputLocation, entries, false);
    } catch (Exception e) {
    }
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAJavaProjectHelper.java

License:Open Source License

public void init(IJavaProject jproject, IPath defaultOutputLocation, IClasspathEntry[] defaultEntries,
        boolean defaultsOverrideExistingClasspath) {
    if (!defaultsOverrideExistingClasspath && jproject.exists()
            && jproject.getProject().getFile(".classpath").exists()) {
        defaultOutputLocation = null;/*from   w  ww .jav a  2  s.c  om*/
        defaultEntries = null;
    }
    fJavaProject = jproject;
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAJavaProjectHelper.java

License:Open Source License

private List getDefaultClassPath(IJavaProject jproj) {
    List list = new ArrayList();
    IResource srcFolder;/*from ww w.java2  s . c om*/
    IPreferenceStore store = PreferenceConstants.getPreferenceStore();
    String sourceFolderName = store.getString(PreferenceConstants.SRCBIN_SRCNAME);
    if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
        srcFolder = jproj.getProject().getFolder(sourceFolderName);
    } else {
        srcFolder = jproj.getProject();
    }

    list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));

    IClasspathEntry[] jreEntries = PreferenceConstants.getDefaultJRELibrary();
    list.addAll(getExistingEntries(jreEntries));
    return list;
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAUtil.java

License:Open Source License

public static CompilationUnit getCU(File file, PPAOptions options, String requestName) {
    CompilationUnit cu = null;/*from   w w  w.j  a  v a2 s  . co m*/
    String fileName = file.getName();

    try {
        String packageName = getPackageFromFile(file);
        String ppaProjectName = getPPAProjectName(requestName);
        PPAJavaProjectHelper helper = new PPAJavaProjectHelper();
        IJavaProject javaProject = helper.setupJavaProject(ppaProjectName);
        IFile newFile = PPAResourceUtil.copyJavaSourceFile(javaProject.getProject(), file, packageName,
                fileName);
        cu = getCU(newFile, options);
    } catch (Exception e) {
        logger.error("Error while getting CU from PPA", e);
    }

    return cu;
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAUtil.java

License:Open Source License

public static List<CompilationUnit> getCUs(List<File> files, PPAOptions options, String requestName) {
    List<CompilationUnit> cus = new ArrayList<CompilationUnit>();
    List<IFile> iFiles = new ArrayList<IFile>();

    for (File file : files) {
        String fileName = file.getName();
        try {/*w  w  w. j a  va  2s. c  o m*/
            String packageName = getPackageFromFile(file);
            String ppaProjectName = getPPAProjectName(requestName);
            PPAJavaProjectHelper helper = new PPAJavaProjectHelper();
            IJavaProject javaProject = helper.setupJavaProject(ppaProjectName);
            IFile newFile = PPAResourceUtil.copyJavaSourceFile(javaProject.getProject(), file, packageName,
                    fileName);
            iFiles.add(newFile);
            System.out.println(fileName);
        } catch (Exception e) {
            logger.error("Error while getting IFile from PPA", e);
        }
    }

    for (IFile file : iFiles) {
        logger.info("Getting CU for file: " + file.getLocation().toOSString());
        CompilationUnit cu = getCU(file, options);
        if (cu == null) {
            cu = getCUNoPPA(file);
        }
        cus.add(cu);
    }

    return cus;
}

From source file:ca.mcgill.cs.swevo.ppa.ui.PPAUtil.java

License:Open Source License

public static ASTNode getSnippet(File file, PPAOptions options, boolean isTypeBody, String requestName) {
    CompilationUnit cu = null;// w  ww .ja  va 2  s .c  o m
    try {
        String ppaProjectName = getPPAProjectName(requestName);
        PPAJavaProjectHelper helper = new PPAJavaProjectHelper();
        IJavaProject javaProject = helper.setupJavaProject(ppaProjectName);
        IFile newFile = PPAResourceUtil.copyJavaSourceFileSnippet(javaProject.getProject(), file,
                SnippetUtil.SNIPPET_PACKAGE, SnippetUtil.SNIPPET_FILE, isTypeBody);
        cu = getCU(newFile, options);
    } catch (Exception e) {
        logger.error("Error while getting CU from PPA", e);
    }

    return cu;
}