Java Code Examples for org.eclipse.jdt.core.IPackageFragmentRoot#getJavaProject()

The following examples show how to use org.eclipse.jdt.core.IPackageFragmentRoot#getJavaProject() . 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: EditFilterAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected boolean canHandle(IStructuredSelection selection) {
	if (selection.size() != 1)
		return false;

	try {
		Object element= selection.getFirstElement();
		if (element instanceof IJavaProject) {
			return ClasspathModifier.isSourceFolder((IJavaProject)element);
		} else if (element instanceof IPackageFragmentRoot) {
			IPackageFragmentRoot packageFragmentRoot= ((IPackageFragmentRoot) element);
			if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE)
				return false;

			return packageFragmentRoot.getJavaProject() != null;
		}
	} catch (JavaModelException e) {
	}
	return false;
}
 
Example 2
Source File: JarEntryEditorInputFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IPackageFragmentRoot fuzzyResolveRoot(IPackageFragmentRoot restoredRoot) throws JavaModelException {
	IJavaProject project= restoredRoot.getJavaProject();
	String rootName= restoredRoot.getElementName();
	int versionSepIndex= rootName.indexOf('_');
	if (versionSepIndex > 0) {
		// try stripping plug-in version number
		String prefix= rootName.substring(0, versionSepIndex);
		IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
		for (int i= 0; i < roots.length; i++) {
			if (roots[i].getElementName().startsWith(prefix)) {
				return roots[i];
			}
		}
	}
	return null;
}
 
Example 3
Source File: PackageExplorerContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Object internalGetParent(Object element) {
	if (!fIsFlatLayout && element instanceof IPackageFragment) {
		return getHierarchicalPackageParent((IPackageFragment) element);
	} else if (element instanceof IPackageFragmentRoot) {
		// since we insert logical package containers we have to fix
		// up the parent for package fragment roots so that they refer
		// to the container and containers refer to the project
		IPackageFragmentRoot root= (IPackageFragmentRoot)element;

		try {
			IClasspathEntry entry= root.getRawClasspathEntry();
			int entryKind= entry.getEntryKind();
			if (entryKind == IClasspathEntry.CPE_CONTAINER) {
				return new ClassPathContainer(root.getJavaProject(), entry);
			} else if (fShowLibrariesNode && (entryKind == IClasspathEntry.CPE_LIBRARY || entryKind == IClasspathEntry.CPE_VARIABLE)) {
				return new LibraryContainer(root.getJavaProject());
			}
		} catch (JavaModelException e) {
			// fall through
		}
	} else if (element instanceof PackageFragmentRootContainer) {
		return ((PackageFragmentRootContainer)element).getJavaProject();
	}
	return super.internalGetParent(element);
}
 
Example 4
Source File: JavaClassPathResourceForIEditorInputFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected ResourceSet getResourceSet(/* @Nullable */ IStorage storage) {
	if (storage instanceof IJarEntryResource) {
		IPackageFragmentRoot root = ((IJarEntryResource) storage).getPackageFragmentRoot();
		if (root != null) {
			IJavaProject project = root.getJavaProject();
			if (project != null)
				return getResourceSetProvider().get(project.getProject());
		}
	} 
	return super.getResourceSet(storage);
}
 
Example 5
Source File: JavadocProjectContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Object getParent(Object element) {

		IJavaElement parent= ((IJavaElement)element).getParent();
		if (parent instanceof IPackageFragmentRoot) {
			IPackageFragmentRoot root= (IPackageFragmentRoot) parent;
			if (root.getPath().equals(root.getJavaProject().getProject().getFullPath())) {
				return root.getJavaProject();
			}
		}
		return parent;
	}
 
Example 6
Source File: PackageExplorerContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Object getHierarchicalPackageParent(IPackageFragment child) {
	String name= child.getElementName();
	IPackageFragmentRoot parent= (IPackageFragmentRoot) child.getParent();
	int index= name.lastIndexOf('.');
	if (index != -1) {
		String realParentName= name.substring(0, index);
		IPackageFragment element= parent.getPackageFragment(realParentName);
		if (element.exists()) {
			try {
				if (fFoldPackages && isEmpty(element) && findSinglePackageChild(element, parent.getChildren()) != null) {
					return getHierarchicalPackageParent(element);
				}
			} catch (JavaModelException e) {
				// ignore
			}
			return element;
		} else { // bug 65240
			IResource resource= element.getResource();
			if (resource != null) {
				return resource;
			}
		}
	}
	if (parent.getResource() instanceof IProject) {
		return parent.getJavaProject();
	}
	return parent;
}
 
Example 7
Source File: JarPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Set<Object> removeContainedChildren(Set<Object> elements) {
	Set<Object> newList= new HashSet<Object>(elements.size());
	Set<Object> javaElementResources= getCorrespondingContainers(elements);
	Iterator<Object> iter= elements.iterator();
	boolean removedOne= false;
	while (iter.hasNext()) {
		Object element= iter.next();
		Object parent;
		if (element instanceof IResource)
			parent= ((IResource)element).getParent();
		else if (element instanceof IJavaElement) {
			parent= ((IJavaElement)element).getParent();
			if (parent instanceof IPackageFragmentRoot) {
				IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
				try {
					if (pkgRoot.getCorrespondingResource() instanceof IProject)
						parent= pkgRoot.getJavaProject();
				} catch (JavaModelException ex) {
					// leave parent as is
				}
			}
		}
		else {
			// unknown type
			newList.add(element);
			continue;
		}
		if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
			removedOne= true;
		else
			newList.add(element);
	}
	if (removedOne)
		return removeContainedChildren(newList);
	else
		return newList;
}
 
Example 8
Source File: NewContainerWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the Java project of the currently selected package fragment root or <code>null</code>
 * if no package fragment root is configured.
 *
 * @return The current Java project or <code>null</code>.
 * @since 3.3
 */
public IJavaProject getJavaProject() {
	IPackageFragmentRoot root= getPackageFragmentRoot();
	if (root != null) {
		return root.getJavaProject();
	}
	return null;
}
 
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: LoggedCreateTargetQueries.java    From eclipse.jdt.ls with Eclipse Public License 2.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()) {
		ResourceUtil.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 11
Source File: JavaProjectsStateHelper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public Collection<URI> initContainedURIs(String containerHandle) {
	IJavaElement javaElement = JavaCore.create(containerHandle);
	if (javaElement instanceof IPackageFragmentRoot) {
		IPackageFragmentRoot root = (IPackageFragmentRoot) javaElement;
		IJavaProject javaProject = root.getJavaProject();
		if (!isAccessibleXtextProject(javaProject.getProject())) {
			return Collections.emptyList();
		}
		Map<URI, IStorage> entries = uriMapperExtensions.getAllEntries(root);
		return entries.keySet();
	}
	return Collections.emptyList();
}
 
Example 12
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * A hook method that gets called when the package field has changed. The method
 * validates the package name and returns the status of the validation. The validation
 * also updates the package fragment model.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus packageChanged() {
	StatusInfo status= new StatusInfo();
	IPackageFragmentRoot root= getPackageFragmentRoot();
	fPackageDialogField.enableButton(root != null);

	IJavaProject project= root != null ? root.getJavaProject() : null;

	String packName= getPackageText();
	if (packName.length() > 0) {
		IStatus val= validatePackageName(packName, project);
		if (val.getSeverity() == IStatus.ERROR) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidPackageName, val.getMessage()));
			return status;
		} else if (val.getSeverity() == IStatus.WARNING) {
			status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_DiscouragedPackageName, val.getMessage()));
			// continue
		}
	} else {
		status.setWarning(NewWizardMessages.NewTypeWizardPage_warning_DefaultPackageDiscouraged);
	}

	if (project != null) {
		if (project.exists() && packName.length() > 0) {
			try {
				IPath rootPath= root.getPath();
				IPath outputPath= project.getOutputLocation();
				if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
					// if the bin folder is inside of our root, don't allow to name a package
					// like the bin folder
					IPath packagePath= rootPath.append(packName.replace('.', '/'));
					if (outputPath.isPrefixOf(packagePath)) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_ClashOutputLocation);
						return status;
					}
				}
			} catch (JavaModelException e) {
				JavaPlugin.log(e);
				// let pass
			}
		}

		fCurrPackage= root.getPackageFragment(packName);
		IResource resource= fCurrPackage.getResource();
		if (resource != null){
			if (resource.isVirtual()){
				status.setError(NewWizardMessages.NewTypeWizardPage_error_PackageIsVirtual);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_PackageNameFiltered);
				return status;
			}
		}
	} else {
		status.setError(""); //$NON-NLS-1$
	}
	return status;
}
 
Example 13
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected RefactoringStatus aboutToPerformHistory(final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		fJavaProject= null;
		fSourceFolder= null;
		fProcessedFragments.clear();
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 520);
		status.merge(super.aboutToPerformHistory(new SubProgressMonitor(monitor, 10, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
		if (!status.hasFatalError()) {
			final IPackageFragmentRoot root= getPackageFragmentRoot();
			if (root != null) {
				status.merge(checkPackageFragmentRoots(root, new SubProgressMonitor(monitor, 90, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
				if (!status.hasFatalError()) {
					status.merge(checkSourceAttachmentRefactorings(new SubProgressMonitor(monitor, 20, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL)));
					if (!status.hasFatalError()) {
						final IJavaProject project= root.getJavaProject();
						if (project != null) {
							final IFolder folder= project.getProject().getFolder(SOURCE_FOLDER + String.valueOf(System.currentTimeMillis()));
							try {
								fAutoBuild= CoreUtility.setAutoBuilding(false);
								final RefactoringHistory history= getRefactoringHistory();
								if (history != null && !history.isEmpty())
									configureClasspath(project, root, folder, new SubProgressMonitor(monitor, 300, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
							} catch (CoreException exception) {
								status.merge(RefactoringStatus.createFatalErrorStatus(exception.getLocalizedMessage()));
								try {
									project.setRawClasspath(project.readRawClasspath(), false, new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
								} catch (CoreException throwable) {
									JavaPlugin.log(throwable);
								}
							} finally {
								if (!status.hasFatalError()) {
									fJavaProject= project;
									fSourceFolder= folder;
								}
							}
						}
					}
				}
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 14
Source File: NewModuleWizard.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected InputStream getInitialContents() {
  List<String> contents = new ArrayList<String>();

  IPackageFragmentRoot root = newModuleWizardPage.getPackageFragmentRoot();
  IJavaProject javaProject = root.getJavaProject();

  contents.add("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
  String gwtModuleDtd = NO_VERSION_FOUND_DTD;

  GwtSdk runtime = GwtSdk.findSdkFor(javaProject);
  if (runtime != null) {
    String versionNum = runtime.getVersion();

    if (!versionNum.endsWith(".999") && !versionNum.startsWith("0.0")) {
      gwtModuleDtd = "<!DOCTYPE module PUBLIC \"-//Google Inc.//DTD Google Web Toolkit " + versionNum
          + "//EN\" \"http://google-web-toolkit.googlecode.com/svn/tags/" + versionNum
          + "/distro-source/core/src/gwt-module.dtd\">";
    }
  }

  contents.add(gwtModuleDtd);

  contents.add("<module>");

  List<IModule> moduleInherits = newModuleWizardPage.getModuleInherits();

  // TODO: Instead of hardcoding a tab character here, we should try and use
  // the WST editor preferences for indentation. We should respect the user's
  // preferences for spaces vs. tabs, and the number of spaces that make up an
  // indentation.
  for (IModule moduleInherit : moduleInherits) {
    contents.add("\t<inherits name=\"" + moduleInherit.getQualifiedName() + "\" />");
  }

  // Explicitly add the source path element
  contents.add("\t<source path=\"client\"/>");

  contents.add("</module>");

  String xml = Util.join(contents, System.getProperty("line.separator"));
  ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
  return stream;
}
 
Example 15
Source File: ClassFileDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Recursively check whether the class file has been deleted.
 * 
 * @param input the package fragment root
 * @param delta the Java element delta
 * @return <code>true</code> if delta processing can be stopped
 */
protected boolean check(IPackageFragmentRoot input, IJavaElementDelta delta) {
	IJavaElement element= delta.getElement();

	if ((delta.getKind() & IJavaElementDelta.REMOVED) != 0 || (delta.getFlags() & IJavaElementDelta.F_CLOSED) != 0) {
		// http://dev.eclipse.org/bugs/show_bug.cgi?id=19023
		if (element.equals(input.getJavaProject()) || element.equals(input)) {
			handleDeleted(fInput);
			return true;
		}
	}

	if (((delta.getFlags() & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) && input.equals(element)) {
		handleDeleted(fInput);
		return true;
	}

	if (((delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) && input.equals(element)) {
		handleDeleted(fInput);
		return true;
	}

	IJavaElementDelta[] subdeltas= delta.getAffectedChildren();
	for (int i= 0; i < subdeltas.length; i++) {
		if (check(input, subdeltas[i]))
			return true;
	}

	if ((delta.getFlags() & IJavaElementDelta.F_SOURCEDETACHED) != 0 ||
		(delta.getFlags() & IJavaElementDelta.F_SOURCEATTACHED) != 0)
	{
		IClassFile file= fInput != null ? fInput.getClassFile() : null;
		IJavaProject project= input != null ? input.getJavaProject() : null;

		boolean isOnClasspath= false;
		if (file != null && project != null)
			isOnClasspath= project.isOnClasspath(file);

		if (isOnClasspath) {
			fireInputChanged(fInput);
			return false;
		} else {
			handleDeleted(fInput);
			return true;
		}
	}

	return false;
}
 
Example 16
Source File: ClassFileEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaModelException {
	IClasspathEntry entry;
	try {
		entry= JavaModelUtil.getClasspathEntry(root);
	} catch (JavaModelException ex) {
		if (ex.isDoesNotExist())
			entry= null;
		else
			throw ex;
	}
	IPath containerPath= null;

	if (entry == null || root.getKind() != IPackageFragmentRoot.K_BINARY) {
		createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSource, BasicElementLabels.getFileName( fFile)));
		return;
	}

	IJavaProject jproject= root.getJavaProject();
	boolean canEditEncoding= true;
	if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
		containerPath= entry.getPath();
		ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0));
		IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject);
		if (initializer == null || container == null) {
			createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_cannotconfigure, BasicElementLabels.getPathLabel(containerPath, false)));
			return;
		}
		String containerName= container.getDescription();
		IStatus status= initializer.getSourceAttachmentStatus(containerPath, jproject);
		if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED) {
			createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_notsupported, containerName));
			return;
		}
		if (status.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY) {
			createLabel(composite, Messages.format(JavaEditorMessages.ClassFileEditor_SourceAttachmentForm_readonly, containerName));
			return;
		}
		IStatus attributeStatus= initializer.getAttributeStatus(containerPath, jproject, IClasspathAttribute.SOURCE_ATTACHMENT_ENCODING);
		canEditEncoding= !(attributeStatus.getCode() == ClasspathContainerInitializer.ATTRIBUTE_NOT_SUPPORTED || attributeStatus.getCode() == ClasspathContainerInitializer.ATTRIBUTE_READ_ONLY);
		entry= JavaModelUtil.findEntryInContainer(container, root.getPath());
		Assert.isNotNull(entry);
	}


	Button button;

	IPath path= entry.getSourceAttachmentPath();
	if (path == null || path.isEmpty()) {
		String rootLabel= JavaElementLabels.getElementLabel(root, JavaElementLabels.ALL_DEFAULT);
		createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSourceAttachment, rootLabel));
		createLabel(composite, JavaEditorMessages.SourceAttachmentForm_message_pressButtonToAttach);
		createLabel(composite, null);

		button= createButton(composite, JavaEditorMessages.SourceAttachmentForm_button_attachSource);

	} else {
		createLabel(composite, Messages.format(JavaEditorMessages.SourceAttachmentForm_message_noSourceInAttachment, BasicElementLabels.getFileName(fFile)));
		createLabel(composite, JavaEditorMessages.SourceAttachmentForm_message_pressButtonToChange);
		createLabel(composite, null);

		button= createButton(composite, JavaEditorMessages.SourceAttachmentForm_button_changeAttachedSource);
	}

	button.addSelectionListener(getButtonListener(entry, containerPath, jproject, canEditEncoding));
}
 
Example 17
Source File: EditOutputFolderAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean canHandle(final IStructuredSelection elements) {
	if (!fShowOutputFolders)
		return false;

	if (elements.size() != 1)
		return false;

	final Object element= elements.getFirstElement();
	try {
		if (element instanceof IPackageFragmentRoot) {
			final IPackageFragmentRoot root= (IPackageFragmentRoot)element;
			if (root.getKind() != IPackageFragmentRoot.K_SOURCE)
				return false;

			IJavaProject javaProject= root.getJavaProject();
			if (javaProject == null)
				return false;

			final IClasspathEntry entry= ClasspathModifier.getClasspathEntryFor(root.getPath(), javaProject, IClasspathEntry.CPE_SOURCE);
			if (entry == null)
				return false;

			return true;
		} else if (element instanceof IJavaProject) {
			IJavaProject project= (IJavaProject)element;
			if (!(ClasspathModifier.isSourceFolder(project)))
				return false;

			return true;
		} else if (element instanceof CPListElementAttribute) {
			CPListElementAttribute attribute= (CPListElementAttribute)element;
			if (attribute.getKey() != CPListElement.OUTPUT)
				return false;

			return true;
		}

	} catch (final JavaModelException e) {
		return false;
	}
	return false;
}
 
Example 18
Source File: StandardJavaElementContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Tests if the package fragment root is located on the project.
 *
 * @param root the package fragment root
 * @return returns <code>true</code> if the package fragment root is the located on the project
 */
protected boolean isProjectPackageFragmentRoot(IPackageFragmentRoot root) {
	IJavaProject javaProject= root.getJavaProject();
	return javaProject != null && javaProject.getPath().equals(root.getPath());
}