org.eclipse.jdt.core.IClassFile Java Examples

The following examples show how to use org.eclipse.jdt.core.IClassFile. 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: CallHierarchyHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Gets the location of the Java {@code element} based on the desired
 * {@code locationType}.
 */
private Location getLocation(IJavaElement element, LocationType locationType) throws JavaModelException {
	Assert.isNotNull(element, "element");
	Assert.isNotNull(locationType, "locationType");

	Location location = locationType.toLocation(element);
	if (location == null && element instanceof IType) {
		IType type = (IType) element;
		ICompilationUnit unit = (ICompilationUnit) type.getAncestor(COMPILATION_UNIT);
		IClassFile classFile = (IClassFile) type.getAncestor(CLASS_FILE);
		if (unit != null || (classFile != null && classFile.getSourceRange() != null)) {
			location = locationType.toLocation(type);
		}
	}
	if (location == null && element instanceof IMember && ((IMember) element).getClassFile() != null) {
		location = JDTUtils.toLocation(((IMember) element).getClassFile());
	}
	return location;
}
 
Example #2
Source File: JavaEditorBreadcrumb.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the input for the given element. The Java breadcrumb does not show some elements of
 * the model:
 * <ul>
 * 		<li><code>ITypeRoots</li>
 * 		<li><code>IPackageDeclaration</li>
 * 		<li><code>IImportContainer</li>
 * 		<li><code>IImportDeclaration</li>
 * </ul>
 *
 * @param element the potential input element
 * @return the element to use as input
 */
private IJavaElement getInput(IJavaElement element) {
	try {
		if (element instanceof IImportDeclaration)
			element= element.getParent();

		if (element instanceof IImportContainer)
			element= element.getParent();

		if (element instanceof IPackageDeclaration)
			element= element.getParent();

		if (element instanceof ICompilationUnit) {
			IType[] types= ((ICompilationUnit) element).getTypes();
			if (types.length > 0)
				element= types[0];
		}

		if (element instanceof IClassFile)
			element= ((IClassFile) element).getType();

		return element;
	} catch (JavaModelException e) {
		return null;
	}
}
 
Example #3
Source File: JdtSourceLookUpProvider.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
private String getContents(IClassFile cf) {
    String source = null;
    if (cf != null) {
        try {
            IBuffer buffer = cf.getBuffer();
            if (buffer != null) {
                source = buffer.getContents();
            }
        } catch (JavaModelException e) {
            logger.log(Level.SEVERE, String.format("Failed to parse the source contents of the class file: %s", e.toString()), e);
        }
        if (source == null) {
            source = "";
        }
    }
    return source;
}
 
Example #4
Source File: LapseView.java    From lapse-plus with GNU General Public License v3.0 6 votes vote down vote up
private CompilationUnit internalSetInput(IOpenable input) throws CoreException {
	IBuffer buffer = input.getBuffer();
	if (buffer == null) {
		JavaPlugin.logErrorMessage("Input has no buffer"); //$NON-NLS-1$
	}
	if (input instanceof ICompilationUnit) {
		fParser.setSource((ICompilationUnit) input);
	} else {
		fParser.setSource((IClassFile) input);
	}

	try {
		CompilationUnit root = (CompilationUnit) fParser.createAST(null);
		log("Recomputed the AST for " + buffer.getUnderlyingResource().getName());
						
		if (root == null) {
			JavaPlugin.logErrorMessage("Could not create AST"); //$NON-NLS-1$
		}

		return root;
	} catch (RuntimeException e) {
		JavaPlugin.logErrorMessage("Could not create AST:\n" + e.getMessage()); //$NON-NLS-1$
		return null;
	}
}
 
Example #5
Source File: JdtSourceLookUpProvider.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public String getSourceFileURI(String fullyQualifiedName, String sourcePath) {
    if (sourcePath == null) {
        return null;
    }

    Object sourceElement = JdtUtils.findSourceElement(sourcePath, getSourceContainers());
    if (sourceElement instanceof IResource) {
        return getFileURI((IResource) sourceElement);
    } else if (sourceElement instanceof IClassFile) {
        try {
            IClassFile file = (IClassFile) sourceElement;
            if (file.getBuffer() != null) {
                return getFileURI(file);
            }
        } catch (JavaModelException e) {
            // do nothing.
        }
    }
    return null;
}
 
Example #6
Source File: MembersView.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Answers if the given <code>element</code> is a valid
 * element for this part.
 *
 * @param 	element	the object to test
 * @return	<true> if the given element is a valid element
 */
@Override
protected boolean isValidElement(Object element) {
	if (element instanceof IMember)
		return super.isValidElement(((IMember)element).getDeclaringType());
	else if (element instanceof IImportDeclaration)
		return isValidElement(((IJavaElement)element).getParent());
	else if (element instanceof IImportContainer) {
		Object input= getViewer().getInput();
		if (input instanceof IJavaElement) {
			ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
			if (cu != null) {
				ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT);
				return cu.equals(importContainerCu);
			} else {
				IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE);
				IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE);
				return cf != null && cf.equals(importContainerCf);
			}
		}
	}
	return false;
}
 
Example #7
Source File: AbstractJavaSearchResult.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public IFile getFile(Object element) {
	if (element instanceof IJavaElement) {
		IJavaElement javaElement= (IJavaElement) element;
		ICompilationUnit cu= (ICompilationUnit) javaElement.getAncestor(IJavaElement.COMPILATION_UNIT);
		if (cu != null) {
			return (IFile) cu.getResource();
		} else {
			IClassFile cf= (IClassFile) javaElement.getAncestor(IJavaElement.CLASS_FILE);
			if (cf != null)
				return (IFile) cf.getResource();
		}
		return null;
	}
	if (element instanceof IFile)
		return (IFile) element;
	return null;
}
 
Example #8
Source File: JavaElementResourceMapping.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ResourceMapping create(IJavaElement element) {
	switch (element.getElementType()) {
		case IJavaElement.TYPE:
			return create((IType)element);
		case IJavaElement.COMPILATION_UNIT:
			return create((ICompilationUnit)element);
		case IJavaElement.CLASS_FILE:
			return create((IClassFile)element);
		case IJavaElement.PACKAGE_FRAGMENT:
			return create((IPackageFragment)element);
		case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			return create((IPackageFragmentRoot)element);
		case IJavaElement.JAVA_PROJECT:
			return create((IJavaProject)element);
		case IJavaElement.JAVA_MODEL:
			return create((IJavaModel)element);
		default:
			return null;
	}

}
 
Example #9
Source File: ClassFileDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates an annotation model derived from the given class file editor input.
 *
 * @param classFileEditorInput the editor input from which to query the annotations
 * @return the created annotation model
 * @exception CoreException if the editor input could not be accessed
 */
protected IAnnotationModel createClassFileAnnotationModel(IClassFileEditorInput classFileEditorInput) throws CoreException {
	IResource resource= null;
	IClassFile classFile= classFileEditorInput.getClassFile();

	IResourceLocator locator= (IResourceLocator) classFile.getAdapter(IResourceLocator.class);
	if (locator != null)
		resource= locator.getContainingResource(classFile);

	if (resource != null) {
		ClassFileMarkerAnnotationModel model= new ClassFileMarkerAnnotationModel(resource);
		model.setClassFile(classFile);
		return model;
	}

	return null;
}
 
Example #10
Source File: GenericRefactoringHandleTransplanter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
protected IType transplantHandle(IJavaElement parent, IType element) {
	switch (parent.getElementType()) {
		case IJavaElement.COMPILATION_UNIT:
			return ((ICompilationUnit) parent).getType(element.getElementName());
		case IJavaElement.CLASS_FILE:
			return ((IClassFile) parent).getType();
		case IJavaElement.METHOD:
			return ((IMethod) parent).getType(element.getElementName(), element.getOccurrenceCount());
		case IJavaElement.FIELD:
			return ((IField) parent).getType(element.getElementName(), element.getOccurrenceCount());
		case IJavaElement.INITIALIZER:
			return ((IInitializer) parent).getType(element.getElementName(), element.getOccurrenceCount());
		case IJavaElement.TYPE:
			return ((IType) parent).getType(element.getElementName(), element.getOccurrenceCount());
		default:
			throw new IllegalStateException(element.toString());
	}
}
 
Example #11
Source File: JDClassFileEditor.java    From jd-eclipse with GNU General Public License v3.0 6 votes vote down vote up
protected static void cleanupBuffer(IClassFile file) {
	IBuffer buffer = BufferManager.getDefaultBufferManager().getBuffer(file);

	if (buffer != null) {
		try {
			// Remove the buffer
			Method method = BufferManager.class.getDeclaredMethod("removeBuffer", new Class[] {IBuffer.class});
			method.setAccessible(true);
			method.invoke(BufferManager.getDefaultBufferManager(), new Object[] {buffer});				
		} catch (Exception e) {
			JavaDecompilerPlugin.getDefault().getLog().log(new Status(
				Status.ERROR, JavaDecompilerPlugin.PLUGIN_ID, 
				0, e.getMessage(), e));
		}
	}
}
 
Example #12
Source File: HoverHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testHoverThrowable() throws Exception {
	String uriString = ClassFileUtil.getURI(project, "java.lang.Exception");
	IClassFile classFile = JDTUtils.resolveClassFile(uriString);
	String contents = JavaLanguageServerPlugin.getContentProviderManager().getSource(classFile, monitor);
	IDocument document = new Document(contents);
	IRegion region = new FindReplaceDocumentAdapter(document).find(0, "Throwable", true, false, false, false);
	int offset = region.getOffset();
	int line = document.getLineOfOffset(offset);
	int character = offset - document.getLineOffset(line);
	TextDocumentIdentifier textDocument = new TextDocumentIdentifier(uriString);
	Position position = new Position(line, character);
	TextDocumentPositionParams params = new TextDocumentPositionParams(textDocument, position);
	Hover hover = handler.hover(params, monitor);
	assertNotNull(hover);
	assertTrue("Unexpected hover ", !hover.getContents().getLeft().isEmpty());
}
 
Example #13
Source File: FindOccurrencesInFileAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IMember getMember(IStructuredSelection selection) {
	if (selection.size() != 1)
		return null;
	Object o= selection.getFirstElement();
	if (o instanceof IMember) {
		IMember member= (IMember)o;
		try {
			if (member.getNameRange() == null)
				return null;
		} catch (JavaModelException ex) {
			return null;
		}

		IClassFile file= member.getClassFile();
		if (file != null) {
			try {
				if (file.getSourceRange() != null)
					return member;
			} catch (JavaModelException e) {
				return null;
			}
		}
		return member;
	}
	return null;
}
 
Example #14
Source File: MavenBuildSupportTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDownloadSources() throws Exception {
	File file = DependencyUtil.getSources("org.apache.commons", "commons-lang3", "3.5");
	FileUtils.deleteDirectory(file.getParentFile());
	boolean mavenDownloadSources = preferences.isMavenDownloadSources();
	try {
		preferences.setMavenDownloadSources(false);
		IProject project = importMavenProject("salut");
		waitForBackgroundJobs();
		assertTrue(!file.exists());
		IJavaProject javaProject = JavaCore.create(project);
		IType type = javaProject.findType("org.apache.commons.lang3.StringUtils");
		IClassFile classFile = ((BinaryType) type).getClassFile();
		assertNull(classFile.getBuffer());
		String source = new SourceContentProvider().getSource(classFile, new NullProgressMonitor());
		if (source == null) {
			JobHelpers.waitForDownloadSourcesJobs(JobHelpers.MAX_TIME_MILLIS);
			source = new SourceContentProvider().getSource(classFile, new NullProgressMonitor());
		}
		assertNotNull("Couldn't find source for " + type.getFullyQualifiedName() + "(" + file.getAbsolutePath() + (file.exists() ? " exists)" : " is missing)"), source);
	} finally {
		preferences.setMavenDownloadSources(mavenDownloadSources);
	}
}
 
Example #15
Source File: NavigateToDefinitionHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Location fixLocation(IJavaElement element, Location location, IJavaProject javaProject) {
	if (location == null) {
		return null;
	}
	if (!javaProject.equals(element.getJavaProject()) && element.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		// see issue at: https://github.com/eclipse/eclipse.jdt.ls/issues/842 and https://bugs.eclipse.org/bugs/show_bug.cgi?id=541573
		// for jdk classes, jdt will reuse the java model by altering project to share the model between projects
		// so that sometimes the project for `element` is default project and the project is different from the project for `unit`
		// this fix is to replace the project name with non-default ones since default project should be transparent to users.
		if (location.getUri().contains(ProjectsManager.DEFAULT_PROJECT_NAME)) {
			String patched = StringUtils.replaceOnce(location.getUri(), ProjectsManager.DEFAULT_PROJECT_NAME, javaProject.getProject().getName());
			try {
				IClassFile cf = (IClassFile) JavaCore.create(JDTUtils.toURI(patched).getQuery());
				if (cf != null && cf.exists()) {
					location.setUri(patched);
				}
			} catch (Exception ex) {

			}
		}
	}
	return location;
}
 
Example #16
Source File: JarPackageWizard.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void addJavaElement(List<Object> selectedElements, IJavaElement je) {
	if (je.getElementType() == IJavaElement.COMPILATION_UNIT)
		selectedElements.add(je);
	else if (je.getElementType() == IJavaElement.CLASS_FILE)
		selectedElements.add(je);
	else if (je.getElementType() == IJavaElement.JAVA_PROJECT)
		selectedElements.add(je);
	else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
		if (!isInArchiveOrExternal(je))
			selectedElements.add(je);
	} else if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
		if (!isInArchiveOrExternal(je))
			selectedElements.add(je);
	} else {
		IOpenable openable= je.getOpenable();
		if (openable instanceof ICompilationUnit)
			selectedElements.add(((ICompilationUnit) openable).getPrimary());
		else if (openable instanceof IClassFile && !isInArchiveOrExternal(je))
			selectedElements.add(openable);
	}
}
 
Example #17
Source File: CollectingSearchRequestor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static boolean isBinaryElement(Object element) throws JavaModelException {
	if (element instanceof IMember) {
		return ((IMember)element).isBinary();

	} else if (element instanceof ICompilationUnit) {
		return true;

	} else if (element instanceof IClassFile) {
		return false;

	} else if (element instanceof IPackageFragment) {
		return isBinaryElement(((IPackageFragment) element).getParent());

	} else if (element instanceof IPackageFragmentRoot) {
		return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_BINARY;

	}
	return false;

}
 
Example #18
Source File: JavaBrowsingContentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
	ISourceReference[] sourceRefs;
	if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
		sourceRefs= fragment.getCompilationUnits();
	}
	else {
		IClassFile[] classFiles= fragment.getClassFiles();
		List<IClassFile> topLevelClassFile= new ArrayList<IClassFile>();
		for (int i= 0; i < classFiles.length; i++) {
			IType type= classFiles[i].getType();
			if (type != null && type.getDeclaringType() == null && !type.isAnonymous() && !type.isLocal())
				topLevelClassFile.add(classFiles[i]);
		}
		sourceRefs= topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
	}

	Object[] result= new Object[0];
	for (int i= 0; i < sourceRefs.length; i++)
		result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
	return concatenate(result, fragment.getNonJavaResources());
}
 
Example #19
Source File: JavaElementLabelComposer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Appends the label for a class file. Considers the CF_* flags.
 *
 * @param classFile the element to render
 * @param flags the rendering flags. Flags with names starting with 'CF_' are considered.
 */
public void appendClassFileLabel(IClassFile classFile, long flags) {
	if (getFlag(flags, JavaElementLabels.CF_QUALIFIED)) {
		IPackageFragment pack= (IPackageFragment) classFile.getParent();
		if (!pack.isDefaultPackage()) {
			appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
			fBuilder.append('.');
		}
	}
	fBuilder.append(classFile.getElementName());

	if (getFlag(flags, JavaElementLabels.CF_POST_QUALIFIED)) {
		fBuilder.append(JavaElementLabels.CONCAT_STRING);
		appendPackageFragmentLabel((IPackageFragment) classFile.getParent(), flags & QUALIFIER_FLAGS);
	}
}
 
Example #20
Source File: RegionBasedHierarchyBuilder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Adds all of the openables defined within this package fragment to the
 * list.
 */
private void injectAllOpenablesForPackageFragment(
	IPackageFragment packFrag,
	ArrayList openables) {

	try {
		IPackageFragmentRoot root = (IPackageFragmentRoot) packFrag.getParent();
		int kind = root.getKind();
		if (kind != 0) {
			boolean isSourcePackageFragment = (kind == IPackageFragmentRoot.K_SOURCE);
			if (isSourcePackageFragment) {
				ICompilationUnit[] cus = packFrag.getCompilationUnits();
				for (int i = 0, length = cus.length; i < length; i++) {
					openables.add(cus[i]);
				}
			} else {
				IClassFile[] classFiles = packFrag.getClassFiles();
				for (int i = 0, length = classFiles.length; i < length; i++) {
					openables.add(classFiles[i]);
				}
			}
		}
	} catch (JavaModelException e) {
		// ignore
	}
}
 
Example #21
Source File: OccurrencesSearchResult.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Match[] computeContainedMatches(AbstractTextSearchResult result, IEditorPart editor) {
	//TODO same code in JavaSearchResult
	IEditorInput editorInput= editor.getEditorInput();
	if (editorInput instanceof IFileEditorInput)  {
		IFileEditorInput fileEditorInput= (IFileEditorInput) editorInput;
		return computeContainedMatches(result, fileEditorInput.getFile());

	} else if (editorInput instanceof IClassFileEditorInput) {
		IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) editorInput;
		IClassFile classFile= classFileEditorInput.getClassFile();

		Object[] elements= getElements();
		if (elements.length == 0)
			return NO_MATCHES;
		//all matches from same file:
		JavaElementLine jel= (JavaElementLine) elements[0];
		if (jel.getJavaElement().equals(classFile))
			return collectMatches(elements);
	}
	return NO_MATCHES;
}
 
Example #22
Source File: SourceContentProvider.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public String getSource(IClassFile classFile, IProgressMonitor monitor) throws CoreException {
	String source = null;
	try {
		IBuffer buffer = classFile.getBuffer();
		if (buffer == null) {
			ProjectsManager projectsManager = JavaLanguageServerPlugin.getProjectsManager();
			if (projectsManager != null) {
				Optional<IBuildSupport> bs = projectsManager.getBuildSupport(classFile.getJavaProject().getProject());
				if (bs.isPresent()) {
					bs.get().discoverSource(classFile, monitor);
				}
			}
			buffer = classFile.getBuffer();
		}
		if (buffer != null) {
			source = buffer.getContents();
			JavaLanguageServerPlugin.logInfo("ClassFile contents request completed");
		}
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.logException("Exception getting java element ", e);
	}
	return source;
}
 
Example #23
Source File: JavaEditorBreadcrumb.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Object[] getPackageContent(IPackageFragment pack) {
	ArrayList<Object> result= new ArrayList<Object>();
	try {
		ICompilationUnit[] units= pack.getCompilationUnits();
		for (int i= 0; i < units.length; i++) {
			if (JavaModelUtil.isPackageInfo(units[i]))
				result.add(units[i]);
			IType[] types= units[i].getTypes();
			for (int j= 0; j < types.length; j++) {
				if (isValidType(types[j]))
					result.add(types[j]);
			}
		}

		IClassFile[] classFiles= pack.getClassFiles();
		for (int i= 0; i < classFiles.length; i++) {
			if (isValidType(classFiles[i].getType()))
				result.add(classFiles[i].getType());
		}

		Object[] nonJavaResources= pack.getNonJavaResources();
		for (int i= 0; i < nonJavaResources.length; i++) {
			result.add(nonJavaResources[i]);
		}
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}

	return result.toArray();
}
 
Example #24
Source File: PackageFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see IPackageFragment#getClassFile(String)
 * @exception IllegalArgumentException if the name does not end with ".class"
 */
public IClassFile getClassFile(String classFileName) {
	if (!org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(classFileName)) {
		throw new IllegalArgumentException(Messages.bind(Messages.element_invalidClassFileName, classFileName));
	}
	// don't hold on the .class file extension to save memory
	// also make sure to not use substring as the resulting String may hold on the underlying char[] which might be much bigger than necessary
	int length = classFileName.length() - 6;
	char[] nameWithoutExtension = new char[length];
	classFileName.getChars(0, length, nameWithoutExtension, 0);
	return new ClassFile(this, new String(nameWithoutExtension));
}
 
Example #25
Source File: BonitaProjectExplorer.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected boolean evaluateExpandableWithFilters(Object parent) {
    if (parent instanceof IJavaProject || parent instanceof ICompilationUnit || parent instanceof IClassFile
            || parent instanceof ClassPathContainer) {
        return false;
    }
    if (parent instanceof IPackageFragmentRoot && ((IPackageFragmentRoot) parent).isArchive()) {
        return false;
    }
    return true;
}
 
Example #26
Source File: SourceAttachmentCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateSourceAttachmentFromProjectJar() throws Exception {
	IResource source = project.findMember("foo-sources.jar");
	assertNotNull(source);
	IPath sourcePath = source.getLocation();
	SourceAttachmentAttribute attributes = new SourceAttachmentAttribute(null, sourcePath.toOSString(), "UTF-8");
	SourceAttachmentRequest request = new SourceAttachmentRequest(classFileUri, attributes);
	String arguments = new Gson().toJson(request, SourceAttachmentRequest.class);
	SourceAttachmentResult updateResult = SourceAttachmentCommand.updateSourceAttachment(Arrays.asList(arguments), new NullProgressMonitor());
	assertNotNull(updateResult);
	assertNull(updateResult.errorMessage);

	// Verify the source is attached to the classfile.
	IClassFile classfile = JDTUtils.resolveClassFile(classFileUri);
	IBuffer buffer = classfile.getBuffer();
	assertNotNull(buffer);
	assertTrue(buffer.getContents().indexOf("return sum;") >= 0);

	// Verify whether project inside jar attachment is saved with project relative path.
	IJavaProject javaProject = JavaCore.create(project);
	IPath relativePath = source.getFullPath();
	IPath absolutePath = source.getLocation();
	for (IClasspathEntry entry : javaProject.getRawClasspath()) {
		if (Objects.equals("foo.jar", entry.getPath().lastSegment())) {
			assertNotNull(entry.getSourceAttachmentPath());
			assertEquals(relativePath, entry.getSourceAttachmentPath());
			assertNotEquals(absolutePath, entry.getSourceAttachmentPath());
			break;
		}
	}
}
 
Example #27
Source File: FindAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IJavaElement getTypeIfPossible(IJavaElement o, boolean silent) {
	switch (o.getElementType()) {
		case IJavaElement.COMPILATION_UNIT:
			if (silent)
				return o;
			else
				return findType((ICompilationUnit)o, silent);
		case IJavaElement.CLASS_FILE:
			return ((IClassFile)o).getType();
		default:
			return o;
	}
}
 
Example #28
Source File: StubCreationOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Runs the stub generation on the specified class file.
 *
 * @param file
 *            the class file
 * @param parent
 *            the parent store
 * @param monitor
 *            the progress monitor to use
 * @throws CoreException
 *             if an error occurs
 */
@Override
protected void run(final IClassFile file, final IFileStore parent, final IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask(RefactoringCoreMessages.StubCreationOperation_creating_type_stubs, 2);
		SubProgressMonitor subProgressMonitor= new SubProgressMonitor(monitor, 1);
		final IType type= file.getType();
		if (type.isAnonymous() || type.isLocal() || type.isMember())
			return;
		String source= new StubCreator(fStubInvisible).createStub(type, subProgressMonitor);
		createCompilationUnit(parent, type.getElementName() + JavaModelUtil.DEFAULT_CU_SUFFIX, source, monitor);
	} finally {
		monitor.done();
	}
}
 
Example #29
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static String toUri(IClassFile classFile) {
	if (JavaLanguageServerPlugin.getPreferencesManager() != null && !JavaLanguageServerPlugin.getPreferencesManager().isClientSupportsClassFileContent()) {
		return null;
	}

	String packageName = classFile.getParent().getElementName();
	String jarName = classFile.getParent().getParent().getElementName();
	String uriString = null;
	try {
		uriString = new URI(JDT_SCHEME, "contents", PATH_SEPARATOR + jarName + PATH_SEPARATOR + packageName + PATH_SEPARATOR + classFile.getElementName(), classFile.getHandleIdentifier(), null).toASCIIString();
	} catch (URISyntaxException e) {
		JavaLanguageServerPlugin.logException("Error generating URI for class ", e);
	}
	return uriString;
}
 
Example #30
Source File: SourceAttachmentCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateSourceAttachment_EmptySourceAttachmentPath() throws Exception {
	SourceAttachmentAttribute attributes = new SourceAttachmentAttribute(null, null, "UTF-8");
	SourceAttachmentRequest request = new SourceAttachmentRequest(classFileUri, attributes);
	String arguments = new Gson().toJson(request, SourceAttachmentRequest.class);
	SourceAttachmentResult updateResult = SourceAttachmentCommand.updateSourceAttachment(Arrays.asList(arguments), new NullProgressMonitor());
	assertNotNull(updateResult);
	assertNull(updateResult.errorMessage);

	// Verify no source is attached to the classfile.
	IClassFile classfile = JDTUtils.resolveClassFile(classFileUri);
	IBuffer buffer = classfile.getBuffer();
	assertNull(buffer);
}