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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#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: ResourceToItemsMapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Method that decides which elements can have error markers
 * Returns null if an element can not have error markers.
 * @param element The input element
 * @return Returns the corresponding resource or null
 */
private static IResource getCorrespondingResource(Object element) {
	if (element instanceof IJavaElement) {
		IJavaElement elem= (IJavaElement) element;
		IResource res= elem.getResource();
		if (res == null) {
			ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
			if (cu != null) {
				// elements in compilation units are mapped to the underlying resource of the original cu
				res= cu.getResource();
			}
		}
		return res;
	} else if (element instanceof IResource) {
		return (IResource) element;
	}
	return null;
}
 
Example 2
Source File: DocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public ICompilationUnit handleOpen(DidOpenTextDocumentParams params) {
	ICompilationUnit unit = super.handleOpen(params);

	if (unit == null || unit.getResource() == null || unit.getResource().isDerived()) {
		return unit;
	}

	try {
		installSemanticHighlightings(unit);
	} catch (JavaModelException | BadPositionCategoryException e) {
		JavaLanguageServerPlugin.logException("Error while opening document. URI: " + params.getTextDocument().getUri(), e);
	}

	return unit;
}
 
Example 3
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 4
Source File: MoveModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
public void move(ICompilationUnit unit, MoveArguments args) throws CoreException {
	add(unit, args, null);
	IType[] types= unit.getTypes();
	for (int tt= 0; tt < types.length; tt++) {
		add(types[tt], args, null);
	}
	IResource resourceDestination= getResourceDestination(args);
	if (resourceDestination != null && unit.getResource() != null) {
		IResource parent= resourceDestination;
		while (!parent.exists()) {
			getResourceModifications().addCreate(parent);
			parent= parent.getParent();
		}

		getResourceModifications().addMove(unit.getResource(), new MoveArguments(resourceDestination, args.getUpdateReferences()));
	}
}
 
Example 5
Source File: WorkspaceEventsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void discardWorkingCopies(String parentUri) {
	IPath parentPath = ResourceUtils.filePathFromURI(parentUri);
	if (parentPath != null && !parentPath.lastSegment().endsWith(".java")) {
		ICompilationUnit[] workingCopies = JavaCore.getWorkingCopies(null);
		for (ICompilationUnit workingCopy : workingCopies) {
			IResource resource = workingCopy.getResource();
			if (resource == null) {
				continue;
			}

			IPath cuPath = resource.getRawLocation() != null ? resource.getRawLocation() : resource.getLocation();
			if (cuPath != null && parentPath.isPrefixOf(cuPath)) {
				try {
					workingCopy.discardWorkingCopy();
				} catch (JavaModelException e) {
					// do nothing.
				}
			}
		}
	}
}
 
Example 6
Source File: RenameModifications.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void buildValidateEdits(ValidateEditChecker checker) {
	for (Iterator<Object> iter= fRename.iterator(); iter.hasNext();) {
		Object element= iter.next();
		if (element instanceof ICompilationUnit) {
			ICompilationUnit unit= (ICompilationUnit)element;
			IResource resource= unit.getResource();
			if (resource != null && resource.getType() == IResource.FILE) {
				checker.addFile((IFile)resource);
			}
		}
	}
}
 
Example 7
Source File: RefactoringFileBuffers.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Releases the text file buffer associated with the compilation unit.
 *
 * @param unit the compilation unit whose text file buffer has to be released
 * @throws CoreException if the buffer could not be successfully released
 */
public static void release(final ICompilationUnit unit) throws CoreException {
	Assert.isNotNull(unit);
	final IResource resource= unit.getResource();
	if (resource != null && resource.getType() == IResource.FILE) {
		FileBuffers.getTextFileBufferManager().disconnect(resource.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());
	}
}
 
Example 8
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Change moveCuToPackage(ICompilationUnit cu, IPackageFragment dest) {
	// XXX workaround for bug 31998 we will have to disable renaming of
	// linked packages (and cus)
	IResource resource= cu.getResource();
	if (resource != null && resource.isLinked()) {
		if (ResourceUtil.getResource(dest) instanceof IContainer)
			return moveFileToContainer(cu, (IContainer) ResourceUtil.getResource(dest));
	}
	return new MoveCompilationUnitChange(cu, dest);
}
 
Example 9
Source File: ResourceUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public static IFile getFile(ICompilationUnit cu) {
	IResource resource = cu.getResource();
	if (resource != null && resource.getType() == IResource.FILE) {
		return (IFile) resource;
	} else {
		return null;
	}
}
 
Example 10
Source File: CopyModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
public void copy(ICompilationUnit unit, CopyArguments javaArgs, CopyArguments resourceArgs) {
	add(unit, javaArgs, null);
	ResourceMapping mapping= JavaElementResourceMapping.create(unit);
	if (mapping != null) {
		add(mapping, resourceArgs, null);
	}
	if (unit.getResource() != null) {
		getResourceModifications().addCopyDelta(unit.getResource(), resourceArgs);
	}
}
 
Example 11
Source File: ProblemsLabelDecorator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private IAnnotationModel isInJavaAnnotationModel(ICompilationUnit original) {
	if (original.isWorkingCopy()) {
		FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource());
		return JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
	}
	return null;
}
 
Example 12
Source File: OpenTypeHistory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isContainerDirty(TypeNameMatch match) {
	ICompilationUnit cu= match.getType().getCompilationUnit();
	if (cu == null) {
		return false;
	}
	IResource resource= cu.getResource();
	ITextFileBufferManager manager= FileBuffers.getTextFileBufferManager();
	ITextFileBuffer textFileBuffer= manager.getTextFileBuffer(resource.getFullPath(), LocationKind.IFILE);
	if (textFileBuffer != null) {
		return textFileBuffer.isDirty();
	}
	return false;
}
 
Example 13
Source File: ASTReader.java    From JDeodorant with MIT License 5 votes vote down vote up
private List<ClassObject> parseAST(ICompilationUnit iCompilationUnit) {
	ASTInformationGenerator.setCurrentITypeRoot(iCompilationUnit);
	IFile iFile = (IFile)iCompilationUnit.getResource();
       ASTParser parser = ASTParser.newParser(JLS);
       parser.setKind(ASTParser.K_COMPILATION_UNIT);
       parser.setSource(iCompilationUnit);
       parser.setResolveBindings(true); // we need bindings later on
       CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
       
       return parseAST(compilationUnit, iFile);
}
 
Example 14
Source File: RefactoringFileBuffers.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Releases the text file buffer associated with the compilation unit.
 *
 * @param unit the compilation unit whose text file buffer has to be released
 * @throws CoreException if the buffer could not be successfully released
 */
public static void release(final ICompilationUnit unit) throws CoreException {
	Assert.isNotNull(unit);
	final IResource resource= unit.getResource();
	if (resource != null && resource.getType() == IResource.FILE)
		FileBuffers.getTextFileBufferManager().disconnect(resource.getFullPath(), LocationKind.IFILE, new NullProgressMonitor());
}
 
Example 15
Source File: BaseDocumentLifeCycleHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private ICompilationUnit checkPackageDeclaration(String uri, ICompilationUnit unit) {
	if (unit.getResource() != null && unit.getJavaProject() != null && unit.getJavaProject().getProject().getName().equals(ProjectsManager.DEFAULT_PROJECT_NAME)) {
		try {
			CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(unit, CoreASTProvider.WAIT_YES, new NullProgressMonitor());
			IProblem[] problems = astRoot.getProblems();
			for (IProblem problem : problems) {
				if (problem.getID() == IProblem.PackageIsNotExpectedPackage) {
					IResource file = unit.getResource();
					boolean toRemove = file.isLinked();
					if (toRemove) {
						IPath path = file.getParent().getProjectRelativePath();
						if (path.segmentCount() > 0 && JDTUtils.SRC.equals(path.segments()[0])) {
							String packageNameResource = path.removeFirstSegments(1).toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
							path = file.getLocation();
							if (path != null && path.segmentCount() > 0) {
								path = path.removeLastSegments(1);
								String pathStr = path.toString().replace(JDTUtils.PATH_SEPARATOR, JDTUtils.PERIOD);
								if (pathStr.endsWith(packageNameResource)) {
									toRemove = false;
								}
							}
						}
					}
					if (toRemove) {
						file.delete(true, new NullProgressMonitor());
						if (unit.equals(sharedASTProvider.getActiveJavaElement())) {
							sharedASTProvider.disposeAST();
						}
						unit.discardWorkingCopy();
						unit = JDTUtils.resolveCompilationUnit(uri);
						unit.becomeWorkingCopy(new NullProgressMonitor());
						triggerValidation(unit);
					}
					break;
				}
			}

		} catch (CoreException e) {
			JavaLanguageServerPlugin.logException(e.getMessage(), e);
		}
	}
	return unit;
}
 
Example 16
Source File: RenameModifications.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public void rename(ICompilationUnit unit, RenameArguments args) {
	add(unit, args, null);
	if (unit.getResource() != null) {
		getResourceModifications().addRename(unit.getResource(), new RenameArguments(args.getNewName(), args.getUpdateReferences()));
	}
}
 
Example 17
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static Change moveFileToContainer(ICompilationUnit cu, IContainer dest) {
	return new MoveResourceChange(cu.getResource(), dest);
}
 
Example 18
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static boolean isDefaultProject(ICompilationUnit unit) {
	return unit != null && unit.getResource() != null && unit.getResource().getProject().equals(JavaLanguageServerPlugin.getProjectsManager().getDefaultProject());
}
 
Example 19
Source File: JavaDeleteProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void checkDirtyCompilationUnit(RefactoringStatus result, ICompilationUnit cunit) {
	IResource resource= cunit.getResource();
	if (resource == null || resource.getType() != IResource.FILE)
		return;
	checkDirtyFile(result, (IFile)resource);
}
 
Example 20
Source File: TwoTimesCogniCryptRunTests.java    From CogniCrypt with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Scenario: User runs CogniCrypt two times and selects a previous generated
 * "logic" class.
 * 
 * @throws Exception
 */
@Test
public void runCCTwoTimesLogicClassSelection() throws Exception {
	// task template
	String templateSecEnc = "secretkeyencryption";
	String templateSecPwd = "securepassword";

	// create Java project without any package or class
	IJavaProject generatedProject = TestUtils.createJavaProject("TestProject3");

	// setup for first generation
	CodeGenerator codeGenerator = new CrySLBasedCodeGenerator(generatedProject.getResource());
	DeveloperProject developerProject = codeGenerator.getDeveloperProject();
	CrySLConfiguration chosenConfig = TestUtils.createCrySLConfiguration(templateSecEnc,
			generatedProject.getResource(), codeGenerator, developerProject);

	// first generation run
	boolean secEncCheck = codeGenerator.generateCodeTemplates(chosenConfig, "");
	assertTrue(secEncCheck); // check if code generation is successful for the first run

	ICompilationUnit encClass = TestUtils.getICompilationUnit(developerProject, Constants.PackageNameAsName,
			"SecureEncryptor.java");
	assertNotNull(encClass); // check if SecureEncryptor.java is created

	ICompilationUnit outputClass = TestUtils.getICompilationUnit(developerProject, Constants.PackageNameAsName,
			"Output.java");
	assertNotNull(outputClass);

	// setup for second generation
	codeGenerator = new CrySLBasedCodeGenerator(encClass.getResource());
	developerProject = codeGenerator.getDeveloperProject();
	chosenConfig = TestUtils.createCrySLConfiguration(templateSecPwd, encClass.getResource(), codeGenerator,
			developerProject);

	// second generation run
	boolean secPwdCheck = codeGenerator.generateCodeTemplates(chosenConfig, "");
	assertTrue(secPwdCheck); // check if code generation is successful for the second run

	ICompilationUnit pwdHasherClass = TestUtils.getICompilationUnit(developerProject, Constants.PackageNameAsName,
			"PasswordHasher.java");
	assertNotNull(pwdHasherClass); // check if PasswordHasher.java is created

	encClass = TestUtils.getICompilationUnit(developerProject, Constants.PackageNameAsName, "SecureEncryptor.java");
	assertNotNull(encClass);

	int secureEncryptorMethodCount = TestUtils.countMethods(encClass);

	assertEquals(4, secureEncryptorMethodCount);

}