Java Code Examples for org.eclipse.jdt.core.IJavaProject#exists()

The following examples show how to use org.eclipse.jdt.core.IJavaProject#exists() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RefactoringScopeFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static void addReferencingProjects(IJavaProject focus, Set<IJavaProject> projects) throws JavaModelException {
	IProject[] referencingProjects = focus.getProject().getReferencingProjects();
	for (int i = 0; i < referencingProjects.length; i++) {
		IJavaProject candidate = JavaCore.create(referencingProjects[i]);
		if (candidate == null || projects.contains(candidate) || !candidate.exists()) {
			continue; // break cycle
		}
		IClasspathEntry entry = getReferencingClassPathEntry(candidate, focus);
		if (entry != null) {
			projects.add(candidate);
			if (entry.isExported()) {
				addReferencingProjects(candidate, projects);
			}
		}
	}
}
 
Example 2
Source File: JdtToBeBuiltComputer.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
protected boolean isBuiltByUpstream(IPackageFragmentRoot root, IProject project, IProject[] projectsInCorrectBuildOrder) {
	for (IProject p : projectsInCorrectBuildOrder) {
		if (p.equals(project))
			return false;
		if (XtextProjectHelper.hasNature(p) && XtextProjectHelper.hasBuilder(p)) {
			IJavaProject javaProject = JavaCore.create(p);
			if (javaProject.exists()) {
				if (javaProject.isOnClasspath(root)) {
					if (log.isTraceEnabled())
						log.trace("Build of project '"+project.getName()+"' skips indexing classpath entry '"+root.getPath()+"' because it already indexed by "+javaProject.getElementName());
					return true;
				}
			}
		}
	}
	return false;
}
 
Example 3
Source File: LaunchConfigurationProcessorUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Uses the processor to update the given configuration.
 */
public static void updateViaProcessor(
    ILaunchConfigurationProcessor processor,
    ILaunchConfigurationWorkingCopy configuration) {
  IJavaProject javaProject = LaunchConfigurationUtilities.getJavaProject(configuration);
  if (javaProject != null && javaProject.exists()) {
    try {
      List<String> programArgs = parseProgramArgs(configuration);
      List<String> vmArgs = parseVmArgs(configuration);
      processor.update(configuration, javaProject, programArgs, vmArgs);
      configuration.setAttribute(
          IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
          LaunchConfigurationProcessorUtilities.createArgsString(programArgs));
      configuration.setAttribute(
          IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS,
          LaunchConfigurationProcessorUtilities.createArgsString(vmArgs));
    } catch (Throwable e) {
      CorePluginLog.logError(e, "Could not update the launch configuration");
    }
  }
}
 
Example 4
Source File: ExportSarlApplicationPage.java    From sarl with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Java project specified by the given launch configuration, or
 * {@code null} if none.
 *
 * @param configuration
 *            launch configuration
 * @return the Java project specified by the given launch configuration, or
 *         {@code null} if none
 * @exception CoreException
 *                if unable to retrieve the attribute
 */
protected static IJavaProject getJavaProject(ILaunchConfiguration configuration)
		throws CoreException {
	String projectName = getJavaProjectName(configuration);
	if (projectName != null) {
		projectName = projectName.trim();
		if (projectName.length() > 0) {
			final IProject project = ResourcesPlugin.getWorkspace().getRoot()
					.getProject(projectName);
			final IJavaProject javaProject = JavaCore.create(project);
			if (javaProject != null && javaProject.exists()) {
				return javaProject;
			}
		}
	}
	return null;
}
 
Example 5
Source File: AbstractXtendContentAssistBugTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IJavaProject getJavaProject(ResourceSet resourceSet) {
	IJavaProject javaProject = findJavaProject(WorkbenchTestHelper.TESTPROJECT_NAME);
	if (javaProject == null || !javaProject.exists()) {
		try {
			demandCreateProject = WorkbenchTestHelper.createPluginProject(WorkbenchTestHelper.TESTPROJECT_NAME);
			javaProject = findJavaProject(WorkbenchTestHelper.TESTPROJECT_NAME);
		} catch (CoreException e) {
			fail("cannot create java project due to: " + e.getMessage() + " / " + e);
		}
	}
	return javaProject;
}
 
Example 6
Source File: AbstractCheckContentAssistBugTest.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public IJavaProject getJavaProject(final ResourceSet resourceSet) {
  IJavaProject javaProject = findJavaProject(PluginTestProjectManager.TEST_PROJECT_NAME);
  if (javaProject == null || !javaProject.exists()) {
    javaProject = findJavaProject(PluginTestProjectManager.TEST_PROJECT_NAME);
  }
  return javaProject;
}
 
Example 7
Source File: XtendUIValidator.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
protected String getExpectedPackageName(XtendFile xtendFile) {
	URI fileURI = xtendFile.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 claspathRelativePath = fileWorkspacePath.makeRelativeTo(sourceFolderPath);
									return claspathRelativePath.removeLastSegments(1).toString().replace("/", ".");
								}
							}
						}
					}
				} catch (JavaModelException e) {
					LOG.error("Error resolving expected path for XtendFile", e);
				}
			}
		}
	}
	return null;
}
 
Example 8
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IStatus validatePackageName(String text) {
	IJavaProject project= getJavaProject();
	if (project == null || !project.exists()) {
		return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3);
	}
	return JavaConventionsUtil.validatePackageName(text, project);
}
 
Example 9
Source File: LoggedCreateTargetQueries.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createPackageFragmentRoot(IPackageFragmentRoot root) throws CoreException {
	final IJavaProject project= root.getJavaProject();
	if (!project.exists())
		createJavaProject(project.getProject());
	final IFolder folder= project.getProject().getFolder(root.getElementName());
	if (!folder.exists())
		CoreUtility.createFolder(folder, true, true, new NullProgressMonitor());
	final List<IClasspathEntry> list= Arrays.asList(project.getRawClasspath());
	list.add(JavaCore.newSourceEntry(folder.getFullPath()));
	project.setRawClasspath(list.toArray(new IClasspathEntry[list.size()]), new NullProgressMonitor());
}
 
Example 10
Source File: NewContainerWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Initializes the source folder field with a valid package fragment root.
 * The package fragment root is computed from the given Java element.
 *
 * @param elem the Java element used to compute the initial package
 *    fragment root used as the source folder
 */
protected void initContainerPage(IJavaElement elem) {
	IPackageFragmentRoot initRoot= null;
	if (elem != null) {
		initRoot= JavaModelUtil.getPackageFragmentRoot(elem);
		try {
			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) {
			JavaPlugin.log(e);
		}
	}
	setPackageFragmentRoot(initRoot, true);
}
 
Example 11
Source File: JdtAwareProjectByResourceProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public IProject getProjectContext(Resource resource) {
	IProject result = super.getProjectContext(resource);
	if (result != null) {
		return result;
	}
	IJavaProject javaProject = javaProjectProvider.getJavaProject(resource.getResourceSet());
	if (javaProject != null && javaProject.exists()) {
		return javaProject.getProject();
	}
	return null;
}
 
Example 12
Source File: JdtClasspathUriResolver.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private URI findResourceInProjectRoot(IJavaProject javaProject, String path, Set<String> visited) throws CoreException {
	boolean includeAll = visited.isEmpty();
	if (visited.add(javaProject.getElementName())) {
		IProject project = javaProject.getProject();
		IResource resourceFromProjectRoot = project.findMember(path);
		if (resourceFromProjectRoot != null && resourceFromProjectRoot.exists()) {
			return createPlatformResourceURI(resourceFromProjectRoot);
		}
		for(IClasspathEntry entry: javaProject.getResolvedClasspath(true)) {
			if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
				if (includeAll || entry.isExported()) {
					IResource referencedProject = project.getWorkspace().getRoot().findMember(entry.getPath());
					if (referencedProject != null && referencedProject.getType() == IResource.PROJECT) {
						IJavaProject referencedJavaProject = JavaCore.create((IProject) referencedProject);
						if (referencedJavaProject.exists()) {
							URI result = findResourceInProjectRoot(referencedJavaProject, path, visited);
							if (result != null) {
								return result;
							}
						}
					}
					break;
				}
			}
		}
	}
	return null;
}
 
Example 13
Source File: NLSRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isEclipseNLSAvailable() {
	if (getCu() == null)
		return false;

	IJavaProject javaProject= getCu().getJavaProject();
	if (javaProject == null || !javaProject.exists())
		return false;

	try {
		return javaProject.findType("org.eclipse.osgi.util.NLS") != null; //$NON-NLS-1$
	} catch (JavaModelException e) {
		return false;
	}
}
 
Example 14
Source File: AddToClasspathAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IFile getCandidate(IAdaptable element) throws JavaModelException {
	IResource resource= (IResource)element.getAdapter(IResource.class);
	if (! (resource instanceof IFile) || ! ArchiveFileFilter.isArchivePath(resource.getFullPath(), true))
		return null;

	IJavaProject project= JavaCore.create(resource.getProject());
	if (project != null && project.exists() && (project.findPackageFragmentRoot(resource.getFullPath()) == null))
		return (IFile) resource;
	return null;
}
 
Example 15
Source File: SyntaxProjectsManager.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IPath[] listAllSourcePaths() throws JavaModelException {
	Set<IPath> classpaths = new HashSet<>();
	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
	for (IProject project : projects) {
		if (ProjectsManager.DEFAULT_PROJECT_NAME.equals(project.getName())) {
			continue;
		}
		IJavaProject javaProject = JavaCore.create(project);
		if (javaProject != null && javaProject.exists()) {
			IClasspathEntry[] classpath = javaProject.getRawClasspath();
			for (IClasspathEntry entry : classpath) {
				if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
					IPath path = entry.getPath();
					if (path == null) {
						continue;
					}

					IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(path);
					if (folder.exists() && !folder.isDerived()) {
						IPath location = folder.getLocation();
						if (location != null && !ResourceUtils.isContainedIn(location, classpaths)) {
							classpaths.add(location);
						}
					}
				}
			}
		}
	}

	return classpaths.toArray(new IPath[classpaths.size()]);
}
 
Example 16
Source File: GWTSettingsTab.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IProject getProject() throws CoreException {
  IJavaProject javaProject = getJavaProject();
  if (javaProject == null || !javaProject.exists()) {
    throw new CoreException(new Status(IStatus.ERROR, GWTPlugin.PLUGIN_ID, "Could not get a valid Java project"));
  }
  return javaProject.getProject();
}
 
Example 17
Source File: INSDEnvironmentPage.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the initial class path.
 *
 * @param classPath the class path
 * @return the initial class path
 */
private String getInitialClassPath(String classPath) {
  // do nothing if the container is not a project
  if (currentContainer.getType() != IResource.PROJECT) {
    return classPath;
  }

  try {
    IJavaProject javaProject = JavaCore.create((IProject) currentContainer);
    // if java project
    if (javaProject != null && javaProject.exists()) {

      MissingLibraries = new ArrayList();

      // get class path
      IClasspathEntry[] classPathEntries = javaProject.getResolvedClasspath(true);
      ArrayList resultStringEntries = tokenizeClassPath(classPath);

      // add classPathEntries
      addToClassPath(classPathEntries, resultStringEntries);

      // add output Location
      System.out.println("Output Location (normal): "
              + javaProject.getOutputLocation().toOSString());
      System.out.println("Output Location (relative): "
              + javaProject.getOutputLocation().makeRelative().toOSString());
      System.out.println("Output Location (absolute): "
              + javaProject.getOutputLocation().makeAbsolute().toOSString());
      String outputLocation = "$main_root/"
              + javaProject.getOutputLocation().makeRelative().removeFirstSegments(1)
                      .toOSString();
      outputLocation = outputLocation.replace('\\', '/');
      outputLocation = outputLocation.trim();
      System.out.println("Output Location (to class path): " + outputLocation);

      if (!contain(resultStringEntries, outputLocation)) {
        resultStringEntries.add(0, outputLocation);
        System.out.println("\tadded Output Location to ClassPath: " + outputLocation);
      }

      // convert class path a to String
      classPath = convertToString(resultStringEntries, ";");

      System.out.println("CLASSPATH: " + classPath);

      // warn about required projects (if any) javaProject.getRequiredProjectNames();
      if (MissingLibraries != null && MissingLibraries.size() > 0) {

        StringBuffer sb = new StringBuffer();
        Iterator itr = MissingLibraries.iterator();
        while (itr.hasNext())
          sb.append("\n- ").append((String) itr.next());
        MessageDialog
                .openWarning(
                        getShell(),
                        "Missing class path entries",
                        "The following class path entries corresponds to resources not included in your project. Please make sure all the required class path resources (except JRE and UIMA jars) are included in this project and in the PEAR class path (in the environment page of the wizard):"
                                + sb.toString());
      }
    }
  } catch (Throwable e) {
    MessageDialog
            .openWarning(
                    getShell(),
                    "Class Path Initialization",
                    "The class path could not be initialized properly. Please edit the class path variable in the environment page of the wizard.");
    e.printStackTrace();
  }

  return classPath;
}
 
Example 18
Source File: PackageExplorerContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isOnClassPath(ICompilationUnit element) {
	IJavaProject project= element.getJavaProject();
	if (project == null || !project.exists())
		return false;
	return project.isOnClasspath(element);
}
 
Example 19
Source File: JavaCompilationParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean isActive(IJavaProject project) {
  boolean active = project.exists() && GWTNature.isGWTProject(project.getProject());
  return active;
}
 
Example 20
Source File: JavaProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Returns <code>true</code> if the given IJavaProject is not null, and
 * <code>javaProject.exists()</code> is true.
 */
public static boolean isJavaProjectNonNullAndExists(IJavaProject javaProject) {
  return (javaProject != null && javaProject.exists());
}