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:at.bestsolution.efxclipse.tooling.ui.wizards.AbstractNewJDTElementWizard.java

License:Open Source License

protected IPackageFragmentRoot getFragmentRoot(IJavaElement elem) {
    IPackageFragmentRoot initRoot = null;
    if (elem != null) {
        initRoot = (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
        try {/*from   w ww  .  j a  v  a  2  s  . c o m*/
            if (initRoot == null || initRoot.getKind() != IPackageFragmentRoot.K_SOURCE) {
                IJavaProject jproject = elem.getJavaProject();
                if (jproject != null) {
                    initRoot = null;
                    if (jproject.exists()) {
                        IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
                        for (int i = 0; i < roots.length; i++) {
                            if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                                initRoot = roots[i];
                                break;
                            }
                        }
                    }
                    if (initRoot == null) {
                        initRoot = jproject.getPackageFragmentRoot(jproject.getResource());
                    }
                }
            }
        } catch (JavaModelException e) {
            // TODO
            e.printStackTrace();
        }
    }
    return initRoot;
}

From source file:ca.ecliptical.pde.ds.search.DescriptorQueryParticipant.java

License:Open Source License

public void search(ISearchRequestor requestor, QuerySpecification query, IProgressMonitor monitor)
        throws CoreException {
    if (debug.isDebugging())
        debug.trace(String.format("Query: %s", query)); //$NON-NLS-1$

    // we only look for straight references
    switch (query.getLimitTo()) {
    case IJavaSearchConstants.REFERENCES:
    case IJavaSearchConstants.ALL_OCCURRENCES:
        break;/*from  w ww  . j  ava 2 s. c  o  m*/
    default:
        return;
    }

    // we only look for types and methods
    if (query instanceof ElementQuerySpecification) {
        searchElement = ((ElementQuerySpecification) query).getElement();
        switch (searchElement.getElementType()) {
        case IJavaElement.TYPE:
        case IJavaElement.METHOD:
            break;
        default:
            return;
        }
    } else {
        String pattern = ((PatternQuerySpecification) query).getPattern();
        boolean ignoreMethodParams = false;
        searchFor = ((PatternQuerySpecification) query).getSearchFor();
        switch (searchFor) {
        case IJavaSearchConstants.UNKNOWN:
        case IJavaSearchConstants.METHOD:
            int leftParen = pattern.lastIndexOf('(');
            int rightParen = pattern.indexOf(')');
            ignoreMethodParams = leftParen == -1 || rightParen == -1 || leftParen >= rightParen;
            // no break
        case IJavaSearchConstants.TYPE:
        case IJavaSearchConstants.CLASS:
        case IJavaSearchConstants.CLASS_AND_INTERFACE:
        case IJavaSearchConstants.CLASS_AND_ENUM:
        case IJavaSearchConstants.INTERFACE:
        case IJavaSearchConstants.INTERFACE_AND_ANNOTATION:
            break;
        default:
            return;
        }

        // searchPattern = PatternConstructor.createPattern(pattern, ((PatternQuerySpecification) query).isCaseSensitive());
        int matchMode = getMatchMode(pattern) | SearchPattern.R_ERASURE_MATCH;
        if (((PatternQuerySpecification) query).isCaseSensitive())
            matchMode |= SearchPattern.R_CASE_SENSITIVE;

        searchPattern = new SearchPatternDescriptor(pattern, matchMode, ignoreMethodParams);
    }

    HashSet<IPath> scope = new HashSet<IPath>();
    for (IPath path : query.getScope().enclosingProjectsAndJars()) {
        scope.add(path);
    }

    if (scope.isEmpty())
        return;

    this.requestor = requestor;

    // look through all active bundles
    IPluginModelBase[] wsModels = PluginRegistry.getWorkspaceModels();
    IPluginModelBase[] exModels = PluginRegistry.getExternalModels();
    monitor.beginTask(Messages.DescriptorQueryParticipant_taskName, wsModels.length + exModels.length);
    try {
        // workspace models
        for (IPluginModelBase model : wsModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            if (!model.isEnabled() || !(model instanceof IBundlePluginModelBase)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            IProject project = model.getUnderlyingResource().getProject();
            if (!scope.contains(project.getFullPath())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Project out of scope: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            // we can only search in Java bundle projects (for now)
            if (!project.hasNature(JavaCore.NATURE_ID)) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-Java project: %s", project.getName())); //$NON-NLS-1$

                continue;
            }

            PDEModelUtility.modifyModel(new ModelModification(project) {
                @Override
                protected void modifyModel(IBaseModel model, IProgressMonitor monitor) throws CoreException {
                    if (model instanceof IBundlePluginModelBase)
                        searchBundle((IBundlePluginModelBase) model, monitor);
                }
            }, new SubProgressMonitor(monitor, 1));
        }

        // external models
        SearchablePluginsManager spm = PDECore.getDefault().getSearchablePluginsManager();
        IJavaProject javaProject = spm.getProxyProject();
        if (javaProject == null || !javaProject.exists() || !javaProject.isOpen()) {
            monitor.worked(exModels.length);
            if (debug.isDebugging())
                debug.trace("External Plug-in Search project inaccessible!"); //$NON-NLS-1$

            return;
        }

        for (IPluginModelBase model : exModels) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();

            BundleDescription bd;
            if (!model.isEnabled() || (bd = model.getBundleDescription()) == null) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-bundle model: %s", model)); //$NON-NLS-1$

                continue;
            }

            // check scope
            ArrayList<IClasspathEntry> cpEntries = new ArrayList<IClasspathEntry>();
            ClasspathUtilCore.addLibraries(model, cpEntries);
            ArrayList<IPath> cpEntryPaths = new ArrayList<IPath>(cpEntries.size());
            for (IClasspathEntry cpEntry : cpEntries) {
                cpEntryPaths.add(cpEntry.getPath());
            }

            cpEntryPaths.retainAll(scope);
            if (cpEntryPaths.isEmpty()) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("External bundle out of scope: %s", model.getInstallLocation())); //$NON-NLS-1$

                continue;
            }

            if (!spm.isInJavaSearch(bd.getSymbolicName())) {
                monitor.worked(1);
                if (debug.isDebugging())
                    debug.trace(String.format("Non-searchable external model: %s", bd.getSymbolicName())); //$NON-NLS-1$

                continue;
            }

            searchBundle(model, javaProject, new SubProgressMonitor(monitor, 1));
        }
    } finally {
        monitor.done();
    }
}

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;//w w w  . j  a va 2  s  .  c o m
        defaultEntries = null;
    }
    fJavaProject = jproject;
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.debug.DebugProvider.java

License:Open Source License

@Override
public boolean isDebugSupported(DockerFoundryApplicationModule appModule, DockerFoundryServer cloudServer) {
    IJavaProject javaProject = DockerFoundryProjectUtil.getJavaProject(appModule);
    return javaProject != null && javaProject.exists() && containsDebugFiles(javaProject);
}

From source file:co.turnus.widgets.util.WidgetsUtils.java

License:Open Source License

/**
 * Returns the qualified name of the given file, i.e. qualified.name.of.File
 * for <code>/project/sourceFolder/qualified/name/of/File.fileExt</code> or
 * <code>/project/outputFolder/qualified/name/of/File.fileExt</code>.
 * /*w  w w. ja  v a  2s. c  o  m*/
 * @param file
 *            a file
 * @return a qualified name, or <code>null</code> if the file is not in a
 *         source folder
 */
public static String getQualifiedName(IFile file) {
    IProject project = file.getProject();

    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        return null;
    }

    try {
        IPath path = file.getParent().getFullPath();
        IPackageFragment fragment = null;
        if (javaProject.getOutputLocation().isPrefixOf(path)) {
            // create relative path
            int count = path.matchingFirstSegments(javaProject.getOutputLocation());
            IPath relPath = path.removeFirstSegments(count);

            // creates full path to source
            for (IFolder folder : getSourceFolders(project)) {
                path = folder.getFullPath().append(relPath);
                fragment = javaProject.findPackageFragment(path);
                if (fragment != null) {
                    break;
                }
            }
        } else {
            fragment = javaProject.findPackageFragment(path);
        }

        if (fragment == null) {
            return null;
        }

        String name = file.getFullPath().removeFileExtension().lastSegment();
        if (fragment.isDefaultPackage()) {
            // handles the default package case
            return name;
        }
        return fragment.getElementName() + "." + name;
    } catch (JavaModelException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:co.turnus.widgets.util.WidgetsUtils.java

License:Open Source License

/**
 * Returns the list of source folders of the given project as a list of
 * absolute workspace paths./*from w w  w  .  j  a v a2 s .c o  m*/
 * 
 * @param project
 *            a project
 * @return a list of absolute workspace paths
 */
public static List<IFolder> getSourceFolders(IProject project) {
    List<IFolder> srcFolders = new ArrayList<IFolder>();

    IJavaProject javaProject = JavaCore.create(project);
    if (!javaProject.exists()) {
        return srcFolders;
    }

    // iterate over package roots
    try {
        for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
            IResource resource = root.getCorrespondingResource();
            if (resource != null && resource.getType() == IResource.FOLDER) {
                srcFolders.add((IFolder) resource);
            }
        }
    } catch (CoreException e) {
        e.printStackTrace();
    }

    return srcFolders;
}

From source file:com.aliyun.odps.eclipse.launch.configuration.udf.UDFClassTab.java

License:Apache License

/**
 * Show a dialog that lists all main types
 *///from  ww  w . jav  a  2  s .  c o m
protected void handleSearchButtonSelected() {
    IJavaProject project = getJavaProject();
    IJavaElement[] elements = null;
    if ((project == null) || !project.exists()) {
        IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
        if (model != null) {
            try {
                elements = model.getJavaProjects();
            } catch (JavaModelException e) {
                JDIDebugUIPlugin.log(e);
            }
        }
    } else {
        elements = new IJavaElement[] { project };
    }
    if (elements == null) {
        elements = new IJavaElement[] {};
    }
    int constraints = IJavaSearchScope.SOURCES;
    constraints |= IJavaSearchScope.APPLICATION_LIBRARIES;
    // constraints |= IJavaSearchScope.SYSTEM_LIBRARIES;

    IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(elements, constraints);
    UDFSearchEngine engine = new UDFSearchEngine();
    IType[] types = null;
    try {
        types = engine.searchUDFClass(getLaunchConfigurationDialog(), searchScope, false);
    } catch (InvocationTargetException e) {
        setErrorMessage(e.getMessage());
        return;
    } catch (InterruptedException e) {
        setErrorMessage(e.getMessage());
        return;
    }
    DebugTypeSelectionDialog mmsd = new DebugTypeSelectionDialog(getShell(), types,
            LauncherMessages.JavaMainTab_Choose_Main_Type_11);
    if (mmsd.open() == Window.CANCEL) {
        return;
    }
    Object[] results = mmsd.getResult();
    IType type = (IType) results[0];
    if (type != null) {
        fMainText.setText(type.getFullyQualifiedName());
        fProjText.setText(type.getJavaProject().getElementName());
    }
}

From source file:com.amashchenko.eclipse.strutsclipse.ProjectUtil.java

License:Apache License

public static IType findClass(final IDocument document, final String className) {
    IType result = null;/*from  w w w  .  j a va 2  s . com*/
    try {
        IJavaProject javaProject = getCurrentJavaProject(document);
        if (javaProject != null && javaProject.exists()) {
            IType type = javaProject.findType(className);
            if (type != null && type.exists()) {
                result = type;
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.amashchenko.eclipse.strutsclipse.ProjectUtil.java

License:Apache License

public static List<JarEntryStorage> findJarEntryStrutsResources(final IDocument document) {
    List<JarEntryStorage> results = new ArrayList<JarEntryStorage>();
    try {//from   w w w.  j  a v a  2 s .c om
        IJavaProject javaProject = getCurrentJavaProject(document);

        if (javaProject != null && javaProject.exists()) {
            IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
            for (IPackageFragmentRoot root : roots) {
                if (root.isArchive()) {
                    Object[] nonJavaResources = root.getNonJavaResources();
                    for (Object nonJavaRes : nonJavaResources) {
                        if (nonJavaRes instanceof IJarEntryResource) {
                            IJarEntryResource jarEntry = (IJarEntryResource) nonJavaRes;
                            if (jarEntry.isFile() && (StrutsXmlConstants.STRUTS_DEFAULT_FILE_NAME
                                    .equals(jarEntry.getName())
                                    || StrutsXmlConstants.STRUTS_PLUGIN_FILE_NAME.equals(jarEntry.getName()))) {
                                results.add(new JarEntryStorage(root.getPath(), jarEntry));
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
    return results;
}

From source file:com.amashchenko.eclipse.strutsclipse.StrutsXmlHyperlinkDetector.java

License:Apache License

private List<IHyperlink> createResultLocationLinks(final IDocument document, final String elementValue,
        final IRegion elementRegion, final String typeAttrValue, final String namespaceParamValue) {
    final List<IHyperlink> links = new ArrayList<IHyperlink>();

    // assume that default is dispatcher for now, TODO improve
    // that//w w w  . ja  v a2 s  .co  m
    if (typeAttrValue == null || StrutsXmlConstants.DISPATCHER_RESULT.equals(typeAttrValue)
            || StrutsXmlConstants.FREEMARKER_RESULT.equals(typeAttrValue)) {
        IProject project = ProjectUtil.getCurrentProject(document);
        if (project != null && project.exists()) {
            IVirtualComponent rootComponent = ComponentCore.createComponent(project);
            final IVirtualFolder rootFolder = rootComponent.getRootFolder();
            IPath path = rootFolder.getProjectRelativePath().append(elementValue);

            IFile file = project.getFile(path);
            if (file.exists()) {
                links.add(new FileHyperlink(elementRegion, file));
            }
        }
    } else if (StrutsXmlConstants.REDIRECT_ACTION_RESULT.equals(typeAttrValue)) {
        Set<String> namespaces = new HashSet<String>();

        // if there is a namespaceParamValue then used it, else get
        // namespace from parent package
        String namespace = namespaceParamValue;
        if (namespace == null) {
            TagRegion packageTagRegion = strutsXmlParser.getParentTagRegion(document, elementRegion.getOffset(),
                    StrutsXmlConstants.PACKAGE_TAG);
            if (packageTagRegion != null) {
                namespace = packageTagRegion.getAttrValue(StrutsXmlConstants.NAMESPACE_ATTR, "");
            } else {
                namespace = "";
            }

            // if namespace came NOT from namespaceParamValue then add
            // special namespaces
            namespaces.add("");
            namespaces.add("/");
        }

        namespaces.add(namespace);

        IRegion region = strutsXmlParser.getActionRegion(document, namespaces, elementValue);
        if (region != null) {
            ITextFileBuffer textFileBuffer = FileBuffers.getTextFileBufferManager().getTextFileBuffer(document);
            if (textFileBuffer != null) {
                IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(textFileBuffer.getLocation());
                if (file.exists()) {
                    links.add(new FileHyperlink(elementRegion, file, region));
                }
            }
        }
    } else if (StrutsXmlConstants.TILES_RESULT.equals(typeAttrValue)) {
        try {
            final IDocumentProvider provider = new TextFileDocumentProvider();
            final IJavaProject javaProject = ProjectUtil.getCurrentJavaProject(document);
            if (javaProject != null && javaProject.exists()) {
                final IProject project = javaProject.getProject();
                final String outputFolder = javaProject.getOutputLocation()
                        .makeRelativeTo(project.getFullPath()).segment(0);
                project.accept(new IResourceVisitor() {
                    @Override
                    public boolean visit(IResource resource) throws CoreException {
                        // don't visit output folder
                        if (resource.getType() == IResource.FOLDER
                                && resource.getProjectRelativePath().segment(0).equals(outputFolder)) {
                            return false;
                        }
                        if (resource.isAccessible() && resource.getType() == IResource.FILE
                                && "xml".equalsIgnoreCase(resource.getFileExtension()) && resource.getName()
                                        .toLowerCase(Locale.ROOT).contains(StrutsXmlConstants.TILES_RESULT)) {
                            provider.connect(resource);
                            IDocument document = provider.getDocument(resource);
                            provider.disconnect(resource);

                            IRegion region = tilesXmlParser.getDefinitionRegion(document, elementValue);
                            if (region != null) {
                                IFile file = project.getFile(resource.getProjectRelativePath());
                                if (file.exists()) {
                                    links.add(new FileHyperlink(elementRegion, file, region));
                                }
                            }
                        }
                        return true;
                    }
                });
            }
        } catch (CoreException e) {
            e.printStackTrace();
        }
    }
    return links;
}