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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Returns whether this Java element exists in the model.

Usage

From source file:org.eclipse.gmf.tests.gen.CompilationTest.java

License:Open Source License

public void testPreexistingImportConflicts() throws Exception {
    DiaGenSource gmfGenSource = createLibraryGen(false);
    gmfGenSource.getGenDiagram().getEditorGen().setSameFileForDiagramAndModel(false);
    String pluginId = gmfGenSource.getGenDiagram().getEditorGen().getPlugin().getID();
    IProject diagramProject = ResourcesPlugin.getWorkspace().getRoot().getProject(pluginId);
    if (!diagramProject.isAccessible()) {
        //Initialize the plugin the same way it would be initialized if present.
        Generator.createEMFProject(diagramProject.getFolder("src").getFullPath(), null, //$NON-NLS-1$
                Collections.<IProject>emptyList(), new NullProgressMonitor(),
                Generator.EMF_PLUGIN_PROJECT_STYLE);
    }// w  w  w  .  j  av a 2 s .c  o m
    IJavaProject javaProject = JavaCore.create(diagramProject);
    assertTrue(javaProject.exists());
    IPackageFragment pf = javaProject.getPackageFragmentRoot(diagramProject.getFolder("src")) //$NON-NLS-1$
            .createPackageFragment(gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(), false,
                    new NullProgressMonitor());
    ICompilationUnit cu = pf
            .getCompilationUnit(gmfGenSource.getGenDiagram().getNotationViewFactoryClassName() + ".java"); //$NON-NLS-1$
    String contents = MessageFormat.format(
            "package {0};\nimport {2};\n /**\n * @generated\n */\npublic class {1} '{ }'", //$NON-NLS-1$
            gmfGenSource.getGenDiagram().getNotationViewFactoriesPackageName(),
            gmfGenSource.getGenDiagram().getNotationViewFactoryClassName(), "javax.swing.text.View");
    if (cu.exists()) {
        IBuffer buffer = cu.getBuffer();
        buffer.setContents(contents);
        buffer.save(new NullProgressMonitor(), true);
    } else {
        pf.createCompilationUnit(cu.getElementName(), contents, false, new NullProgressMonitor());
    }
    generateAndCompile(gmfGenSource);
}

From source file:org.eclipse.imp.java.hosted.ProjectUtils.java

License:Open Source License

public void addExtenderForJavaHostedProjects(Language lang) {
    ModelFactory.getInstance().installExtender(new IFactoryExtender() {
        public void extend(ISourceProject project) {
            initializeBuildPathFromJavaProject(project);
        }//w  w w  .j  ava 2 s  .co  m

        public void extend(ICompilationUnit unit) {
        }

        /**
         * Read the IJavaProject classpath configuration and populate the ISourceProject's
         * build path accordingly.
         */
        public void initializeBuildPathFromJavaProject(ISourceProject project) {
            IJavaProject javaProject = JavaCore.create(project.getRawProject());
            if (javaProject.exists()) {
                try {
                    IClasspathEntry[] cpEntries = javaProject.getResolvedClasspath(true);
                    List<IPathEntry> buildPath = new ArrayList<IPathEntry>(cpEntries.length);
                    for (int i = 0; i < cpEntries.length; i++) {
                        IClasspathEntry entry = cpEntries[i];
                        IPathEntry.PathEntryType type;
                        IPath path = entry.getPath();

                        switch (entry.getEntryKind()) {
                        case IClasspathEntry.CPE_CONTAINER:
                            type = PathEntryType.CONTAINER;
                            break;
                        case IClasspathEntry.CPE_LIBRARY:
                            type = PathEntryType.ARCHIVE;
                            break;
                        case IClasspathEntry.CPE_PROJECT:
                            type = PathEntryType.PROJECT;
                            break;
                        case IClasspathEntry.CPE_SOURCE:
                            type = PathEntryType.SOURCE_FOLDER;
                            break;
                        default:
                            // case IClasspathEntry.CPE_VARIABLE:
                            throw new IllegalArgumentException("Encountered variable class-path entry: "
                                    + entry.getPath().toPortableString());
                        }
                        IPathEntry pathEntry = ModelFactory.createPathEntry(type, path);
                        buildPath.add(pathEntry);
                    }
                    project.setBuildPath(buildPath);
                } catch (JavaModelException e) {
                    ErrorHandler.reportError(e.getMessage(), e);
                }
            }
        }
    }, lang);
}

From source file:org.eclipse.imp.releng.CopyrightAdder.java

License:Open Source License

/**
 * @param projects/*  www .j av a 2s.  co m*/
 */
private void collectProjectSourceRoots(Set<IProject> projectsToModify) {
    IWorkspaceRoot wsRoot = fReleaseTool.fWSRoot;

    for (IProject project : projectsToModify) {
        ReleaseEngineeringPlugin.getMsgStream().println("Collecting source folders for " + project.getName());

        IJavaProject javaProject = JavaCore.create(project);

        if (!javaProject.exists()) {
            ReleaseEngineeringPlugin.getMsgStream()
                    .println("Project " + javaProject.getElementName() + " does not exist!");
            continue;
        }

        try {
            IClasspathEntry[] cpe = javaProject.getResolvedClasspath(true);

            for (int j = 0; j < cpe.length; j++) {
                IClasspathEntry entry = cpe[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                    // TODO Doesn't handle path inclusion/exclusion constraints
                    if (entry.getPath().segmentCount() == 1)
                        ReleaseEngineeringPlugin.getMsgStream().println("*** Ignoring source path entry "
                                + entry.getPath().toPortableString() + " because it's at a project root.");
                    else
                        fSrcRoots.add(wsRoot.getFolder(entry.getPath()));
                }
            }
        } catch (JavaModelException e) {
            ReleaseEngineeringPlugin.getMsgStream()
                    .println("Exception encountered while traversing resources:\n  " + e.getMessage());
            logError(e);
        }
    }
}

From source file:org.eclipse.imp.ui.explorer.OutputFolderFilter.java

License:Open Source License

/**
 * Returns the result of this filter, when applied to the given element.
 * // w w w. j ava 2 s.co  m
 * @param element
 *            the element to test
 * @return <code>true</code> if element should be included
 * @since 3.0
 */
public boolean select(Viewer viewer, Object parent, Object element) {
    if (element instanceof ISourceFolder) {
        element = ((ISourceFolder) element).getResource();
    }
    if (element instanceof IFolder) {
        IFolder folder = (IFolder) element;
        IProject proj = folder.getProject();
        try {
            if (!proj.hasNature(JavaCore.NATURE_ID))
                return true;
            IJavaProject jProject = JavaCore.create(folder.getProject());
            if (jProject == null || !jProject.exists())
                return true;
            // Check default output location
            IPath defaultOutputLocation = jProject.getOutputLocation();
            IPath folderPath = folder.getFullPath();
            if (defaultOutputLocation != null && defaultOutputLocation.equals(folderPath))
                return false;
            // Check output location for each class path entry
            IClasspathEntry[] cpEntries = jProject.getRawClasspath();
            for (int i = 0, length = cpEntries.length; i < length; i++) {
                IPath outputLocation = cpEntries[i].getOutputLocation();
                if (outputLocation != null && outputLocation.equals(folderPath))
                    return false;
            }
        } catch (CoreException ex) {
            return true;
        }
    }
    return true;
}

From source file:org.eclipse.incquery.patternlanguage.emf.ui.validation.GenmodelBasedEMFPatternLanguageJavaValidator.java

License:Open Source License

protected String getActualPackageName(PatternModel model) {
    URI fileURI = model.eResource().getURI();
    for (Pair<IStorage, IProject> storage : storage2UriMapper.getStorages(fileURI)) {
        if (storage.getFirst() instanceof IFile) {
            IPath fileWorkspacePath = storage.getFirst().getFullPath();
            IJavaProject javaProject = JavaCore.create(storage.getSecond());
            if (javaProject != null && javaProject.exists() && javaProject.isOpen()) {
                try {
                    for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
                        if (!root.isArchive() && !root.isExternal()) {
                            IResource resource = root.getResource();
                            if (resource != null) {
                                IPath sourceFolderPath = resource.getFullPath();
                                if (sourceFolderPath.isPrefixOf(fileWorkspacePath)) {
                                    IPath classpathRelativePath = fileWorkspacePath
                                            .makeRelativeTo(sourceFolderPath);
                                    return classpathRelativePath.removeLastSegments(1).toString().replace("/",
                                            ".");
                                }/*ww w.ja  v a 2s . co  m*/
                            }
                        }
                    }
                } catch (JavaModelException e) {
                    logger.error("Error resolving package declaration for Pattern Model", e);
                }
            }
        }
    }
    return null;
}

From source file:org.eclipse.incquery.tooling.ui.wizards.NewEiqFileWizardContainerConfigurationPage.java

License:Open Source License

private IStatus validatePackageName(String text) {
    if (text == null || text.isEmpty()) {
        return new Status(IStatus.WARNING, IncQueryGUIPlugin.PLUGIN_ID, DEFAULT_PACKAGE_WARNING);
    }//  w ww .  j  a  v  a  2s  . c o  m
    IJavaProject project = getJavaProject();
    if (project == null || !project.exists()) {
        return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_6, JavaCore.VERSION_1_6);
    }
    IStatus status = JavaConventionsUtil.validatePackageName(text, project);
    if (!text.toLowerCase().equals(text)) {
        return new Status(IStatus.ERROR, IncQueryGUIPlugin.PLUGIN_ID, PACKAGE_NAME_WARNING);
    }
    return status;
}

From source file:org.eclipse.jem.internal.proxy.core.ProxyLaunchSupport.java

License:Open Source License

/**
 * Fill in the launch info config info and contribs. The contribs sent in may be expanded due to extension
 * points and a new one created. Either the expanded copy or the original (if no change) will be stored in
 * the launchinfo and returned from this call.
 * //from   w  w  w .  ja  va2 s. c om
 * @param aContribs this should never be <code>null</code>. Pass in {@link ProxyLaunchSupport#EMPTY_CONFIG_CONTRIBUTORS} in that case.
 * @param launchInfo
 * @param projectName
 * @return a modified aContribs if any change was made to it.  This will never be <code>null</code>. It will return an empty list if aContribs was null and no changes were made.
 * @throws JavaModelException
 * @throws CoreException
 * 
 * @since 1.0.0
 */
public static IConfigurationContributor[] fillInLaunchInfo(IConfigurationContributor[] aContribs,
        LaunchInfo launchInfo, String projectName) throws JavaModelException, CoreException {
    if (projectName != null) {
        projectName = projectName.trim();
        if (projectName.length() > 0) {
            IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
            IJavaProject javaProject = JavaCore.create(project);
            if (javaProject != null && javaProject.exists()) {
                launchInfo.configInfo = createDefaultConfigurationContributionInfo(javaProject);
                if (!launchInfo.configInfo.getContainerIds().isEmpty()
                        || !launchInfo.configInfo.getContainers().isEmpty()
                        || !launchInfo.configInfo.getPluginIds().isEmpty()) {
                    List computedContributors = new ArrayList(launchInfo.configInfo.getContainerIds().size()
                            + launchInfo.configInfo.getContainers().size()
                            + launchInfo.configInfo.getPluginIds().size());
                    // Note: We don't care about the visibility business here. For contributors to proxy it means
                    // some classes in the projects/plugins/etc. need configuration whether they are visible or not.
                    // This is because even though not visible, some other visible class may instantiate it. So it
                    // needs the configuration.
                    // First handle explicit classpath containers that implement IConfigurationContributor
                    for (Iterator iter = launchInfo.configInfo.getContainers().keySet().iterator(); iter
                            .hasNext();) {
                        IClasspathContainer container = (IClasspathContainer) iter.next();
                        if (container instanceof IConfigurationContributor)
                            computedContributors.add(container);
                    }

                    // Second add in contributors that exist for a container id.
                    for (Iterator iter = launchInfo.configInfo.getContainerIds().values().iterator(); iter
                            .hasNext();) {
                        ContainerPaths paths = (ContainerPaths) iter.next();
                        IConfigurationElement[] contributors = ProxyPlugin.getPlugin()
                                .getContainerConfigurations(paths.getContainerId(), paths.getAllPaths());
                        if (contributors != null)
                            for (int i = 0; i < contributors.length; i++) {
                                Object contributor = contributors[i]
                                        .createExecutableExtension(ProxyPlugin.PI_CLASS);
                                if (contributor instanceof IConfigurationContributor)
                                    computedContributors.add(contributor);
                            }
                    }

                    // Finally add in contributors that exist for a plugin id.
                    for (Iterator iter = launchInfo.configInfo.getPluginIds().keySet().iterator(); iter
                            .hasNext();) {
                        String pluginId = (String) iter.next();
                        IConfigurationElement[] contributors = ProxyPlugin.getPlugin()
                                .getPluginConfigurations(pluginId);
                        if (contributors != null)
                            for (int i = 0; i < contributors.length; i++) {
                                Object contributor = contributors[i]
                                        .createExecutableExtension(ProxyPlugin.PI_CLASS);
                                if (contributor instanceof IConfigurationContributor)
                                    computedContributors.add(contributor);
                            }
                    }

                    // Now turn into array
                    if (!computedContributors.isEmpty()) {
                        IConfigurationContributor[] newContribs = new IConfigurationContributor[aContribs.length
                                + computedContributors.size()];
                        System.arraycopy(aContribs, 0, newContribs, 0, aContribs.length);
                        IConfigurationContributor[] cContribs = (IConfigurationContributor[]) computedContributors
                                .toArray(new IConfigurationContributor[computedContributors.size()]);
                        System.arraycopy(cContribs, 0, newContribs, aContribs.length, cContribs.length);
                        aContribs = newContribs;
                    }
                }
            }
        }
    }

    launchInfo.contributors = aContribs;
    return aContribs;
}

From source file:org.eclipse.jem.internal.proxy.core.ProxyPlugin.java

License:Open Source License

private void expandProject(IPath projectPath, FoundIDs foundIds, boolean visible, boolean first)
        throws JavaModelException {
    IResource res = ResourcesPlugin.getWorkspace().getRoot().findMember(projectPath.lastSegment());
    if (res == null)
        return; // Not exist so don't delve into it.
    IJavaProject project = (IJavaProject) JavaCore.create(res);
    if (project == null || !project.exists() || !project.getProject().isOpen())
        return; // Not exist as a java project or not open, so don't delve into it.

    IClasspathEntry[] entries = project.getRawClasspath();
    for (int i = 0; i < entries.length; i++) {
        IClasspathEntry entry = entries[i];
        Boolean currentFlag = null; // Current setting value.
        boolean newFlag; // The new setting value. 
        switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_PROJECT:
            // Force true if already true, or this is the first project, or this project is visible and the entry is exported. These override a previous false.
            currentFlag = (Boolean) foundIds.projects.get(entry.getPath());
            newFlag = (currentFlag != null && currentFlag.booleanValue()) || first
                    || (visible && entry.isExported());
            if (currentFlag == null || currentFlag.booleanValue() != newFlag)
                foundIds.projects.put(entry.getPath(), newFlag ? Boolean.TRUE : Boolean.FALSE);
            if (currentFlag == null)
                expandProject(entry.getPath(), foundIds, visible && entry.isExported(), false);
            break;
        case IClasspathEntry.CPE_CONTAINER:
            if (!first && JavaRuntime.JRE_CONTAINER.equals(entry.getPath().segment(0))) //$NON-NLS-1$
                break; // The first project determines the JRE, so any subsequent ones can be ignored.
            Map[] paths = (Map[]) foundIds.containerIds.get(entry.getPath().segment(0));
            if (paths == null) {
                paths = new Map[] { new HashMap(2), new HashMap(2) };
                foundIds.containerIds.put(entry.getPath().segment(0), paths);
            }//from   w w  w  .  j  a v  a 2 s  .com
            currentFlag = null;
            if (paths[0].containsKey(entry.getPath()))
                currentFlag = Boolean.TRUE;
            else if (paths[1].containsKey(entry.getPath()))
                currentFlag = Boolean.FALSE;
            newFlag = (currentFlag != null && currentFlag.booleanValue()) || first
                    || (visible && entry.isExported());
            if (currentFlag == null || currentFlag.booleanValue() != newFlag) {
                if (newFlag) {
                    // It is visible, remove from hidden, if there, and add to visible.
                    paths[1].remove(entry.getPath());
                    paths[0].put(entry.getPath(), entry.getPath().toString());
                } else {
                    // It is hidden, remove from visible, if there, and add to hidden.
                    paths[0].remove(entry.getPath());
                    paths[1].put(entry.getPath(), entry.getPath().toString());
                }
            }

            IClasspathContainer container = JavaCore.getClasspathContainer(entry.getPath(), project);
            // Force true if already true, or this is the first project, or this project is visible and the entry is exported. These override a previous false.
            currentFlag = (Boolean) foundIds.containers.get(container);
            newFlag = (currentFlag != null && currentFlag.booleanValue()) || first
                    || (visible && entry.isExported());
            if (currentFlag == null || currentFlag.booleanValue() != newFlag)
                foundIds.containers.put(container, newFlag ? Boolean.TRUE : Boolean.FALSE);
            break;
        case IClasspathEntry.CPE_VARIABLE:
            // We only care about JRE_LIB. If we have that, then we will treat it as JRE_CONTAINER. Only
            // care about first project too, because the first project is the one that determines the JRE type.
            if (first && JavaRuntime.JRELIB_VARIABLE.equals(entry.getPath().segment(0))) { //$NON-NLS-1$
                paths = (Map[]) foundIds.containerIds.get(JavaRuntime.JRE_CONTAINER);
                if (paths == null) {
                    paths = new Map[] { new HashMap(2), new HashMap(2) };
                    foundIds.containerIds.put(JavaRuntime.JRE_CONTAINER, paths);
                }
                currentFlag = null;
                if (paths[0].containsKey(JRE_CONTAINER_PATH))
                    currentFlag = Boolean.TRUE;
                else if (paths[1].containsKey(JRE_CONTAINER_PATH))
                    currentFlag = Boolean.FALSE;
                newFlag = (currentFlag != null && currentFlag.booleanValue()) || first
                        || (visible && entry.isExported());
                if (currentFlag == null || currentFlag.booleanValue() != newFlag) {
                    if (newFlag) {
                        // It is visible, remove from hidden, if there, and add to visible.
                        paths[1].remove(JRE_CONTAINER_PATH);
                        paths[0].put(JRE_CONTAINER_PATH, JavaRuntime.JRE_CONTAINER);
                    } else {
                        // It is hidden, remove from visible, if there, and add to hidden.
                        paths[0].remove(JRE_CONTAINER_PATH);
                        paths[1].put(JRE_CONTAINER_PATH, JavaRuntime.JRE_CONTAINER);
                    }
                }
            }
            break;
        default:
            break;
        }
    }

    findPlugins(foundIds, visible, first, project);
}

From source file:org.eclipse.jpt.jpa.annotate.util.AnnotateMappingUtil.java

License:Open Source License

/**
 * Retrieves an IType for a given Java project or any project it references.
 * Anonymous types cannot be retrieved with this method.  
 * @param fullyQualifiedType The fully qualified name of the type - for example "java.lang.String".  
 *        This doesn't work for primitive or array types, such as "int" or "Foo[]".
 * @param project The project that is in scope.
 *///from  w w w. j  a  v a2 s  .co m
public static IType getType(String fullyQualifiedType, IProject project) throws JavaModelException {
    assert fullyQualifiedType != null : "Fully qualified type should not be null."; //$NON-NLS-1$

    // the JDT returns a non-null anonymous class IType 
    // for empty string and package names that end with a dot
    // if the type starts with a dot, the JDT helpfully removes it 
    // and returns the type referenced without the dot
    // short circuit here for perf and so validation results make sense
    // e.g. if the valid type is "Thing", then ".Thing" and "Thing." should not be valid
    if (fullyQualifiedType.trim().length() == 0 || fullyQualifiedType.startsWith(".") //$NON-NLS-1$
            || fullyQualifiedType.endsWith(".")) //$NON-NLS-1$
        return null;

    int ltIndex = fullyQualifiedType.indexOf('<');
    int gtIndex = fullyQualifiedType.lastIndexOf('>');
    if (ltIndex != -1 && gtIndex != -1 && gtIndex > ltIndex)
        assert false : "Type should have type parameter info stripped before calling this method: " //$NON-NLS-1$
                + fullyQualifiedType;
    assert !isArrayType(fullyQualifiedType) : "Type should have array brackets stripped before calling: " + //$NON-NLS-1$
            fullyQualifiedType;
    assert project != null : "Project should not be null."; //$NON-NLS-1$

    // if the project is not accessible, this will cause a JavaModelException below
    if (!project.isAccessible()) {
        return null;
    }

    IJavaProject javaProject = JavaCore.create(project);

    if ((javaProject == null) || (!javaProject.exists())) {
        return null;
    }

    IType type = null;
    type = javaProject.findType(fullyQualifiedType);
    if (type != null && (!type.exists() || type.isAnonymous())) {
        type = null;
    }
    return type;
}

From source file:org.eclipse.jpt.jpa.gen.internal.PackageGenerator.java

License:Open Source License

private IPackageFragmentRoot getDefaultJavaSourceLocation(IJavaProject jproject, String sourceFolder) {
    IPackageFragmentRoot defaultSrcPath = null;
    if (jproject != null && jproject.exists()) {
        try {/*from   ww  w .  ja v a  2 s.  c  o m*/
            IPackageFragmentRoot[] roots = jproject.getPackageFragmentRoots();
            for (int i = 0; i < roots.length; i++) {
                if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
                    if (defaultSrcPath == null) {
                        defaultSrcPath = roots[i];
                    }
                    String path = roots[i].getPath().toString();
                    if (path.equals('/' + sourceFolder)) {
                        return roots[i];
                    }
                }
            }
        } catch (JavaModelException e) {
            JptJpaGenPlugin.instance().logError(e);
        }
    }
    return defaultSrcPath;
}