Java Code Examples for org.eclipse.jdt.core.IJavaElement#getResource()

The following examples show how to use org.eclipse.jdt.core.IJavaElement#getResource() . 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: JavaEditorErrorTickUpdater.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) {
	if (!isMarkerChange)
		return;

	IEditorInput input= fJavaEditor.getEditorInput();
	if (input != null) { // might run async, tests needed
		IJavaElement jelement= (IJavaElement) input.getAdapter(IJavaElement.class);
		if (jelement != null) {
			IResource resource= jelement.getResource();
			for (int i = 0; i < changedResources.length; i++) {
				if (changedResources[i].equals(resource)) {
					updateEditorImage(jelement);
				}
			}
		}
	}
}
 
Example 2
Source File: JavaElementContainmentAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private boolean contains(IJavaElement workingSetElement, IResource element, int flags) {
	IResource workingSetResource= workingSetElement.getResource();
	if (workingSetResource == null)
		return false;
	if (checkContext(flags) && workingSetResource.equals(element)) {
		return true;
	}
	if (checkIfChild(flags) && workingSetResource.equals(element.getParent())) {
		return true;
	}
	if (checkIfDescendant(flags) && check(workingSetResource, element)) {
		return true;
	}
	if (checkIfAncestor(flags) && check(element, workingSetResource)) {
		return true;
	}
	return false;
}
 
Example 3
Source File: RefactoringModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
protected IResource[] collectResourcesOfInterest(IPackageFragment source) throws CoreException {
	IJavaElement[] children = source.getChildren();
	int childOfInterest = IJavaElement.COMPILATION_UNIT;
	if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
		childOfInterest = IJavaElement.CLASS_FILE;
	}
	ArrayList<IResource> result = new ArrayList<>(children.length);
	for (int i = 0; i < children.length; i++) {
		IJavaElement child = children[i];
		if (child.getElementType() == childOfInterest && child.getResource() != null) {
			result.add(child.getResource());
		}
	}
	// Gather non-java resources
	Object[] nonJavaResources = source.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object element= nonJavaResources[i];
		if (element instanceof IResource) {
			result.add((IResource) element);
		}
	}
	return result.toArray(new IResource[result.size()]);
}
 
Example 4
Source File: NewEntryPointWizardPage.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void init(IStructuredSelection selection) {
  IJavaElement initialJavaElement = getInitialJavaElement(selection);
  initContainerPage(initialJavaElement);
  initTypePage(initialJavaElement);

  // Set the initial resource, based either on the selection or on the
  // initial Java element returned by NewContainerWizardPage
  IResource initialResource = AbstractNewFileWizard.getSelectedResource(selection);
  if (initialResource.getType() == IResource.ROOT
      && initialJavaElement != null) {
    initialResource = initialJavaElement.getResource();
  }

  initEntryPointPage(initialResource);
  doStatusUpdate();

  setMethodStubSelection(false, true);
}
 
Example 5
Source File: RefactoringAvailabilityTester.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static boolean isDeleteAvailable(final IJavaElement element) {
	if (!element.exists())
		return false;
	if (element instanceof IJavaModel || element instanceof IJavaProject)
		return false;
	if (element.getParent() != null && element.getParent().isReadOnly())
		return false;
	if (element instanceof IPackageFragmentRoot) {
		IPackageFragmentRoot root= (IPackageFragmentRoot) element;
		if (root.isExternal() || Checks.isClasspathDelete(root)) // TODO: rename isClasspathDelete
			return false;

		if (root.getResource().equals(root.getJavaProject().getProject()))
			return false;
	}
	if (element.getResource() == null && !RefactoringAvailabilityTester.isWorkingCopyElement(element))
		return false;
	if (element instanceof IMember && ((IMember) element).isBinary())
		return false;
	return true;
}
 
Example 6
Source File: RefactoringModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IResource[] collectResourcesOfInterest(IPackageFragment source) throws CoreException {
	IJavaElement[] children = source.getChildren();
	int childOfInterest = IJavaElement.COMPILATION_UNIT;
	if (source.getKind() == IPackageFragmentRoot.K_BINARY) {
		childOfInterest = IJavaElement.CLASS_FILE;
	}
	ArrayList<IResource> result = new ArrayList<IResource>(children.length);
	for (int i = 0; i < children.length; i++) {
		IJavaElement child = children[i];
		if (child.getElementType() == childOfInterest && child.getResource() != null) {
			result.add(child.getResource());
		}
	}
	// Gather non-java resources
	Object[] nonJavaResources = source.getNonJavaResources();
	for (int i= 0; i < nonJavaResources.length; i++) {
		Object element= nonJavaResources[i];
		if (element instanceof IResource) {
			result.add((IResource) element);
		}
	}
	return result.toArray(new IResource[result.size()]);
}
 
Example 7
Source File: DeleteModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void delete(IJavaElement element) throws CoreException {
	switch(element.getElementType()) {
		case IJavaElement.JAVA_MODEL:
			return;
		case IJavaElement.JAVA_PROJECT:
			fDelete.add(element);
			if (element.getResource() != null)
				getResourceModifications().addDelete(element.getResource());
			return;
		case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			fDelete.add(element);
			IResource resource= element.getResource();
			// Flag an resource change even if we have an archive. If it is
			// internal (we have a underlying resource then we have a resource
			// change.
			if (resource != null)
				getResourceModifications().addDelete(resource);
			IJavaProject[] referencingProjects= JavaElementUtil.getReferencingProjects((IPackageFragmentRoot) element);
			for (int i= 0; i < referencingProjects.length; i++) {
				IFile classpath= referencingProjects[i].getProject().getFile(".classpath"); //$NON-NLS-1$
				getResourceModifications().addChanged(classpath);
			}
			return;
		case IJavaElement.PACKAGE_FRAGMENT:
			fDelete.add(element);
			fPackagesToDelete.add((IPackageFragment) element);
			return;
		case IJavaElement.COMPILATION_UNIT:
			fDelete.add(element);
			IType[] types= ((ICompilationUnit)element).getTypes();
			fDelete.addAll(Arrays.asList(types));
			if (element.getResource() != null)
				getResourceModifications().addDelete(element.getResource());
			return;
		default:
			fDelete.add(element);
	}

}
 
Example 8
Source File: JavaElementAdapterFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IResource getResource(IJavaElement element) {
// can't use IJavaElement.getResource directly as we are interested in the
// corresponding resource
switch (element.getElementType()) {
	case IJavaElement.TYPE:
		// top level types behave like the CU
		IJavaElement parent= element.getParent();
		if (parent instanceof ICompilationUnit) {
			return ((ICompilationUnit) parent).getPrimary().getResource();
		}
		return null;
	case IJavaElement.COMPILATION_UNIT:
		return ((ICompilationUnit) element).getPrimary().getResource();
	case IJavaElement.CLASS_FILE:
	case IJavaElement.PACKAGE_FRAGMENT:
		// test if in a archive
		IPackageFragmentRoot root= (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
		if (!root.isArchive() && !root.isExternal()) {
			return element.getResource();
		}
		return null;
	case IJavaElement.PACKAGE_FRAGMENT_ROOT:
	case IJavaElement.JAVA_PROJECT:
	case IJavaElement.JAVA_MODEL:
		return element.getResource();
	default:
		return null;
}
  }
 
Example 9
Source File: JavaDocLocations.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns the location of the Javadoc.
 * 
 * @param element whose Javadoc location has to be found
 * @param isBinary <code>true</code> if the Java element is from a binary container
 * @return the location URL of the Javadoc or <code>null</code> if the location cannot be found
 * @throws JavaModelException thrown when the Java element cannot be accessed
 * @since 3.9
 */
public static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException {
	if (isBinary) {
		// Source attachment usually does not include Javadoc resources
		// => Always use the Javadoc location as base:
		URL baseURL= JavaUI.getJavadocLocation(element, false);
		if (baseURL != null) {
			if (baseURL.getProtocol().equals(JAR_PROTOCOL)) {
				// It's a JarURLConnection, which is not known to the browser widget.
				// Let's start the help web server:
				URL baseURL2= PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true);
				if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
					baseURL= baseURL2;
				}
			}
			return baseURL.toExternalForm();
		}
	} else {
		IResource resource= element.getResource();
		if (resource != null) {
			/*
			 * Too bad: Browser widget knows nothing about EFS and custom URL handlers,
			 * so IResource#getLocationURI() does not work in all cases.
			 * We only support the local file system for now.
			 * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
			 */
			IPath location= resource.getLocation();
			if (location != null)
				return location.toFile().toURI().toString();
		}
	}
	return null;
}
 
Example 10
Source File: DeleteSourceManipulationChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected IResource getModifiedResource() {
	IJavaElement elem= JavaCore.create(fHandle);
	if (elem != null) {
		return elem.getResource();
	}
	return null;
}
 
Example 11
Source File: JavaTaskListAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public IResource getAffectedResource(IAdaptable element) {
IJavaElement java = (IJavaElement) element;
IResource resource= java.getResource();
if (resource != null)
	return resource;

ICompilationUnit cu= (ICompilationUnit) java.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
	return cu.getPrimary().getResource();
}
return null;
}
 
Example 12
Source File: ResolveClasspathsHandler.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Accord to the project name and the main class, compute runtime classpath.
 *
 * @param mainClass
 *            fully qualified class name
 * @param projectName
 *            project name
 * @return class path
 * @throws CoreException
 *             CoreException
 */
private static String[][] computeClassPath(String mainClass, String projectName) throws CoreException {
    IJavaProject project = null;
    // if type exists in multiple projects, debug configuration need provide
    // project name.
    if (StringUtils.isNotBlank(projectName)) {
        project = getJavaProjectFromName(projectName);
    } else {
        List<IJavaProject> projects = getJavaProjectFromType(mainClass);
        if (projects.size() == 0) {
            throw new CoreException(new Status(IStatus.ERROR, JavaDebuggerServerPlugin.PLUGIN_ID,
                    String.format("Main class '%s' doesn't exist in the workspace.", mainClass)));
        }
        if (projects.size() > 1) {
            throw new CoreException(new Status(IStatus.ERROR, JavaDebuggerServerPlugin.PLUGIN_ID,
                    String.format(
                            "Main class '%s' isn't unique in the workspace, please pass in specified projectname.",
                            mainClass)));
        }
        project = projects.get(0);
    }

    IJavaElement testElement = findMainClassInTestFolders(project, mainClass);
    List<IResource> mappedResources = (testElement != null && testElement.getResource() != null)
            ? Arrays.asList(testElement.getResource()) : Collections.EMPTY_LIST;
    return computeClassPath(project, mainClass, testElement == null, mappedResources);
}
 
Example 13
Source File: JavaDocLocations.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the location of the Javadoc.
 *
 * @param element
 *            whose Javadoc location has to be found
 * @param isBinary
 *            <code>true</code> if the Java element is from a binary container
 * @return the location URL of the Javadoc or <code>null</code> if the location
 *         cannot be found
 * @throws JavaModelException
 *             thrown when the Java element cannot be accessed
 * @since 3.9
 */
public static String getBaseURL(IJavaElement element, boolean isBinary) throws JavaModelException {
	if (isBinary) {
		// Source attachment usually does not include Javadoc resources
		// => Always use the Javadoc location as base:
		URL baseURL = JavaDocLocations.getJavadocLocation(element, false);
		if (baseURL != null) {
			if (baseURL.getProtocol().equals(JAR_PROTOCOL)) {
				// It's a JarURLConnection, which is not known to the browser widget.
				// Let's start the help web server:
				//					URL baseURL2 = PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true);
				//					if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
				//						baseURL = baseURL2;
				//					}
			}
			return baseURL.toExternalForm();
		}
	} else {
		IResource resource = element.getResource();
		if (resource != null) {
			/*
			 * Too bad: Browser widget knows nothing about EFS and custom URL handlers,
			 * so IResource#getLocationURI() does not work in all cases.
			 * We only support the local file system for now.
			 * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
			 */
			IPath location = resource.getLocation();
			if (location != null) {
				return location.toFile().toURI().toString();
			}
		}
	}
	return null;
}
 
Example 14
Source File: DeleteSourceManipulationChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected IResource getModifiedResource() {
	IJavaElement elem= JavaCore.create(fHandle);
	if (elem != null) {
		return elem.getResource();
	}
	return null;
}
 
Example 15
Source File: BasicCompilationUnit.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void initEncoding(IJavaElement javaElement) {
	if (javaElement != null) {
		try {
			IJavaProject javaProject = javaElement.getJavaProject();
			switch (javaElement.getElementType()) {
				case IJavaElement.COMPILATION_UNIT:
					IFile file = (IFile) javaElement.getResource();
					if (file != null) {
						this.encoding = file.getCharset();
						break;
					}
					// if no file, then get project encoding
					// $FALL-THROUGH$
				default:
					IProject project = (IProject) javaProject.getResource();
					if (project != null) {
						this.encoding = project.getDefaultCharset();
					}
					break;
			}
		} catch (CoreException e1) {
			this.encoding = null;
		}
	} else  {
		this.encoding = null;
	}
}
 
Example 16
Source File: ReorgUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static IResource getResource(IJavaElement element){
	if (element instanceof ICompilationUnit) {
		return ((ICompilationUnit)element).getPrimary().getResource();
	} else {
		return element.getResource();
	}
}
 
Example 17
Source File: RefactoringAvailabilityTester.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static boolean isDeleteAvailable(final IJavaElement element) {
	if (!element.exists()) {
		return false;
	}
	if (element instanceof IJavaModel || element instanceof IJavaProject) {
		return false;
	}
	if (element.getParent() != null && element.getParent().isReadOnly()) {
		return false;
	}
	if (element instanceof IPackageFragmentRoot) {
		IPackageFragmentRoot root = (IPackageFragmentRoot) element;
		if (root.isExternal() || Checks.isClasspathDelete(root)) {
			return false;
		}

		if (root.getResource().equals(root.getJavaProject().getProject())) {
			return false;
		}
	}
	if (element instanceof IPackageFragment && ((IPackageFragment) element).isDefaultPackage()) {
		return false;
	}
	if (element.getResource() == null && !RefactoringAvailabilityTester.isWorkingCopyElement(element)) {
		return false;
	}
	if (element instanceof IMember && ((IMember) element).isBinary()) {
		return false;
	}
	return true;
}
 
Example 18
Source File: JvmOutlineNodeElementOpener.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void openEObject(EObject state) {
	try {
		if (state instanceof JvmIdentifiableElement && state.eResource() instanceof TypeResource) {
			IJavaElement javaElement = javaElementFinder.findElementFor((JvmIdentifiableElement) state);
			if (javaElement instanceof IMember) {
				IResource resource = javaElement.getResource();
				if (resource instanceof IStorage) {
					ITrace traceToSource = traceInformation.getTraceToSource((IStorage) resource);
					if (traceToSource != null) {
						ISourceRange sourceRange = ((IMember) javaElement).getSourceRange();
						ILocationInResource sourceInformation = traceToSource.getBestAssociatedLocation(new TextRegion(sourceRange.getOffset(), sourceRange.getLength()));
						if (sourceInformation != null) {
							globalURIEditorOpener.open(sourceInformation.getAbsoluteResourceURI().getURI(), javaElement, true);
							return;
						}
					}
				}
				globalURIEditorOpener.open(null, javaElement, true);
				return;
			}
		}
	} catch (Exception exc) {
		LOG.error("Error opening java editor", exc);
	}
	super.openEObject(state);
}
 
Example 19
Source File: ReorgUtils.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static IResource getResource(IJavaElement element){
	if (element instanceof ICompilationUnit)
		return ((ICompilationUnit)element).getPrimary().getResource();
	else
		return element.getResource();
}
 
Example 20
Source File: JavaElementContainmentAdapter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private boolean isChild(IJavaElement workingSetElement, IResource element) {
	IResource resource= workingSetElement.getResource();
	if (resource == null)
		return false;
	return check(element, resource);
}