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

The following examples show how to use org.eclipse.jdt.core.IPackageFragmentRoot#getKind() . 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: JavaModelUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the classpath entry of the given package fragment root. This is the raw entry, except
 * if the root is a referenced library, in which case it's the resolved entry.
 * 
 * @param root a package fragment root
 * @return the corresponding classpath entry
 * @throws JavaModelException if accessing the entry failed
 * @since 3.6
 */
public static IClasspathEntry getClasspathEntry(IPackageFragmentRoot root) throws JavaModelException {
	IClasspathEntry rawEntry= root.getRawClasspathEntry();
	int rawEntryKind= rawEntry.getEntryKind();
	switch (rawEntryKind) {
		case IClasspathEntry.CPE_LIBRARY:
		case IClasspathEntry.CPE_VARIABLE:
		case IClasspathEntry.CPE_CONTAINER: // should not happen, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037
			if (root.isArchive() && root.getKind() == IPackageFragmentRoot.K_BINARY) {
				IClasspathEntry resolvedEntry= root.getResolvedClasspathEntry();
				if (resolvedEntry.getReferencingEntry() != null)
					return resolvedEntry;
				else
					return rawEntry;
			}
	}
	return rawEntry;
}
 
Example 2
Source File: NLSHintHelper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IPackageFragment getResourceBundlePackage(IJavaProject javaProject, String packageName, String resourceName) throws JavaModelException {
	IPackageFragmentRoot[] allRoots= javaProject.getAllPackageFragmentRoots();
	for (int i= 0; i < allRoots.length; i++) {
		IPackageFragmentRoot root= allRoots[i];
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			IPackageFragment packageFragment= root.getPackageFragment(packageName);
			if (packageFragment.exists()) {
				Object[] resources= packageFragment.isDefaultPackage() ? root.getNonJavaResources() : packageFragment.getNonJavaResources();
				for (int j= 0; j < resources.length; j++) {
					Object object= resources[j];
					if (object instanceof IFile) {
						IFile file= (IFile) object;
						if (file.getName().equals(resourceName)) {
							return packageFragment;
						}
					}
				}
			}
		}
	}
	return null;
}
 
Example 3
Source File: OpenAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Object getPackageFragmentObjectToOpen(IPackageFragment packageFragment) throws JavaModelException {
	ITypeRoot typeRoot= null;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY)
		typeRoot= (packageFragment).getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	else
		typeRoot= (packageFragment).getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	if (typeRoot.exists())
		return typeRoot;
	
	Object[] nonJavaResources= (packageFragment).getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return file;
			}
		}
	}
	return packageFragment;
}
 
Example 4
Source File: JavadocContentAccess.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets a reader for an package fragment's Javadoc comment content from the source attachment.
 * The content does contain only the text from the comment without the Javadoc leading star characters.
 * Returns <code>null</code> if the package fragment does not contain a Javadoc comment or if no source is available.
 * @param fragment The package fragment to get the Javadoc of.
 * @return Returns a reader for the Javadoc comment content or <code>null</code> if the member
 * does not contain a Javadoc comment or if no source is available
 * @throws JavaModelException is thrown when the package fragment's javadoc can not be accessed
 * @since 3.4
 */
private static Reader internalGetContentReader(IPackageFragment fragment) throws JavaModelException {
	IPackageFragmentRoot root= (IPackageFragmentRoot) fragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);

	//1==> Handle the case when the documentation is present in package-info.java or package-info.class file
	boolean isBinary= root.getKind() == IPackageFragmentRoot.K_BINARY;
	ITypeRoot packageInfo;
	if (isBinary) {
		packageInfo= fragment.getClassFile(PACKAGE_INFO_CLASS);
	} else {
		packageInfo= fragment.getCompilationUnit(PACKAGE_INFO_JAVA);
	}
	if (packageInfo != null && packageInfo.exists()) {
		String source = packageInfo.getSource();
		//the source can be null for some of the class files
		if (source != null) {
			Javadoc javadocNode = getPackageJavadocNode(fragment, source);
			if (javadocNode != null) {
				int start = javadocNode.getStartPosition();
				int length = javadocNode.getLength();
				return new JavaDocCommentReader(source, start, start + length - 1);
			}
		}
	}
	return null;
}
 
Example 5
Source File: JavadocProjectContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
	ArrayList<Object> result= new ArrayList<Object>();

	IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
	for (int i= 0; i < roots.length; i++) {
		IPackageFragmentRoot root= roots[i];
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			if (root.getPath().equals(root.getJavaProject().getPath())) {
				Object[] packageFragments= getPackageFragments(root);
				for (int k= 0; k < packageFragments.length; k++) {
					result.add(packageFragments[k]);
				}
			} else {
				result.add(root);
			}
		}
	}
	return result.toArray();
}
 
Example 6
Source File: JavaDocLocations.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
	if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
		return getProjectJavadocLocation((IJavaProject) element);
	}

	IPackageFragmentRoot root = JavaModelUtil.getPackageFragmentRoot(element);
	if (root == null) {
		return null;
	}

	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		IClasspathEntry entry = root.getResolvedClasspathEntry();
		URL javadocLocation = getLibraryJavadocLocation(entry);
		if (javadocLocation != null) {
			return getLibraryJavadocLocation(entry);
		}
		entry = root.getRawClasspathEntry();
		switch (entry.getEntryKind()) {
			case IClasspathEntry.CPE_LIBRARY:
			case IClasspathEntry.CPE_VARIABLE:
				return getLibraryJavadocLocation(entry);
			default:
				return null;
		}
	} else {
		return getProjectJavadocLocation(root.getJavaProject());
	}
}
 
Example 7
Source File: CleanUpAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void collectCompilationUnits(IPackageFragmentRoot root, Collection<IJavaElement> result) throws JavaModelException {
	if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
		IJavaElement[] children= root.getChildren();
		for (int i= 0; i < children.length; i++) {
			collectCompilationUnits((IPackageFragment)children[i], result);
		}
	}
}
 
Example 8
Source File: JavaDocLocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException {
	if (element.getElementType() == IJavaElement.JAVA_PROJECT) {
		return getProjectJavadocLocation((IJavaProject) element);
	}

	IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
	if (root == null) {
		return null;
	}

	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		IClasspathEntry entry= root.getResolvedClasspathEntry();
		URL javadocLocation= getLibraryJavadocLocation(entry);
		if (javadocLocation != null) {
			return getLibraryJavadocLocation(entry);
		}
		entry= root.getRawClasspathEntry();
		switch (entry.getEntryKind()) {
			case IClasspathEntry.CPE_LIBRARY:
			case IClasspathEntry.CPE_VARIABLE:
				return getLibraryJavadocLocation(entry);
			default:
				return null;
		}
	} else {
		return getProjectJavadocLocation(root.getJavaProject());
	}
}
 
Example 9
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
private IClasspathEntry findJavaXValidationClasspathEntry() throws JavaModelException {
  IType type = javaProject.findType("javax.validation.Constraint");

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

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example 10
Source File: GWTMavenRuntime.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Find the classpath for get-dev.jar which is used to run super dev mode.
 *
 * @return IClasspathEntry for the path to gwt-dev.jar
 * @throws JavaModelException
 */
private IClasspathEntry findGwtCodeServerClasspathEntry() throws JavaModelException {
  IType type = javaProject.findType(GwtLaunchConfigurationProcessorUtilities.GWT_CODE_SERVER);
  if (type == null) {
    return null;
  }

  IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) type
      .getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
  if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_BINARY) {
    return JavaCore.newLibraryEntry(packageFragmentRoot.getPath(), null, null);
  }

  return null;
}
 
Example 11
Source File: CheckProjectHelper.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks that the Java file for the given class name exists in the project.
 *
 * @param project
 *          the project, must not be {@code null}
 * @param className
 *          the class name, must not be {@code null}
 * @return whether the corresponding java file exists in the project
 */
public boolean isJavaFilePresent(final IProject project, final String className) {
  int packageSplitIndex = className.lastIndexOf('.');
  if (packageSplitIndex == -1) {
    throw new IllegalArgumentException(String.format("%s is a simple class name or not a class name at all.", className));
  }
  int fileNameEndIndex = className.indexOf('$');
  if (fileNameEndIndex == -1) {
    fileNameEndIndex = className.length();
  }
  String packageName = className.substring(0, packageSplitIndex);
  String fileName = className.substring(packageSplitIndex + 1, fileNameEndIndex) + ".java";
  try {
    if (project.hasNature(JavaCore.NATURE_ID)) {
      for (IPackageFragmentRoot root : JavaCore.create(project).getAllPackageFragmentRoots()) {
        if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
          for (IJavaElement element : root.getChildren()) {
            if (element instanceof IPackageFragment && packageName.equals(element.getElementName())
                && ((IPackageFragment) element).getCompilationUnit(fileName).exists()) {
              return true;
            }
          }
        }
      }
    }
  } catch (CoreException e) {
    LOGGER.error(String.format("Failed to read project %s.", project.getName()), e);
  }
  return false;
}
 
Example 12
Source File: JavaSourcePackageFragmentRootCompletionProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @param prefix prefixString with thatthe sourcepackagefragmentroots must begin
 * @param replacementLength length of the text to replace
 * @return array with sourcepackagefragmentroots
 */
private ICompletionProposal[] createSourcePackageFragmentRootProposals(String prefix, int replacementLength) {
	List<JavaCompletionProposal> proposals= new ArrayList<JavaCompletionProposal>();
	try {
		IJavaProject[] projects= fRoot.getJavaProjects();
		for (int i= 0; i < projects.length; i++) {
			IJavaProject project= projects[i];
			IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
			for (int j= 0; j < roots.length; j++) {
				IPackageFragmentRoot root= roots[j];
				if (root.exists() && (root.getKind() == IPackageFragmentRoot.K_SOURCE)) {
					String name= root.getPath().toString();
					if (name.length() > 1) {
						name= name.substring(1);
					}
					if (name.startsWith(prefix)) {
						Image image= fLabelProvider.getImage(root);
						JavaCompletionProposal proposal= new JavaCompletionProposal(name, 0, replacementLength, image,
							name, 0);
						proposals.add(proposal);
					}
				}
			}
		}
	} catch (JavaModelException e) {
		// nothing to do
	}

	return proposals.toArray(new ICompletionProposal[proposals.size()]);
}
 
Example 13
Source File: JavaUI.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a selection dialog that lists all packages of the given Java project.
 * The caller is responsible for opening the dialog with <code>Window.open</code>,
 * and subsequently extracting the selected package (of type
 * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
 *
 * @param parent the parent shell of the dialog to be created
 * @param project the Java project
 * @param style flags defining the style of the dialog; the valid flags are:
 *   <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that
 *   packages from binary package fragment roots should be included in addition
 *   to those from source package fragment roots;
 *   <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that
 *   packages from required projects should be included as well.
 * @param filter the initial pattern to filter the set of packages. For example "com" shows
 * all packages starting with "com". The meta character '?' representing any character and
 * '*' representing any string are supported. Clients can pass an empty string if no filtering
 * is required.
 * @return a new selection dialog
 * @exception JavaModelException if the selection dialog could not be opened
 *
 * @since 2.0
 */
public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException {
	Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) ==
		(IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS));

	IPackageFragmentRoot[] roots= null;
	if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) {
	    roots= project.getAllPackageFragmentRoots();
	} else {
		roots= project.getPackageFragmentRoots();
	}

	List<IPackageFragmentRoot> consideredRoots= null;
	if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) {
		consideredRoots= Arrays.asList(roots);
	} else {
		consideredRoots= new ArrayList<IPackageFragmentRoot>(roots.length);
		for (int i= 0; i < roots.length; i++) {
			IPackageFragmentRoot root= roots[i];
			if (root.getKind() != IPackageFragmentRoot.K_BINARY)
				consideredRoots.add(root);

		}
	}

	IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(consideredRoots.toArray(new IJavaElement[consideredRoots.size()]));
	BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
	if (style == 0 || style == IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) {
		return createPackageDialog(parent, context, searchScope, false, true, filter);
	} else {
		return createPackageDialog(parent, context, searchScope, false, false, filter);
	}
}
 
Example 14
Source File: CleanUpAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean isEnabled(IStructuredSelection selection) {
	Object[] selected= selection.toArray();
	for (int i= 0; i < selected.length; i++) {
		try {
			if (selected[i] instanceof IJavaElement) {
				IJavaElement elem= (IJavaElement)selected[i];
				if (elem.exists()) {
					switch (elem.getElementType()) {
						case IJavaElement.TYPE:
							return elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT; // for browsing perspective
						case IJavaElement.COMPILATION_UNIT:
							return true;
						case IJavaElement.IMPORT_CONTAINER:
							return true;
						case IJavaElement.PACKAGE_FRAGMENT:
						case IJavaElement.PACKAGE_FRAGMENT_ROOT:
							IPackageFragmentRoot root= (IPackageFragmentRoot)elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
							return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
						case IJavaElement.JAVA_PROJECT:
							// https://bugs.eclipse.org/bugs/show_bug.cgi?id=65638
							return true;
					}
				}
			} else if (selected[i] instanceof LogicalPackage) {
				return true;
			} else if (selected[i] instanceof IWorkingSet) {
				IWorkingSet workingSet= (IWorkingSet) selected[i];
				return IWorkingSetIDs.JAVA.equals(workingSet.getId());
			}
		} catch (JavaModelException e) {
			if (!e.isDoesNotExist()) {
				JavaPlugin.log(e);
			}
		}
	}
	return false;
}
 
Example 15
Source File: MultiOrganizeImportsHandler.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
private void collectRelevantFiles(IPackageFragmentRoot root, Multimap<IProject, IFile> result)
		throws JavaModelException {
	if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
		IJavaElement[] children = root.getChildren();
		for (int i = 0; i < children.length; i++) {
			collectRelevantFiles((IPackageFragment) children[i], result);
		}

	}
}
 
Example 16
Source File: SourceContainerDialog.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean select(Viewer viewer, Object parent, Object element) {
	if (element instanceof IPackageFragmentRoot) {
		IPackageFragmentRoot fragmentRoot= (IPackageFragmentRoot)element;
		try {
			return (fragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE);
		} catch (JavaModelException e) {
			return false;
		}
	}
	return super.select(viewer, parent, element);
}
 
Example 17
Source File: JavadocHelpContext.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public JavadocHelpContext(IContext context, Object[] elements) throws JavaModelException {
	Assert.isNotNull(elements);
	if (context instanceof IContext2)
		fTitle= ((IContext2)context).getTitle();

	List<IHelpResource> helpResources= new ArrayList<IHelpResource>();

	String javadocSummary= null;
	for (int i= 0; i < elements.length; i++) {
		if (elements[i] instanceof IJavaElement) {
			IJavaElement element= (IJavaElement) elements[i];
			// if element isn't on the build path skip it
			if (!ActionUtil.isOnBuildPath(element))
				continue;

			// Create Javadoc summary
			if (BUG_85721_FIXED) {
				if (javadocSummary == null) {
					javadocSummary= retrieveText(element);
					if (javadocSummary != null) {
						String elementLabel= JavaElementLabels.getTextLabel(element, JavaElementLabels.ALL_DEFAULT);

						// FIXME: needs to be NLSed once the code becomes active
						javadocSummary= "<b>Javadoc for " + elementLabel + ":</b><br>" + javadocSummary;   //$NON-NLS-1$//$NON-NLS-2$
					}
				} else {
					javadocSummary= ""; // no Javadoc summary for multiple selection //$NON-NLS-1$
				}
			}

			URL url= JavaUI.getJavadocLocation(element, true);
			if (url == null || doesNotExist(url)) {
				IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
				if (root != null) {
					url= JavaUI.getJavadocBaseLocation(element);
					if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
						element= element.getJavaProject();
					} else {
						element= root;
					}
					url= JavaUI.getJavadocLocation(element, false);
				}
			}
			if (url != null) {
				IHelpResource javaResource= new JavaUIHelpResource(element, getURLString(url));
				helpResources.add(javaResource);
			}
		}
	}

	// Add static help topics
	if (context != null) {
		IHelpResource[] resources= context.getRelatedTopics();
		if (resources != null) {
			for (int j= 0; j < resources.length; j++) {
				helpResources.add(resources[j]);
			}
		}
	}

	fHelpResources= helpResources.toArray(new IHelpResource[helpResources.size()]);

	if (context != null)
		fText= context.getText();

	if (BUG_85721_FIXED) {
		if (javadocSummary != null && javadocSummary.length() > 0) {
			if (fText != null)
				fText= context.getText() + "<br><br>" + javadocSummary; //$NON-NLS-1$
			else
				fText= javadocSummary;
		}
	}

	if (fText == null)
		fText= "";  //$NON-NLS-1$

}
 
Example 18
Source File: ProblemsLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Computes the adornment flags for the given element.
 *
 * @param obj the element to compute the flags for
 *
 * @return the adornment flags
 */
protected int computeAdornmentFlags(Object obj) {
	try {
		if (obj instanceof IJavaElement) {
			IJavaElement element= (IJavaElement) obj;
			int type= element.getElementType();
			switch (type) {
				case IJavaElement.JAVA_MODEL:
				case IJavaElement.JAVA_PROJECT:
				case IJavaElement.PACKAGE_FRAGMENT_ROOT:
					int flags= getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null);
					switch (type) {
						case IJavaElement.PACKAGE_FRAGMENT_ROOT:
							IPackageFragmentRoot root= (IPackageFragmentRoot) element;
							if (flags != ERRORTICK_ERROR && root.getKind() == IPackageFragmentRoot.K_SOURCE && isIgnoringOptionalProblems(root.getRawClasspathEntry())) {
								flags= ERRORTICK_IGNORE_OPTIONAL_PROBLEMS;
							}
							break;
						case IJavaElement.JAVA_PROJECT:
							IJavaProject project= (IJavaProject) element;
							if (flags != ERRORTICK_ERROR && flags != ERRORTICK_BUILDPATH_ERROR && isIgnoringOptionalProblems(project)) {
								flags= ERRORTICK_IGNORE_OPTIONAL_PROBLEMS;
							}
							break;
					}
					return flags;
				case IJavaElement.PACKAGE_FRAGMENT:
					return getPackageErrorTicksFromMarkers((IPackageFragment) element);
				case IJavaElement.COMPILATION_UNIT:
				case IJavaElement.CLASS_FILE:
					return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null);
				case IJavaElement.PACKAGE_DECLARATION:
				case IJavaElement.IMPORT_DECLARATION:
				case IJavaElement.IMPORT_CONTAINER:
				case IJavaElement.TYPE:
				case IJavaElement.INITIALIZER:
				case IJavaElement.METHOD:
				case IJavaElement.FIELD:
				case IJavaElement.LOCAL_VARIABLE:
					ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
					if (cu != null) {
						ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element;
						// The assumption is that only source elements in compilation unit can have markers
						IAnnotationModel model= isInJavaAnnotationModel(cu);
						int result= 0;
						if (model != null) {
							// open in Java editor: look at annotation model
							result= getErrorTicksFromAnnotationModel(model, ref);
						} else {
							result= getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref);
						}
						fCachedRange= null;
						return result;
					}
					break;
				default:
			}
		} else if (obj instanceof IResource) {
			return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
		}
	} catch (CoreException e) {
		if (e instanceof JavaModelException) {
			if (((JavaModelException) e).isDoesNotExist()) {
				return 0;
			}
		}
		if (e.getStatus().getCode() == IResourceStatus.MARKER_NOT_FOUND) {
			return 0;
		}

		JavaPlugin.log(e);
	}
	return 0;
}
 
Example 19
Source File: BinaryRefactoringHistoryWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Checks whether the archive referenced by the package fragment root is not
 * shared with multiple java projects in the workspace.
 *
 * @param root
 *            the package fragment root
 * @param monitor
 *            the progress monitor to use
 * @return the status of the operation
 */
private static RefactoringStatus checkPackageFragmentRoots(final IPackageFragmentRoot root, final IProgressMonitor monitor) {
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, 100);
		final IWorkspaceRoot workspace= ResourcesPlugin.getWorkspace().getRoot();
		if (workspace != null) {
			final IJavaModel model= JavaCore.create(workspace);
			if (model != null) {
				try {
					final URI uri= getLocationURI(root.getRawClasspathEntry());
					if (uri != null) {
						final IJavaProject[] projects= model.getJavaProjects();
						final IProgressMonitor subMonitor= new SubProgressMonitor(monitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
						try {
							subMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, projects.length * 100);
							for (int index= 0; index < projects.length; index++) {
								final IPackageFragmentRoot[] roots= projects[index].getPackageFragmentRoots();
								final IProgressMonitor subsubMonitor= new SubProgressMonitor(subMonitor, 100, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL);
								try {
									subsubMonitor.beginTask(JarImportMessages.JarImportWizard_prepare_import, roots.length);
									for (int offset= 0; offset < roots.length; offset++) {
										final IPackageFragmentRoot current= roots[offset];
										if (!current.equals(root) && current.getKind() == IPackageFragmentRoot.K_BINARY) {
											final IClasspathEntry entry= current.getRawClasspathEntry();
											if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
												final URI location= getLocationURI(entry);
												if (uri.equals(location))
													status.addFatalError(Messages.format(JarImportMessages.JarImportWizard_error_shared_jar, new String[] { JavaElementLabels.getElementLabel(current.getJavaProject(), JavaElementLabels.ALL_DEFAULT) }));
											}
										}
										subsubMonitor.worked(1);
									}
								} finally {
									subsubMonitor.done();
								}
							}
						} finally {
							subMonitor.done();
						}
					}
				} catch (CoreException exception) {
					status.addError(exception.getLocalizedMessage());
				}
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 20
Source File: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public boolean doCheckUniqueInProject(QualifiedName name, JvmDeclaredType type) throws JavaModelException {
	IJavaProject javaProject = javaProjectProvider.getJavaProject(type.eResource().getResourceSet());
	getContext().put(ProjectAwareUniqueClassNameValidator.OUTPUT_CONFIGS,
			outputConfigurationProvider.getOutputConfigurations(type.eResource()));

	String packageName = type.getPackageName();
	String typeName = type.getSimpleName();
	IndexManager indexManager = JavaModelManager.getIndexManager();
	List<IPackageFragmentRoot> sourceFolders = new ArrayList<>();
	for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			sourceFolders.add(root);
		}
	}

	if (sourceFolders.isEmpty() || indexManager.awaitingJobsCount() > 0) {
		// still indexing - don't enter a busy wait loop but ask the source folders directly
		SourceTraversal sourceTraversal = doCheckUniqueInProjectSource(packageName != null ? packageName : "", typeName, type,
				sourceFolders);
		if (sourceTraversal == SourceTraversal.DUPLICATE) {
			return false;
		} else if (sourceTraversal == SourceTraversal.UNIQUE) {
			return true;
		}
	}

	Set<String> workingCopyPaths = new HashSet<>();
	ICompilationUnit[] copies = getWorkingCopies(type);
	if (copies != null) {
		for (ICompilationUnit workingCopy : copies) {
			IPath path = workingCopy.getPath();
			if (javaProject.getPath().isPrefixOf(path) && !isDerived(workingCopy.getResource())) {
				if (workingCopy.getPackageDeclaration(packageName).exists()) {
					IType result = workingCopy.getType(typeName);
					if (result.exists()) {
						addIssue(type, workingCopy.getElementName());
						return false;
					}
				}
				workingCopyPaths.add(workingCopy.getPath().toString());
			}
		}
	}

	// The code below is adapted from BasicSearchEnginge.searchAllSecondaryTypes
	// The Index is ready, query it for a secondary type 
	char[] pkg = packageName == null ? CharOperation.NO_CHAR : packageName.toCharArray();
	TypeDeclarationPattern pattern = new TypeDeclarationPattern(pkg, //
			CharOperation.NO_CHAR_CHAR, // top level type - no enclosing type names
			typeName.toCharArray(), //
			IIndexConstants.TYPE_SUFFIX, //
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {

		@Override
		public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant,
				AccessRuleSet access) {
			if (workingCopyPaths.contains(documentPath)) {
				return true; // filter out working copies
			}
			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(documentPath));
			if (!isDerived(file)) {
				addIssue(type, file.getName());
				return false;
			}
			return true;
		}
	};

	try {
		SearchParticipant searchParticipant = BasicSearchEngine.getDefaultSearchParticipant(); // Java search only
		IJavaSearchScope javaSearchScope = BasicSearchEngine.createJavaSearchScope(sourceFolders.toArray(new IJavaElement[0]));
		PatternSearchJob patternSearchJob = new PatternSearchJob(pattern, searchParticipant, javaSearchScope, searchRequestor);
		indexManager.performConcurrentJob(patternSearchJob, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
		return true;
	} catch (Throwable OperationCanceledException) {
		return false;
	}
}