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

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getWorkingCopy() . 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: SimilarElementsRequestor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static ICompilationUnit createPreparedCU(ICompilationUnit cu, Javadoc comment, int wordStart) throws JavaModelException {
	int startpos= comment.getStartPosition();
	boolean isTopLevel= comment.getParent().getParent() instanceof CompilationUnit;
	char[] content= cu.getBuffer().getCharacters().clone();
	if (isTopLevel && (wordStart + 6 < content.length)) {
		content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p';
		content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't';
	}
	if (wordStart < content.length) {
		for (int i= startpos; i < wordStart; i++) {
			content[i]= ' ';
		}
	}

	/*
	 * Explicitly create a new non-shared working copy.
	 */
	ICompilationUnit newCU= cu.getWorkingCopy(null);
	newCU.getBuffer().setContents(content);
	return newCU;
}
 
Example 2
Source File: SimilarElementsRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static ICompilationUnit createPreparedCU(ICompilationUnit cu, Javadoc comment, int wordStart) throws JavaModelException {
	int startpos= comment.getStartPosition();
	boolean isTopLevel= comment.getParent().getParent() instanceof CompilationUnit;
	char[] content= cu.getBuffer().getCharacters().clone();
	if (isTopLevel && (wordStart + 6 < content.length)) {
		content[startpos++]= 'i'; content[startpos++]= 'm'; content[startpos++]= 'p';
		content[startpos++]= 'o'; content[startpos++]= 'r'; content[startpos++]= 't';
	}
	if (wordStart < content.length) {
		for (int i= startpos; i < wordStart; i++) {
			content[i]= ' ';
		}
	}

	/*
	 * Explicitly create a new non-shared working copy.
	 */
	ICompilationUnit newCU= cu.getWorkingCopy(null);
	newCU.getBuffer().setContents(content);
	return newCU;
}
 
Example 3
Source File: RenameAnalyzeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
static ICompilationUnit createNewWorkingCopy(ICompilationUnit cu, TextChangeManager manager,
		WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
	ICompilationUnit newWc= cu.getWorkingCopy(owner, null);
	String previewContent= manager.get(cu).getPreviewContent(new NullProgressMonitor());
	newWc.getBuffer().setContents(previewContent);
	newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm);
	return newWc;
}
 
Example 4
Source File: AbstractCompilationUnitBasedTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
protected ICompilationUnit getWorkingCopy(String path, String source) throws JavaModelException {
	ICompilationUnit workingCopy = getCompilationUnit(path);
	workingCopy.getWorkingCopy(wcOwner, monitor);
	workingCopy.getBuffer().setContents(source);
	workingCopy.makeConsistent(monitor);
	return workingCopy;
}
 
Example 5
Source File: SuperTypeRefactoringProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected ICompilationUnit getSharedWorkingCopy(final ICompilationUnit unit, final IProgressMonitor monitor) throws JavaModelException {
	try {
		ICompilationUnit copy= unit.findWorkingCopy(fOwner);
		if (copy == null)
			copy= unit.getWorkingCopy(fOwner, monitor);
		return copy;
	} finally {
		monitor.done();
	}
}
 
Example 6
Source File: RenameAnalyzeUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static ICompilationUnit createNewWorkingCopy(ICompilationUnit cu, TextChangeManager manager,
		WorkingCopyOwner owner, SubProgressMonitor pm) throws CoreException {
	ICompilationUnit newWc= cu.getWorkingCopy(owner, null);
	String previewContent= manager.get(cu).getPreviewContent(new NullProgressMonitor());
	newWc.getBuffer().setContents(previewContent);
	newWc.reconcile(ICompilationUnit.NO_AST, false, owner, pm);
	return newWc;
}
 
Example 7
Source File: SimilarElementsRequestor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException {
	StringBuffer dummyCU= new StringBuffer();
	String packName= cu.getParent().getElementName();
	IType type= cu.findPrimaryType();
	if (type == null) {
		return new String[0];
	}

	if (packName.length() > 0) {
		dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$
	}
	dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer  //$NON-NLS-1$//$NON-NLS-2$
	int offset= dummyCU.length();
	dummyCU.append("\n}\n }"); //$NON-NLS-1$

	ICompilationUnit newCU= null;
	try {
		newCU= cu.getWorkingCopy(null);
		newCU.getBuffer().setContents(dummyCU.toString());

		final HashSet<String> result= new HashSet<>();

		CompletionRequestor requestor= new CompletionRequestor(true) {
			@Override
			public void accept(CompletionProposal proposal) {
				if (elementName.equals(new String(proposal.getName()))) {
					CompletionProposal[] requiredProposals= proposal.getRequiredProposals();
					for (int i= 0; i < requiredProposals.length; i++) {
						CompletionProposal curr= requiredProposals[i];
						if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) {
							result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName()));
						}
					}
				}
			}
		};

		if (isMethod) {
			requestor.setIgnored(CompletionProposal.METHOD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
		} else {
			requestor.setIgnored(CompletionProposal.FIELD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
		}
		requestor.setFavoriteReferences(favorites);

		newCU.codeComplete(offset, requestor);

		return result.toArray(new String[result.size()]);
	} finally {
		if (newCU != null) {
			newCU.discardWorkingCopy();
		}
	}
}
 
Example 8
Source File: ParameterObjectFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public List<ResourceChange> createTopLevelParameterObject(IPackageFragmentRoot packageFragmentRoot, CreationListener listener) throws CoreException {
	List<ResourceChange> changes= new ArrayList<ResourceChange>();
	IPackageFragment packageFragment= packageFragmentRoot.getPackageFragment(getPackage());
	if (!packageFragment.exists()) {
		changes.add(new CreatePackageChange(packageFragment));
	}
	ICompilationUnit unit= packageFragment.getCompilationUnit(getClassName() + JavaModelUtil.DEFAULT_CU_SUFFIX);
	Assert.isTrue(!unit.exists());
	IJavaProject javaProject= unit.getJavaProject();
	ICompilationUnit workingCopy= unit.getWorkingCopy(null);

	try {
		// create stub with comments and dummy type
		String lineDelimiter= StubUtility.getLineDelimiterUsed(javaProject);
		String fileComment= getFileComment(workingCopy, lineDelimiter);
		String typeComment= getTypeComment(workingCopy, lineDelimiter);
		String content= CodeGeneration.getCompilationUnitContent(workingCopy, fileComment, typeComment, "class " + getClassName() + "{}", lineDelimiter); //$NON-NLS-1$ //$NON-NLS-2$
		workingCopy.getBuffer().setContents(content);

		CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(workingCopy);
		ASTRewrite rewriter= cuRewrite.getASTRewrite();
		CompilationUnit root= cuRewrite.getRoot();
		AST ast= cuRewrite.getAST();
		ImportRewrite importRewrite= cuRewrite.getImportRewrite();

		// retrieve&replace dummy type with real class
		ListRewrite types= rewriter.getListRewrite(root, CompilationUnit.TYPES_PROPERTY);
		ASTNode dummyType= (ASTNode) types.getOriginalList().get(0);
		String newTypeName= JavaModelUtil.concatenateName(getPackage(), getClassName());
		TypeDeclaration classDeclaration= createClassDeclaration(newTypeName, cuRewrite, listener);
		classDeclaration.modifiers().add(ast.newModifier(ModifierKeyword.PUBLIC_KEYWORD));
		Javadoc javadoc= (Javadoc) dummyType.getStructuralProperty(TypeDeclaration.JAVADOC_PROPERTY);
		rewriter.set(classDeclaration, TypeDeclaration.JAVADOC_PROPERTY, javadoc, null);
		types.replace(dummyType, classDeclaration, null);

		// Apply rewrites and discard workingcopy
		// Using CompilationUnitRewrite.createChange() leads to strange
		// results
		String charset= ResourceUtil.getFile(unit).getCharset(false);
		Document document= new Document(content);
		try {
			rewriter.rewriteAST().apply(document);
			TextEdit rewriteImports= importRewrite.rewriteImports(null);
			rewriteImports.apply(document);
		} catch (BadLocationException e) {
			throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), RefactoringCoreMessages.IntroduceParameterObjectRefactoring_parameter_object_creation_error, e));
		}
		String docContent= document.get();
		CreateCompilationUnitChange compilationUnitChange= new CreateCompilationUnitChange(unit, docContent, charset);
		changes.add(compilationUnitChange);
	} finally {
		workingCopy.discardWorkingCopy();
	}
	return changes;
}
 
Example 9
Source File: CleanUpRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void next(IProgressMonitor monitor) throws CoreException {
	List<ICompilationUnit> parseList= new ArrayList<ICompilationUnit>();
	List<ICompilationUnit> sourceList= new ArrayList<ICompilationUnit>();

	try {
		for (Iterator<ParseListElement> iter= fParseList.iterator(); iter.hasNext();) {
			ParseListElement element= iter.next();

			ICompilationUnit compilationUnit= element.getTarget().getCompilationUnit();
			if (fSolutions.containsKey(compilationUnit)) {
				if (fWorkingCopies.containsKey(compilationUnit)) {
					compilationUnit= fWorkingCopies.get(compilationUnit);
				} else {
					compilationUnit= compilationUnit.getWorkingCopy(new WorkingCopyOwner() {}, null);
					fWorkingCopies.put(compilationUnit.getPrimary(), compilationUnit);
				}
				applyChange(compilationUnit, fSolutions.get(compilationUnit.getPrimary()));
			}

			if (requiresAST(element.getCleanUps())) {
				parseList.add(compilationUnit);
			} else {
				sourceList.add(compilationUnit);
			}
		}

		CleanUpRefactoringProgressMonitor cuMonitor= new CleanUpRefactoringProgressMonitor(monitor, parseList.size() + sourceList.size(), fSize, fIndex);
		CleanUpASTRequestor requestor= new CleanUpASTRequestor(fParseList, fSolutions, cuMonitor);
		if (parseList.size() > 0) {
			ASTBatchParser parser= new ASTBatchParser() {
				@Override
				protected ASTParser createParser(IJavaProject project) {
					ASTParser result= createCleanUpASTParser();
					result.setProject(project);

					Map<String, String> options= RefactoringASTParser.getCompilerOptions(project);
					options.putAll(fCleanUpOptions);
					result.setCompilerOptions(options);
					return result;
				}
			};
			try {
				ICompilationUnit[] units= parseList.toArray(new ICompilationUnit[parseList.size()]);
				parser.createASTs(units, new String[0], requestor, cuMonitor);
			} catch (FixCalculationException e) {
				throw e.getException();
			}
		}

		for (Iterator<ICompilationUnit> iterator= sourceList.iterator(); iterator.hasNext();) {
			ICompilationUnit cu= iterator.next();

			monitor.worked(1);

			requestor.acceptSource(cu);

			if (monitor.isCanceled())
				throw new OperationCanceledException();
		}

		fParseList= requestor.getUndoneElements();
		fIndex= cuMonitor.getIndex();
	} finally {
	}
}
 
Example 10
Source File: SimilarElementsRequestor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static String[] getStaticImportFavorites(ICompilationUnit cu, final String elementName, boolean isMethod, String[] favorites) throws JavaModelException {
	StringBuffer dummyCU= new StringBuffer();
	String packName= cu.getParent().getElementName();
	IType type= cu.findPrimaryType();
	if (type == null)
		return new String[0];
	
	if (packName.length() > 0) {
		dummyCU.append("package ").append(packName).append(';'); //$NON-NLS-1$
	}		
	dummyCU.append("public class ").append(type.getElementName()).append("{\n static {\n").append(elementName); // static initializer  //$NON-NLS-1$//$NON-NLS-2$
	int offset= dummyCU.length();
	dummyCU.append("\n}\n }"); //$NON-NLS-1$
	
	ICompilationUnit newCU= null;
	try {
		newCU= cu.getWorkingCopy(null);
		newCU.getBuffer().setContents(dummyCU.toString());
		
		final HashSet<String> result= new HashSet<String>();
		
		CompletionRequestor requestor= new CompletionRequestor(true) {
			@Override
			public void accept(CompletionProposal proposal) {
				if (elementName.equals(new String(proposal.getName()))) {
					CompletionProposal[] requiredProposals= proposal.getRequiredProposals();
					for (int i= 0; i < requiredProposals.length; i++) {
						CompletionProposal curr= requiredProposals[i];
						if (curr.getKind() == CompletionProposal.METHOD_IMPORT || curr.getKind() == CompletionProposal.FIELD_IMPORT) {
							result.add(JavaModelUtil.concatenateName(Signature.toCharArray(curr.getDeclarationSignature()), curr.getName()));
						}
					}
				}
			}
		};
		
		if (isMethod) {
			requestor.setIgnored(CompletionProposal.METHOD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.METHOD_REF, CompletionProposal.METHOD_IMPORT, true);
		} else {
			requestor.setIgnored(CompletionProposal.FIELD_REF, false);
			requestor.setAllowsRequiredProposals(CompletionProposal.FIELD_REF, CompletionProposal.FIELD_IMPORT, true);
		}
		requestor.setFavoriteReferences(favorites);
		
		newCU.codeComplete(offset, requestor);
		
		return result.toArray(new String[result.size()]);
	} finally {
		if (newCU != null) {
			newCU.discardWorkingCopy();
		}	
	}	
}