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

The following examples show how to use org.eclipse.jdt.core.IJavaProject#findPackageFragmentRoot() . 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: JDTAwareEclipseResourceFileSystemAccess2.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.6
 */
protected void addToSourceFolders(IContainer container) throws JavaModelException {
	IJavaProject jp = JavaCore.create(container.getProject());
	if (jp.exists() && !jp.isOnClasspath(container)) {
		if (getCurrentSource() != null) {
			IPackageFragmentRoot packageFragmentRoot = jp.findPackageFragmentRoot(jp.getPath().append(getCurrentSource()));
			if (packageFragmentRoot != null) {
				IClasspathEntry currentClasspathEntry = packageFragmentRoot.getRawClasspathEntry();
				if (currentClasspathEntry != null) {
					insertClasspathEntry(container, currentClasspathEntry, jp);
					return;
				}
			}
		}
		addClasspathEntry(container, jp);
	}
}
 
Example 2
Source File: AbstractGWTPluginTestCase.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void addToTestProject() throws Exception {
  IProject testProject = Util.getWorkspaceRoot().getProject(TEST_PROJECT_NAME);
  if (!testProject.exists()) {
    throw new Exception("The test project does not exist");
  }

  IJavaProject javaProject = JavaCore.create(testProject);

  IPath srcPath = new Path("/" + TEST_PROJECT_NAME + "/src");
  IPackageFragmentRoot pckgRoot = javaProject.findPackageFragmentRoot(srcPath);

  String packageName = Signature.getQualifier(typeName);
  String cuName = Signature.getSimpleName(typeName) + ".java";

  // If the package fragment already exists, this call does nothing
  IPackageFragment pckg = pckgRoot.createPackageFragment(packageName, false, null);

  cu = pckg.createCompilationUnit(cuName, contents, true, null);
  JobsUtilities.waitForIdle();
}
 
Example 3
Source File: JavaProjectTestUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an {@link ICompilationUnit} with the given fully qualified name and
 * code in the <code>javaProject</code>.
 * 
 * @param javaProject java project to host the new class
 * @param fullyQualifiedClassName fully qualified name for the class
 * @param source code for the classs
 * @return newly created {@link ICompilationUnit}
 * @throws JavaModelException
 */
public static ICompilationUnit createCompilationUnit(
    IJavaProject javaProject, String fullyQualifiedClassName, String source)
    throws JavaModelException {
  IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  if (root == null) {
    addRawClassPathEntry(javaProject,
        JavaCore.newSourceEntry(javaProject.getPath()));
    root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  }

  String qualifier = Signature.getQualifier(fullyQualifiedClassName);
  IProgressMonitor monitor = new NullProgressMonitor();
  IPackageFragment packageFragment = root.createPackageFragment(qualifier,
      true, monitor);
  String name = Signature.getSimpleName(fullyQualifiedClassName);
  return packageFragment.createCompilationUnit(name + ".java", source, false,
      monitor);
}
 
Example 4
Source File: JavaProjectUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an {@link ICompilationUnit} with the given fully qualified name and
 * code in the <code>javaProject</code>.
 *
 * @param javaProject java project to host the new class
 * @param fullyQualifiedClassName fully qualified name for the class
 * @param source code for the classs
 * @return newly created {@link ICompilationUnit}
 * @throws JavaModelException
 */
public static ICompilationUnit createCompilationUnit(
    IJavaProject javaProject, String fullyQualifiedClassName, String source)
    throws JavaModelException {
  IPackageFragmentRoot root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  if (root == null) {
    addRawClassPathEntry(javaProject,
        JavaCore.newSourceEntry(javaProject.getPath()));
    root = javaProject.findPackageFragmentRoot(javaProject.getPath());
  }

  String qualifier = Signature.getQualifier(fullyQualifiedClassName);
  IProgressMonitor monitor = new NullProgressMonitor();
  IPackageFragment packageFragment = root.createPackageFragment(qualifier,
      true, monitor);
  String name = Signature.getSimpleName(fullyQualifiedClassName);
  ICompilationUnit cu = packageFragment.createCompilationUnit(name + ".java",
      source, false, monitor);
  JobsUtilities.waitForIdle();
  return cu;
}
 
Example 5
Source File: RenameSourceFolderProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public RefactoringStatus checkNewElementName(String newName) throws CoreException {
	Assert.isNotNull(newName, "new name"); //$NON-NLS-1$
	if (! newName.trim().equals(newName))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_blank);

	IContainer c= 	fSourceFolder.getResource().getParent();
	if (! c.getFullPath().isValidSegment(newName))
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_invalid_name);

	RefactoringStatus result= RefactoringStatus.create(c.getWorkspace().validateName(newName, IResource.FOLDER));
	if (result.hasFatalError())
		return result;

	result.merge(RefactoringStatus.create(c.getWorkspace().validatePath(createNewPath(newName), IResource.FOLDER)));
	if (result.hasFatalError())
		return result;

	IJavaProject project= fSourceFolder.getJavaProject();
	IPath p= project.getProject().getFullPath().append(newName);
	if (project.findPackageFragmentRoot(p) != null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_already_exists);

	if (project.getProject().findMember(new Path(newName)) != null)
		return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameSourceFolderRefactoring_alread_exists);
	return result;
}
 
Example 6
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void removeUnconfirmedReferencedArchiveFiles(IConfirmQuery query) throws JavaModelException, OperationCanceledException {
	List<IResource> filesToSkip= new ArrayList<IResource>(0);
	for (int i= 0; i < fResources.length; i++) {
		IResource resource= fResources[i];
		if (! (resource instanceof IFile))
			continue;

		IJavaProject project= JavaCore.create(resource.getProject());
		if (project == null || ! project.exists())
			continue;
		IPackageFragmentRoot root= project.findPackageFragmentRoot(resource.getFullPath());
		if (root == null)
			continue;
		List<IJavaProject> referencingProjects= Arrays.asList(JavaElementUtil.getReferencingProjects(root));
		if (skipDeletingReferencedRoot(query, root, referencingProjects))
			filesToSkip.add(resource);
	}
	removeFromSetToDelete(filesToSkip.toArray(new IFile[filesToSkip.size()]));
}
 
Example 7
Source File: SourceContainerDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean isSelectedValid(Object element) {
	try {
		if (element instanceof IJavaProject) {
			IJavaProject jproject= (IJavaProject) element;
			IPath path= jproject.getProject().getFullPath();
			return (jproject.findPackageFragmentRoot(path) != null);
		} else
			if (element instanceof IPackageFragmentRoot) {
				return (((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE);
			}
		return true;
	} catch (JavaModelException e) {
		// fall through returning false
	}
	return false;
}
 
Example 8
Source File: DestinationContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Object[] getResources(IContainer container) {
	try {
		IResource[] members= container.members();
		IJavaProject javaProject= JavaCore.create(container.getProject());
		if (javaProject == null || !javaProject.exists())
			return members;
		boolean isFolderOnClasspath = javaProject.isOnClasspath(container);
		List<IResource> nonJavaResources= new ArrayList<IResource>();
		// Can be on classpath but as a member of non-java resource folder
		for (int i= 0; i < members.length; i++) {
			IResource member= members[i];
			// A resource can also be a java element
			// in the case of exclusion and inclusion filters.
			// We therefore exclude Java elements from the list
			// of non-Java resources.
			if (isFolderOnClasspath) {
				if (javaProject.findPackageFragmentRoot(member.getFullPath()) == null) {
					nonJavaResources.add(member);
				}
			} else if (!javaProject.isOnClasspath(member)) {
				nonJavaResources.add(member);
			}
		}
		return nonJavaResources.toArray();
	} catch(CoreException e) {
		return NO_CHILDREN;
	}
}
 
Example 9
Source File: StandardJavaElementContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Evaluates all children of a given {@link IFolder}. Clients can override this method.
 * @param folder The folder to evaluate the children for.
 * @return The children of the given folder.
 * @exception CoreException if the folder does not exist.
 *
 * @since 3.3
 */
protected Object[] getFolderContent(IFolder folder) throws CoreException {
	IResource[] members= folder.members();
	IJavaProject javaProject= JavaCore.create(folder.getProject());
	if (javaProject == null || !javaProject.exists())
		return members;
	boolean isFolderOnClasspath = javaProject.isOnClasspath(folder);
	List<IResource> nonJavaResources= new ArrayList<IResource>();
	// Can be on classpath but as a member of non-java resource folder
	for (int i= 0; i < members.length; i++) {
		IResource member= members[i];
		// A resource can also be a java element
		// in the case of exclusion and inclusion filters.
		// We therefore exclude Java elements from the list
		// of non-Java resources.
		if (isFolderOnClasspath) {
			if (javaProject.findPackageFragmentRoot(member.getFullPath()) == null) {
				nonJavaResources.add(member);
			}
		} else if (!javaProject.isOnClasspath(member)) {
			nonJavaResources.add(member);
		} else {
			IJavaElement element= JavaCore.create(member, javaProject);
			if (element instanceof IPackageFragmentRoot
					&& javaProject.equals(element.getJavaProject())
					&& ((IPackageFragmentRoot)element).getKind() != IPackageFragmentRoot.K_SOURCE) {
				// don't skip libs and class folders on the classpath of their project
				nonJavaResources.add(member);
			}
		}
	}
	return nonJavaResources.toArray();
}
 
Example 10
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 11
Source File: JarFileExportOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
	if (jProject == null || path == null || path.segmentCount() <= 0)
		return null;
	IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
	if (pkgRoot != null)
		return pkgRoot;
	else
		return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
 
Example 12
Source File: SourceFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void renameLegacy(final String newQualifiedClassName) {
    final IJavaProject project = RepositoryManager.getInstance().getCurrentRepository().getJavaProject();
    String packageName = "";
    String className = newQualifiedClassName;

    if (newQualifiedClassName.indexOf(".") != -1) {
        packageName = newQualifiedClassName.substring(0, newQualifiedClassName.lastIndexOf("."));
        className = newQualifiedClassName.substring(newQualifiedClassName.lastIndexOf(".") + 1,
                newQualifiedClassName.length());
    }

    try {
        final IRepositoryStore<?> store = getParentStore();
        final IPackageFragmentRoot root = project.findPackageFragmentRoot(store.getResource().getFullPath());
        root.createPackageFragment(packageName, true, Repository.NULL_PROGRESS_MONITOR);
        final IPackageFragment targetContainer = project
                .findPackageFragment(store.getResource().getFullPath().append(packageName.replace(".", "/")));
        final IType type = project.findType(qualifiedClassName);
        if (type != null) {
            type.getCompilationUnit().move(targetContainer, null, className + ".java", true,
                    Repository.NULL_PROGRESS_MONITOR);
            qualifiedClassName = newQualifiedClassName;
        }
    } catch (final Exception e) {
        BonitaStudioLog.error(e);
    }
}
 
Example 13
Source File: FileEventHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static WorkspaceEdit computePackageRenameEdit(FileRenameEvent[] renameEvents, SourcePath[] sourcePaths, IProgressMonitor monitor) {
	WorkspaceEdit[] root = new WorkspaceEdit[1];
	SubMonitor submonitor = SubMonitor.convert(monitor, "Computing package rename updates...", 100 * renameEvents.length);
	for (FileRenameEvent event : renameEvents) {
		IPath oldLocation = ResourceUtils.filePathFromURI(event.oldUri);
		IPath newLocation = ResourceUtils.filePathFromURI(event.newUri);
		for (SourcePath sourcePath : sourcePaths) {
			IPath sourceLocation = Path.fromOSString(sourcePath.path);
			IPath sourceEntry = Path.fromOSString(sourcePath.classpathEntry);
			if (sourceLocation.isPrefixOf(oldLocation)) {
				SubMonitor renameMonitor = submonitor.split(100);
				try {
					IJavaProject javaProject = ProjectUtils.getJavaProject(sourcePath.projectName);
					if (javaProject == null) {
						break;
					}

					IPackageFragmentRoot packageRoot = javaProject.findPackageFragmentRoot(sourceEntry);
					if (packageRoot == null) {
						break;
					}

					String oldPackageName = String.join(".", oldLocation.makeRelativeTo(sourceLocation).segments());
					String newPackageName = String.join(".", newLocation.makeRelativeTo(sourceLocation).segments());
					IPackageFragment oldPackageFragment = packageRoot.getPackageFragment(oldPackageName);
					if (oldPackageFragment != null && !oldPackageFragment.isDefaultPackage() && oldPackageFragment.getResource() != null) {
						oldPackageFragment.getResource().refreshLocal(IResource.DEPTH_INFINITE, null);
						if (oldPackageFragment.exists()) {
							ResourcesPlugin.getWorkspace().run((pm) -> {
								WorkspaceEdit edit = getRenameEdit(oldPackageFragment, newPackageName, pm);
								root[0] = ChangeUtil.mergeChanges(root[0], edit, true);
							}, oldPackageFragment.getSchedulingRule(), IResource.NONE, renameMonitor);
						}
					}
				} catch (CoreException e) {
					JavaLanguageServerPlugin.logException("Failed to compute the package rename update", e);
				} finally {
					renameMonitor.done();
				}

				break;
			}
		}
	}

	submonitor.done();
	return ChangeUtil.hasChanges(root[0]) ? root[0] : null;
}
 
Example 14
Source File: ClasspathModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Check whether the provided file is an archive (.jar or .zip).
 *
 * @param file the file to be checked
 * @param project the Java project
 * @return <code>true</code> if the file is an archive, <code>false</code>
 * otherwise
 * @throws JavaModelException
 */
public static boolean isArchive(IFile file, IJavaProject project) throws JavaModelException {
	if (!ArchiveFileFilter.isArchivePath(file.getFullPath(), true))
		return false;
	if (project != null && project.exists() && (project.findPackageFragmentRoot(file.getFullPath()) == null))
		return true;
	return false;
}