Example usage for org.eclipse.jdt.internal.core JavaModelManager getJavaModel

List of usage examples for org.eclipse.jdt.internal.core JavaModelManager getJavaModel

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.core JavaModelManager getJavaModel.

Prototype

public final JavaModel getJavaModel() 

Source Link

Document

Returns the handle to the active Java Model.

Usage

From source file:com.codenvy.ide.ext.java.server.internal.core.search.HierarchyScope.java

License:Open Source License

private IPath[] computeProjectsAndJars(IType type) throws JavaModelException {
    HashSet set = new HashSet();
    IPackageFragmentRoot root = (IPackageFragmentRoot) type.getPackageFragment().getParent();
    if (root.isArchive()) {
        // add the root
        set.add(root.getPath());/*from   w w w . j a v  a  2 s .  c o m*/
        // add all projects that reference this archive and their dependents
        IPath rootPath = root.getPath();
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject[] projects = model.getJavaProjects();
        HashSet visited = new HashSet();
        for (int i = 0; i < projects.length; i++) {
            JavaProject project = (JavaProject) projects[i];
            IClasspathEntry entry = project.getClasspathEntryFor(rootPath);
            if (entry != null) {
                // add the project and its binary pkg fragment roots
                IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
                set.add(project.getPath());
                for (int k = 0; k < roots.length; k++) {
                    IPackageFragmentRoot pkgFragmentRoot = roots[k];
                    if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
                        set.add(pkgFragmentRoot.getPath());
                    }
                }
                // add the dependent projects
                computeDependents(project, set, visited);
            }
        }
    } else {
        // add all the project's pkg fragment roots
        IJavaProject project = (IJavaProject) root.getParent();
        IPackageFragmentRoot[] roots = project.getAllPackageFragmentRoots();
        for (int i = 0; i < roots.length; i++) {
            IPackageFragmentRoot pkgFragmentRoot = roots[i];
            if (pkgFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
                set.add(pkgFragmentRoot.getPath());
            } else {
                set.add(pkgFragmentRoot.getParent().getPath());
            }
        }
        // add the dependent projects
        computeDependents(project, set, new HashSet());
    }
    IPath[] result = new IPath[set.size()];
    set.toArray(result);
    return result;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

/**
 * Returns whether elements of the given project or jar can see the given focus (an IJavaProject or
 * a JarPackageFragmentRot) either because the focus is part of the project or the jar, or because it is
 * accessible throught the project's classpath
 *//*from  w  w w.  j av  a  2  s  .c om*/
public static boolean canSeeFocus(SearchPattern pattern, IPath projectOrJarPath) {
    try {
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject project = getJavaProject(projectOrJarPath, model);
        IJavaElement[] focuses = getFocusedElementsAndTypes(pattern, project, null);
        if (focuses.length == 0)
            return false;
        if (project != null) {
            return canSeeFocus(focuses, (JavaProject) project, null);
        }

        // projectOrJarPath is a jar
        // it can see the focus only if it is on the classpath of a project that can see the focus
        IJavaProject[] allProjects = model.getJavaProjects();
        for (int i = 0, length = allProjects.length; i < length; i++) {
            JavaProject otherProject = (JavaProject) allProjects[i];
            IClasspathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
            if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                if (canSeeFocus(focuses, otherProject, null)) {
                    return true;
                }
            }
        }
        return false;
    } catch (JavaModelException e) {
        return false;
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.IndexSelector.java

License:Open Source License

private void initializeIndexLocations() {
    IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
    // use a linked set to preserve the order during search: see bug 348507
    LinkedHashSet locations = new LinkedHashSet();
    IJavaElement focus = MatchLocator.projectOrJarFocus(this.pattern);
    if (focus == null) {
        for (int i = 0; i < projectsAndJars.length; i++) {
            IPath path = projectsAndJars[i];
            Object target = new File(path.toOSString());//JavaModel.getTarget(path, false/*don't check existence*/);
            if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
            locations.add(indexManager.computeIndexLocation(path));
        }//w w w  .j  ava2s.c  o m
    } else {
        try {
            // See whether the state builder might be used to reduce the number of index locations

            // find the projects from projectsAndJars that see the focus then walk those projects looking for the jars from projectsAndJars
            int length = projectsAndJars.length;
            JavaProject[] projectsCanSeeFocus = new JavaProject[length];
            SimpleSet visitedProjects = new SimpleSet(length);
            int projectIndex = 0;
            SimpleSet externalLibsToCheck = new SimpleSet(length);
            ObjectVector superTypes = new ObjectVector();
            IJavaElement[] focuses = getFocusedElementsAndTypes(this.pattern, focus, superTypes);
            char[][][] focusQualifiedNames = null;
            boolean isAutoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
            if (isAutoBuilding && focus instanceof IJavaProject) {
                focusQualifiedNames = getQualifiedNames(superTypes);
            }
            IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
            for (int i = 0; i < length; i++) {
                IPath path = projectsAndJars[i];
                JavaProject project = (JavaProject) getJavaProject(path, model);
                if (project != null) {
                    visitedProjects.add(project);
                    if (canSeeFocus(focuses, project, focusQualifiedNames)) {
                        locations.add(indexManager.computeIndexLocation(path));
                        projectsCanSeeFocus[projectIndex++] = project;
                    }
                } else {
                    externalLibsToCheck.add(path);
                }
            }
            for (int i = 0; i < projectIndex && externalLibsToCheck.elementSize > 0; i++) {
                IClasspathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath();
                for (int j = entries.length; --j >= 0;) {
                    IClasspathEntry entry = entries[j];
                    if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        IPath path = entry.getPath();
                        if (externalLibsToCheck.remove(path) != null) {
                            Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                            if (target instanceof IFolder) // case of an external folder
                                path = ((IFolder) target).getFullPath();
                            locations.add(indexManager.computeIndexLocation(path));
                        }
                    }
                }
            }
            // jar files can be included in the search scope without including one of the projects that references them, so scan all projects that have not been visited
            if (externalLibsToCheck.elementSize > 0) {
                IJavaProject[] allProjects = model.getJavaProjects();
                for (int i = 0, l = allProjects.length; i < l && externalLibsToCheck.elementSize > 0; i++) {
                    JavaProject project = (JavaProject) allProjects[i];
                    if (!visitedProjects.includes(project)) {
                        IClasspathEntry[] entries = project.getResolvedClasspath();
                        for (int j = entries.length; --j >= 0;) {
                            IClasspathEntry entry = entries[j];
                            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                                IPath path = entry.getPath();
                                if (externalLibsToCheck.remove(path) != null) {
                                    Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                                    if (target instanceof IFolder) // case of an external folder
                                        path = ((IFolder) target).getFullPath();
                                    locations.add(indexManager.computeIndexLocation(path));
                                }
                            }
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
            // ignored
        }
    }

    locations.remove(null); // Ensure no nulls
    this.indexLocations = (IndexLocation[]) locations.toArray(new IndexLocation[locations.size()]);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.JavaWorkspaceScope.java

License:Open Source License

public IPath[] enclosingProjectsAndJars() {
    IPath[] result = this.enclosingPaths;
    if (result != null) {
        return result;
    }//from   www  .  j  a v  a  2 s.c  om
    long start = BasicSearchEngine.VERBOSE ? System.currentTimeMillis() : -1;
    try {
        IJavaProject[] projects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
        // use a linked set to preserve the order during search: see bug 348507
        Set paths = new LinkedHashSet(projects.length * 2);
        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project full path
            IPath projectPath = javaProject.getProject().getFullPath();
            paths.add(projectPath);
        }

        // add the project source paths first in a separate loop above
        // to ensure source files always get higher precedence during search.
        // see bug 348507

        for (int i = 0, length = projects.length; i < length; i++) {
            JavaProject javaProject = (JavaProject) projects[i];

            // Add project libraries paths
            IClasspathEntry[] entries = javaProject.getResolvedClasspath();
            for (int j = 0, eLength = entries.length; j < eLength; j++) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                    IPath path = entry.getPath();
                    Object target = JavaModel.getTarget(path, false/*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                        path = ((IFolder) target).getFullPath();
                    paths.add(entry.getPath());
                }
            }
        }
        result = new IPath[paths.size()];
        paths.toArray(result);
        return this.enclosingPaths = result;
    } catch (JavaModelException e) {
        Util.log(e, "Exception while computing workspace scope's enclosing projects and jars"); //$NON-NLS-1$
        return new IPath[0];
    } finally {
        if (BasicSearchEngine.VERBOSE) {
            long time = System.currentTimeMillis() - start;
            int length = result == null ? 0 : result.length;
            Util.verbose("JavaWorkspaceScope.enclosingProjectsAndJars: " + length + " paths computed in " + time //$NON-NLS-1$//$NON-NLS-2$
                    + "ms."); //$NON-NLS-1$
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

/**
 * Locate the matches in the given files and report them using the search requestor.
 *//*  w ww.ja v  a 2  s.  co m*/
public void locateMatches(SearchDocument[] searchDocuments) throws CoreException {
    if (this.patternLocator == null)
        return;
    int docsLength = searchDocuments.length;
    int progressLength = docsLength;
    if (BasicSearchEngine.VERBOSE) {
        System.out.println("Locating matches in documents ["); //$NON-NLS-1$
        for (int i = 0; i < docsLength; i++)
            System.out.println("\t" + searchDocuments[i]); //$NON-NLS-1$
        System.out.println("]"); //$NON-NLS-1$
    }
    IJavaProject[] javaModelProjects = null;
    if (this.searchPackageDeclaration) {
        javaModelProjects = JavaModelManager.getJavaModelManager().getJavaModel().getJavaProjects();
        progressLength += javaModelProjects.length;
    }

    // init infos for progress increasing
    int n = progressLength < 1000 ? Math.min(Math.max(progressLength / 200 + 1, 2), 4)
            : 5 * (progressLength / 1000);
    this.progressStep = progressLength < n ? 1 : progressLength / n; // step should not be 0
    this.progressWorked = 0;

    // extract working copies
    ArrayList copies = new ArrayList();
    for (int i = 0; i < docsLength; i++) {
        SearchDocument document = searchDocuments[i];
        if (document instanceof WorkingCopyDocument) {
            copies.add(((WorkingCopyDocument) document).workingCopy);
        }
    }
    int copiesLength = copies.size();
    this.workingCopies = new org.eclipse.jdt.core.ICompilationUnit[copiesLength];
    copies.toArray(this.workingCopies);

    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    this.bindings = new SimpleLookupTable();
    try {
        // optimize access to zip files during search operation
        manager.cacheZipFiles(this);

        // initialize handle factory (used as a cache of handles so as to optimize space)
        if (this.handleFactory == null)
            this.handleFactory = new HandleFactory();

        if (this.progressMonitor != null) {
            this.progressMonitor.beginTask("", searchDocuments.length); //$NON-NLS-1$
        }

        // initialize pattern for polymorphic search (i.e. method reference pattern)
        this.patternLocator.initializePolymorphicSearch(this);

        JavaProject previousJavaProject = null;
        PossibleMatchSet matchSet = new PossibleMatchSet();
        Util.sort(searchDocuments, new Util.Comparer() {
            public int compare(Object a, Object b) {
                return ((SearchDocument) a).getPath().compareTo(((SearchDocument) b).getPath());
            }
        });
        int displayed = 0; // progress worked displayed
        String previousPath = null;
        SearchParticipant searchParticipant = null;
        for (int i = 0; i < docsLength; i++) {
            if (this.progressMonitor != null && this.progressMonitor.isCanceled()) {
                throw new OperationCanceledException();
            }

            // skip duplicate paths
            SearchDocument searchDocument = searchDocuments[i];
            if (searchParticipant == null) {
                searchParticipant = searchDocument.getParticipant();
            }
            searchDocuments[i] = null; // free current document
            String pathString = searchDocument.getPath();
            if (i > 0 && pathString.equals(previousPath)) {
                if (this.progressMonitor != null) {
                    this.progressWorked++;
                    if ((this.progressWorked % this.progressStep) == 0)
                        this.progressMonitor.worked(this.progressStep);
                }
                displayed++;
                continue;
            }
            previousPath = pathString;

            Openable openable;
            org.eclipse.jdt.core.ICompilationUnit workingCopy = null;
            if (searchDocument instanceof WorkingCopyDocument) {
                workingCopy = ((WorkingCopyDocument) searchDocument).workingCopy;
                openable = (Openable) workingCopy;
            } else {
                openable = this.handleFactory.createOpenable(pathString, this.scope);
            }
            //         if (openable == null) {
            //            if (this.progressMonitor != null) {
            //               this.progressWorked++;
            //               if ((this.progressWorked%this.progressStep)==0) this.progressMonitor.worked(this.progressStep);
            //            }
            //            displayed++;
            //            continue; // match is outside classpath
            //         }

            // create new parser and lookup environment if this is a new project
            IResource resource = null;
            JavaProject javaProject = (JavaProject) openable.getJavaProject();
            resource = workingCopy != null ? workingCopy.getResource() : openable.getResource();
            if (resource == null)
                resource = javaProject.getProject(); // case of a file in an external jar or external folder
            if (!javaProject.equals(previousJavaProject)) {
                // locate matches in previous project
                if (previousJavaProject != null) {
                    try {
                        locateMatches(previousJavaProject, matchSet, i - displayed);
                        displayed = i;
                    } catch (JavaModelException e) {
                        // problem with classpath in this project -> skip it
                    }
                    matchSet.reset();
                }
                previousJavaProject = javaProject;
            }
            matchSet.add(new PossibleMatch(this, resource, openable, searchDocument, this.pattern.mustResolve));
        }

        // last project
        if (previousJavaProject != null) {
            try {
                locateMatches(previousJavaProject, matchSet, docsLength - displayed);
            } catch (JavaModelException e) {
                // problem with classpath in last project -> ignore
            }
        }

        if (this.searchPackageDeclaration) {
            locatePackageDeclarations(searchParticipant, javaModelProjects);
        }

    } finally {
        if (this.progressMonitor != null)
            this.progressMonitor.done();
        if (this.nameEnvironment != null)
            this.nameEnvironment.cleanup();
        manager.flushZipFiles(this);
        this.bindings = null;
    }
}

From source file:com.redhat.ceylon.eclipse.core.model.JDTModule.java

License:Open Source License

public void refresh() {
    if (originalUnitsToAdd.size() + originalUnitsToRemove.size() == 0) {
        // Nothing to refresh
        return;/*w w  w .jav  a2s.c  om*/
    }

    try {
        PhasedUnitMap<? extends PhasedUnit, ?> phasedUnitMap = null;
        if (isCeylonBinaryArchive()) {
            JavaModelManager.getJavaModelManager().resetClasspathListCache();
            JavaModelManager.getJavaModelManager().getJavaModel().refreshExternalArchives(
                    getPackageFragmentRoots().toArray(new IPackageFragmentRoot[0]), null);
            phasedUnitMap = binaryModulePhasedUnits;
        }
        if (isSourceArchive()) {
            phasedUnitMap = sourceModulePhasedUnits.get();
        }
        if (phasedUnitMap != null) {
            synchronized (phasedUnitMap) {
                for (String relativePathToRemove : originalUnitsToRemove) {
                    if (isCeylonBinaryArchive() || JavaCore.isJavaLikeFileName(relativePathToRemove)) {
                        List<String> unitPathsToSearch = new ArrayList<>();
                        unitPathsToSearch.add(relativePathToRemove);
                        unitPathsToSearch.addAll(toBinaryUnitRelativePaths(relativePathToRemove));
                        for (String relativePathOfUnitToRemove : unitPathsToSearch) {
                            Package p = getPackageFromRelativePath(relativePathOfUnitToRemove);
                            if (p != null) {
                                Set<Unit> units = new HashSet<>();
                                for (Declaration d : p.getMembers()) {
                                    Unit u = d.getUnit();
                                    if (u.getRelativePath().equals(relativePathOfUnitToRemove)) {
                                        units.add(u);
                                    }
                                }
                                for (Unit u : units) {
                                    try {
                                        p.removeUnit(u);
                                        // In the future, when we are sure that we cannot add several unit objects with the 
                                        // same relative path, we can add a break.
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            } else {
                                System.out.println("WARNING : The package of the following binary unit ("
                                        + relativePathOfUnitToRemove + ") " + "cannot be found in module "
                                        + getNameAsString() + artifact != null
                                                ? " (artifact=" + artifact.getAbsolutePath() + ")"
                                                : "");
                            }
                        }
                    }
                    phasedUnitMap.removePhasedUnitForRelativePath(relativePathToRemove);
                }

                if (isSourceArchive()) {
                    ClosableVirtualFile sourceArchive = null;
                    try {
                        sourceArchive = moduleManager.getContext().getVfs()
                                .getFromZipFile(new File(sourceArchivePath));
                        for (String relativePathToAdd : originalUnitsToAdd) {
                            VirtualFile archiveEntry = null;
                            archiveEntry = searchInSourceArchive(relativePathToAdd, sourceArchive);

                            if (archiveEntry != null) {
                                Package pkg = getPackageFromRelativePath(relativePathToAdd);
                                ((ExternalModulePhasedUnits) phasedUnitMap).parseFile(archiveEntry,
                                        sourceArchive, pkg);
                            }
                        }
                    } catch (Exception e) {
                        StringBuilder error = new StringBuilder("Unable to read source artifact from ");
                        error.append(sourceArchive);
                        error.append("\ndue to connection error: ").append(e.getMessage());
                        throw e;
                    } finally {
                        if (sourceArchive != null) {
                            sourceArchive.close();
                        }
                    }
                }

                classesToSources = CarUtils.retrieveMappingFile(returnCarFile());
                javaImplFilesToCeylonDeclFiles = CarUtils
                        .searchCeylonFilesForJavaImplementations(classesToSources, new File(sourceArchivePath));

                originalUnitsToRemove.clear();
                originalUnitsToAdd.clear();
            }
        }
        if (isCeylonBinaryArchive() || isJavaBinaryArchive()) {
            jarPackages.clear();
            loadPackageList(new ArtifactResult() {
                @Override
                public VisibilityType visibilityType() {
                    return null;
                }

                @Override
                public String version() {
                    return null;
                }

                @Override
                public ArtifactResultType type() {
                    return null;
                }

                @Override
                public String name() {
                    return null;
                }

                @Override
                public ImportType importType() {
                    return null;
                }

                @Override
                public List<ArtifactResult> dependencies() throws RepositoryException {
                    return null;
                }

                @Override
                public File artifact() throws RepositoryException {
                    return artifact;
                }

                @Override
                public String repositoryDisplayString() {
                    return "";
                }

                @Override
                public PathFilter filter() {
                    return null;
                }

                @Override
                public Repository repository() {
                    return null;
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.versant.core.jdo.tools.eclipse.Utils.java

License:Open Source License

public static IPath getSrcPath(IProject iProject) throws JavaModelException {
    IJavaProject iJavaProject = JavaModelManager.getJavaModelManager().getJavaModel().findJavaProject(iProject);
    IPackageFragmentRoot[] roots = iJavaProject.getAllPackageFragmentRoots();
    IPath rawLocation = iProject.getLocation();
    for (int x = 0; x < roots.length; x++) {
        IPackageFragmentRoot root = roots[x];
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
            return rawLocation.append(root.getPath().removeFirstSegments(1));
        }//from w w w. j  a v  a2 s  .  co m
    }
    return null;
}

From source file:com.versant.core.jdo.tools.plugins.eclipse.views.BaseExplorer.java

License:Open Source License

protected void makeActions() {
    actAddJDONature = new Action() {
        public void run() {
            IProject iProject = getSelectedIProject();
            if (iProject != null) {
                try {
                    VOAAddNatureDialog wizard = new VOAAddNatureDialog(iProject);
                    WizardDialog dialog = new WizardDialog(getSite().getShell(), wizard);
                    PixelConverter converter = new PixelConverter(JavaPlugin.getActiveWorkbenchShell());

                    dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(70),
                            converter.convertHeightInCharsToPixels(20));
                    dialog.create();/*from ww  w  .  j a v  a  2  s. c  om*/
                    int res = dialog.open();
                    if (res == Window.OK) {
                        IJavaProject iJavaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                                .findJavaProject(iProject);
                        Utils.addJDONature(iJavaProject);
                    }
                    notifyResult(res == Window.OK);
                } catch (Exception x) {
                    VOAToolsPlugin.log(x, "Problems opening Mapping editor.");
                }
                refreshTree(false, true);
            }
        }
    };
    actAddJDONature.setText("Add VOA Nature");
    actAddJDONature.setToolTipText("Add VOA Nature");

    actRemoveJDONature = new Action() {
        public void run() {
            IProject iProject = getSelectedIProject();
            if (iProject != null) {
                IJavaProject iJavaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                        .findJavaProject(iProject);
                RemoveJDONature.removeJDONature(iJavaProject);
                VOAProjectControler.removeInstance(iProject);
                refreshTree(false, true);
            }
        }
    };
    actRemoveJDONature.setText("Remove VOA Nature");
    actRemoveJDONature.setToolTipText("Remove VOA Nature");

    actEnhance = new Action() {
        public void run() {
            EnhanceAction.enhance(getSelectedIProject());
        }
    };
    actEnhance.setText("Enhance Classes");
    actEnhance.setToolTipText("Enhance Classes");

    actAddClass = new Action() {
        public void run() {
            try {
                IProject iProject = getSelectedIProjectInTree();
                if (iProject == null) {
                    return;
                }

                IJavaProject iJavaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                        .findJavaProject(iProject);
                IPackageFragmentRoot[] roots = iJavaProject.getAllPackageFragmentRoots();
                ArrayList elementList = new ArrayList();
                for (int x = 0; x < roots.length; x++) {
                    IPackageFragmentRoot root = roots[x];
                    if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
                        elementList.addAll(Arrays.asList(root.getChildren()));
                    }
                }
                IJavaElement[] elements = new IJavaElement[elementList.size()];
                elementList.toArray(elements);
                IJavaSearchScope scope = SearchEngine.createJavaSearchScope(elements);
                SelectionDialog dialog = JavaUI.createTypeDialog(getSite().getShell(),
                        getSite().getWorkbenchWindow(), scope,
                        IJavaElementSearchConstants.CONSIDER_CLASSES_AND_INTERFACES, true);
                dialog.setTitle("Make Class Persistent");
                dialog.setMessage("Please select a class to make persistent");

                if (dialog.open() == Window.OK) {
                    VOAProjectControler controler = VOAProjectControler.getInstance(iProject);
                    Object[] results = dialog.getResult();
                    for (int i = 0; i < results.length; i++) {
                        IType itype = (IType) results[i];
                        controler.addClass(itype.getFullyQualifiedName());
                    }
                }
            } catch (Exception e) {
                VOAToolsPlugin.log(e, "Problems adding a persistent class.");
            } finally {
                refreshTree(false, true);
            }
        }
    };
    actAddClass.setText("Make Class Persistent");
    actAddClass.setImageDescriptor(VOAToolsPlugin.imageDescriptorFromPlugin("Versant", "icons/class16.png"));
    actAddClass.setToolTipText("Make  a class in you project persistent.");
}

From source file:com.versant.core.jdo.tools.plugins.eclipse.VOAProjectControler.java

License:Open Source License

/**
 * @throws JavaModelException//from   ww  w.ja v a2s .  c  o m
 * @throws CoreException
 */
private void setMdProjectDefaults() throws JavaModelException, CoreException {
    IJavaProject iJavaProject = JavaModelManager.getJavaModelManager().getJavaModel().findJavaProject(iProject);
    File source = Utils.getSrcFile(iProject);
    List cp = mdProject.getClassPathList();
    cp.clear();
    if (source != null) {
        mdProject.setSrcDir(source);
        cp.add(source);
    }
    String[] paths = JavaRuntime.computeDefaultRuntimeClassPath(iJavaProject);
    for (int x = 0; x < paths.length; x++) {
        cp.add(new File(paths[x]));
    }
    mdProject.setAntDisabled(true);
}

From source file:edu.brown.cs.bubbles.bedrock.BedrockOpenEditorBubbleActionDelegate.java

License:Open Source License

@Override
public void run(IAction action) {
    IWorkbenchPage page = our_window.getActivePage();

    if (page != null) {
        if (!(page.getActiveEditor() instanceof ITextEditor))
            return;

        ITextEditor fileEditor = (ITextEditor) page.getActiveEditor();

        IFileEditorInput fileEditorInput = (IFileEditorInput) fileEditor.getEditorInput();
        String path = fileEditorInput.getFile().getProjectRelativePath().toOSString();
        String filePath = path;/*from  w w  w.j  a va2s .  c o m*/
        IProject project = fileEditorInput.getFile().getProject();

        IJavaProject javaProject = JavaModelManager.getJavaModelManager().getJavaModel()
                .getJavaProject(project.getName());

        try {
            for (IClasspathEntry entry : javaProject.getRawClasspath()) {
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    String sourcePath = entry.getPath().toOSString().substring(project.getName().length() + 2);

                    if (path.startsWith(sourcePath)) {
                        path = path.substring(sourcePath.length() + 1);
                        path = path.replace(File.separatorChar, '$');
                        path = path.substring(0, path.indexOf("."));

                        filePath = filePath.substring(sourcePath.length() + 1);

                        break;
                    }
                }
            }
        } catch (Exception e1) {
            BedrockPlugin.log("Exception : " + e1.getMessage() + ", " + e1.getClass().toString());
        }

        try {
            IJavaElement javaElement = javaProject.findElement(new Path(filePath));

            if (!(javaElement instanceof ICompilationUnit))
                return;

            ICompilationUnit icu = (ICompilationUnit) javaElement;

            ISelectionProvider selectionProvider = fileEditor.getSelectionProvider();
            ISelection selection = selectionProvider.getSelection();

            if (selection instanceof ITextSelection) {
                ITextSelection textSelection = (ITextSelection) selection;
                int offset = textSelection.getOffset();

                IJavaElement element = icu.getElementAt(offset);

                IvyXmlWriter xw = BedrockPlugin.getPlugin().beginMessage("OPENEDITOR");
                xw.field("PROJECT", project.getName());

                if (element == null) {
                    xw.field("RESOURCEPATH", path);
                } else {
                    boolean isFirstElement = true;
                    boolean isMethod = false;

                    String fileName = path.substring(path.lastIndexOf('$') + 1);

                    List<String> list = new ArrayList<String>();

                    while (element != null && (!element.getElementName().equals(fileName)
                            || element.getElementType() == IJavaElement.METHOD)) {
                        if (isFirstElement && (element.getElementType() == IJavaElement.METHOD
                                || element.getElementType() == IJavaElement.TYPE)) {
                            list.add(element.getElementName());

                            if (element.getElementType() == IJavaElement.METHOD) {
                                isMethod = true;
                            }

                            isFirstElement = false;
                        } else if (!isFirstElement) {
                            list.add(element.getElementName());
                        }

                        element = element.getParent();

                        if ("".equals(element.getElementName())) {
                            xw.field("RESOURCEPATH", path);
                            BedrockPlugin.getPlugin().finishMessage(xw);

                            return;
                        }
                    }

                    String[] aryPath = new String[list.size()];
                    list.toArray(aryPath);

                    for (int i = aryPath.length - 1; i >= 0; i--) {
                        path += ("$" + aryPath[i]);
                    }

                    xw.field("RESOURCEPATH", path);

                    if (isMethod)
                        xw.field("RESOURCETYPE", "Function");
                }

                BedrockPlugin.getPlugin().finishMessage(xw);
            }
        } catch (Exception e2) {
            BedrockPlugin.log("Exception : " + e2.getMessage() + ", " + e2.getClass().toString());
        }
    }
}