org.eclipse.jdt.core.refactoring.CompilationUnitChange Java Examples

The following examples show how to use org.eclipse.jdt.core.refactoring.CompilationUnitChange. 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: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void addRequiredImportDeclarationsToContext() {
	ImportRewrite sourceImportRewrite = ImportRewrite.create(sourceCompilationUnit, true);
	for(ITypeBinding typeBinding : requiredImportDeclarationsForContext) {
		if(!typeBinding.isNested())
			sourceImportRewrite.addImport(typeBinding);
	}

	try {
		TextEdit sourceImportEdit = sourceImportRewrite.rewriteImports(null);
		if(sourceImportRewrite.getCreatedImports().length > 0) {
			ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
			CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
			change.getEdit().addChild(sourceImportEdit);
			change.addTextEditGroup(new TextEditGroup("Add required import declarations", new TextEdit[] {sourceImportEdit}));
		}
	} catch (CoreException e) {
		e.printStackTrace();
	}
}
 
Example #2
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void initializeReturnedVariableDeclaration() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	if(returnedVariable != null) {
		IVariableBinding returnedVariableBinding = returnedVariable.resolveBinding();
		if(returnedVariable instanceof VariableDeclarationFragment && !returnedVariableBinding.isField()) {
			VariableDeclarationFragment variableDeclarationFragment = (VariableDeclarationFragment)returnedVariable;
			if(variableDeclarationFragment.getInitializer() == null) {
				Expression defaultValue = generateDefaultValue(sourceRewriter, contextAST, returnedVariableBinding.getType());
				sourceRewriter.set(variableDeclarationFragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, defaultValue, null);
			}
		}
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Initialize returned variable", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #3
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private void updateCu(CompilationUnit unit, Set<ConstraintVariable> vars, CompilationUnitChange unitChange,
	ASTRewrite unitRewriter, String typeName) throws JavaModelException {

       // use custom SourceRangeComputer to avoid losing comments
	unitRewriter.setTargetSourceRangeComputer(new SourceRangeComputer());

	for (Iterator<ConstraintVariable> it=vars.iterator(); it.hasNext(); ){
		ConstraintVariable cv = it.next();
		ASTNode decl= findDeclaration(unit, cv);
		if ((decl instanceof SimpleName || decl instanceof QualifiedName) && cv instanceof ExpressionVariable) {
			ASTNode gp= decl.getParent().getParent();
			updateType(unit, getType(gp), unitChange, unitRewriter, typeName);   // local variable or parameter
		} else if (decl instanceof MethodDeclaration || decl instanceof FieldDeclaration) {
			updateType(unit, getType(decl), unitChange, unitRewriter, typeName); // method return or field type
		} else if (decl instanceof ParameterizedType){
			updateType(unit, getType(decl), unitChange, unitRewriter, typeName);
		}
	}
}
 
Example #4
Source File: CompilationUnitRewriteOperationsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException {
	CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite((ICompilationUnit)fCompilationUnit.getJavaElement(), fCompilationUnit);

	fLinkedProposalModel.clear();
	for (int i= 0; i < fOperations.length; i++) {
		CompilationUnitRewriteOperation operation= fOperations[i];
		operation.rewriteAST(cuRewrite, fLinkedProposalModel);
	}

	CompilationUnitChange result= cuRewrite.createChange(getDisplayString(), true, null);
	if (result == null)
		throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, Messages.format(FixMessages.CompilationUnitRewriteOperationsFix_nullChangeError, getDisplayString())));

	return result;
}
 
Example #5
Source File: ChangeUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Destructively clones a {@link CompilationUnitChange} where the cloned
 * change will have a different compilation unit. This does not update text
 * regions or anything more than setting the change properties and moving text
 * edits from the old to new change.
 * 
 * @param originalChange the original change, this change's internal state
 *          will likely become invalid (its text edits will be moved to the
 *          new change)
 * @param cu the compilation unit to be used for the new
 *          {@link CompilationUnitChange}
 * @return the cloned {@link CompilationUnitChange}
 */
public static CompilationUnitChange cloneCompilationUnitChangeWithDifferentCu(
    TextFileChange originalChange, ICompilationUnit cu) {
  CompilationUnitChange newChange = new CompilationUnitChange(
      originalChange.getName(), cu);

  newChange.setEdit(originalChange.getEdit());
  newChange.setEnabledShallow(originalChange.isEnabled());
  newChange.setKeepPreviewEdits(originalChange.getKeepPreviewEdits());
  newChange.setSaveMode(originalChange.getSaveMode());
  newChange.setTextType(originalChange.getTextType());

  // Copy the changes over
  TextEditUtilities.moveTextEditGroupsIntoChange(
      originalChange.getChangeGroups(), newChange);

  return newChange;
}
 
Example #6
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 6 votes vote down vote up
private void createStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
	
	FieldDeclaration typeFieldDeclaration = contextAST.newFieldDeclaration(typeFragment);
	sourceRewriter.set(typeFieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
	ListRewrite typeFieldDeclarationModifiersRewrite = sourceRewriter.getListRewrite(typeFieldDeclaration, FieldDeclaration.MODIFIERS2_PROPERTY);
	typeFieldDeclarationModifiersRewrite.insertLast(contextAST.newModifier(Modifier.ModifierKeyword.PRIVATE_KEYWORD), null);
	contextBodyRewrite.insertBefore(typeFieldDeclaration, typeCheckElimination.getTypeField().getParent(), null);
	
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Create field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #7
Source File: ReplaceConditionalWithPolymorphism.java    From JDeodorant with MIT License 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException,
		OperationCanceledException {
	try {
		pm.beginTask("Creating change...", 1);
		final Collection<CompilationUnitChange> changes = compilationUnitChanges.values();
		CompositeChange change = new CompositeChange(getName(), changes.toArray(new Change[changes.size()])) {
			@Override
			public ChangeDescriptor getDescriptor() {
				ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
				String project = sourceICompilationUnit.getJavaProject().getElementName();
				String description = MessageFormat.format("Replace Conditional with Polymorphism in method ''{0}''", new Object[] { typeCheckElimination.getTypeCheckMethod().getName().getIdentifier()});
				String comment = null;
				return new RefactoringChangeDescriptor(new ReplaceConditionalWithPolymorphismDescriptor(project, description, comment,
						sourceFile, sourceCompilationUnit, sourceTypeDeclaration, typeCheckElimination));
			}
		};
		return change;
	} finally {
		pm.done();
	}
}
 
Example #8
Source File: ChangeUtilTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConvertSimpleCompositeChange() throws CoreException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
	CompositeChange change = new CompositeChange("simple composite change");

	RenameCompilationUnitChange resourceChange = new RenameCompilationUnitChange(cu, "ENew.java");
	change.add(resourceChange);
	CompilationUnitChange textChange = new CompilationUnitChange("insertText", cu);
	textChange.setEdit(new InsertEdit(0, "// some content"));
	change.add(textChange);

	WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
	assertEquals(edit.getDocumentChanges().size(), 2);
	assertTrue(edit.getDocumentChanges().get(0).getRight() instanceof RenameFile);
	assertTrue(edit.getDocumentChanges().get(1).getLeft() instanceof TextDocumentEdit);
}
 
Example #9
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Change removeFields(ICompilationUnit cu, List<String> fields) throws CoreException {
	AccessorClassModifier sourceModification= new AccessorClassModifier(cu);
	String message= Messages.format(NLSMessages.AccessorClassModifier_remove_fields_from_accessor, BasicElementLabels.getFileName(cu));

	TextChange change= new CompilationUnitChange(message, cu);
	MultiTextEdit multiTextEdit= new MultiTextEdit();
	change.setEdit(multiTextEdit);

	for (int i= 0; i < fields.size(); i++) {
		String field= fields.get(i);
		NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null);
		sourceModification.removeKey(substitution, change);
	}

	if (change.getChangeGroups().length == 0)
		return null;

	change.addEdit(sourceModification.getTextEdit());

	return change;
}
 
Example #10
Source File: AccessorClassModifier.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static Change addFields(ICompilationUnit cu, List<String> fields) throws CoreException {
	AccessorClassModifier sourceModification= new AccessorClassModifier(cu);
	String message= Messages.format(NLSMessages.AccessorClassModifier_add_fields_to_accessor, BasicElementLabels.getFileName(cu));

	TextChange change= new CompilationUnitChange(message, cu);
	MultiTextEdit multiTextEdit= new MultiTextEdit();
	change.setEdit(multiTextEdit);

	for (int i= 0; i < fields.size(); i++) {
		String field= fields.get(i);
		NLSSubstitution substitution= new NLSSubstitution(NLSSubstitution.EXTERNALIZED, field, null, null, null);
		sourceModification.addKey(substitution, change);
	}

	if (change.getChangeGroups().length == 0)
		return null;

	change.addEdit(sourceModification.getTextEdit());

	return change;
}
 
Example #11
Source File: ChangeUtilTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConvertCompilationUnitChange() throws CoreException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
	CompilationUnitChange change = new CompilationUnitChange("insertText", cu);
	String newText = "// some content";
	change.setEdit(new InsertEdit(0, newText));

	WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);

	assertEquals(edit.getDocumentChanges().size(), 1);

	TextDocumentEdit textDocumentEdit = edit.getDocumentChanges().get(0).getLeft();
	assertNotNull(textDocumentEdit);
	assertEquals(textDocumentEdit.getEdits().size(), 1);

	TextEdit textEdit = textDocumentEdit.getEdits().get(0);
	assertEquals(textEdit.getNewText(), newText);
}
 
Example #12
Source File: MoveMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException,
		OperationCanceledException {
	try {
		pm.beginTask("Creating change...", 1);
		final Collection<CompilationUnitChange> changes = fChanges.values();
		CompositeChange change = new CompositeChange(getName(), changes.toArray(new Change[changes.size()])) {
			@Override
			public ChangeDescriptor getDescriptor() {
				ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
				String project = sourceICompilationUnit.getJavaProject().getElementName();
				String description = MessageFormat.format("Move method ''{0}''", new Object[] { sourceMethod.getName().getIdentifier()});
				String comment = MessageFormat.format("Move method ''{0}'' to ''{1}''", new Object[] { sourceMethod.getName().getIdentifier(), targetTypeDeclaration.getName().getIdentifier()});
				return new RefactoringChangeDescriptor(new MoveMethodRefactoringDescriptor(project, description, comment,
						sourceCompilationUnit, targetCompilationUnit,
						sourceTypeDeclaration, targetTypeDeclaration, sourceMethod,
						additionalMethodsToBeMoved, leaveDelegate, movedMethodName));
			}
		};
		return change;
	} finally {
		pm.done();
	}
}
 
Example #13
Source File: PolymorphismRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public PolymorphismRefactoring(IFile sourceFile, CompilationUnit sourceCompilationUnit,
		TypeDeclaration sourceTypeDeclaration, TypeCheckElimination typeCheckElimination) {
	this.sourceFile = sourceFile;
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.sourceTypeDeclaration = sourceTypeDeclaration;
	this.typeCheckElimination = typeCheckElimination;
	this.compilationUnitChanges = new LinkedHashMap<ICompilationUnit, CompilationUnitChange>();
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	MultiTextEdit sourceMultiTextEdit = new MultiTextEdit();
	CompilationUnitChange sourceCompilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	sourceCompilationUnitChange.setEdit(sourceMultiTextEdit);
	compilationUnitChanges.put(sourceICompilationUnit, sourceCompilationUnitChange);
	this.javaElementsToOpenInEditor = new LinkedHashSet<IJavaElement>();
	this.fieldDeclarationsChangedWithPublicModifier = new LinkedHashSet<FieldDeclaration>();
}
 
Example #14
Source File: StringFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException {
	if (fEditGroups == null || fEditGroups.length == 0)
		return null;

	CompilationUnitChange result= new CompilationUnitChange(getDisplayString(), fCompilationUnit);
	for (int i= 0; i < fEditGroups.length; i++) {
		TextEdit[] edits= fEditGroups[i].getTextEdits();
		String groupName= fEditGroups[i].getName();
		for (int j= 0; j < edits.length; j++) {
			TextChangeCompatibility.addTextEdit(result, groupName, edits[j]);
		}
	}
	return result;
}
 
Example #15
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
static CompilationUnitChange createAddImportChange(ICompilationUnit cu, Name name, String fullyQualifiedName) throws CoreException {
	String[] args= { BasicElementLabels.getJavaElementName(Signature.getSimpleName(fullyQualifiedName)),
			BasicElementLabels.getJavaElementName(Signature.getQualifier(fullyQualifiedName)) };
	String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_importtype_description, args);

	CompilationUnitChange cuChange= new CompilationUnitChange(label, cu);
	ImportRewrite importRewrite= StubUtility.createImportRewrite((CompilationUnit) name.getRoot(), true);
	importRewrite.addImport(fullyQualifiedName);
	cuChange.setEdit(importRewrite.rewriteImports(null));
	return cuChange;
}
 
Example #16
Source File: FixCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected TextChange createTextChange() throws CoreException {
	CompilationUnitChange createChange= fFix.createChange(null);
	createChange.setSaveMode(TextFileChange.LEAVE_DIRTY);

	if (fFix instanceof ILinkedFix) {
		setLinkedProposalModel(((ILinkedFix) fFix).getLinkedPositions());
	}

	return createChange;
}
 
Example #17
Source File: PasteAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
	p.setSource(getDestinationCu());
	CompilationUnit cuNode= (CompilationUnit) p.createAST(pm);
	ASTRewrite rewrite= ASTRewrite.create(cuNode.getAST());
	TypedSource source= null;
	for (int i= fSources.length - 1; i >= 0; i--) {
		source= fSources[i];
		final ASTNode destination= getDestinationNodeForSourceElement(fDestination, source.getType(), cuNode);
		if (destination != null) {
			if (destination instanceof CompilationUnit)
				insertToCu(rewrite, createNewNodeToInsertToCu(source, rewrite), (CompilationUnit) destination);
			else if (destination instanceof AbstractTypeDeclaration)
				insertToType(rewrite, createNewNodeToInsertToType(source, rewrite), (AbstractTypeDeclaration) destination);
		}
	}
	final CompilationUnitChange result= new CompilationUnitChange(ReorgMessages.PasteAction_change_name, getDestinationCu());
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(getDestinationCu());
		TextEdit rootEdit= rewrite.rewriteAST(buffer.getDocument(), fDestination.getJavaProject().getOptions(true));
		if (getDestinationCu().isWorkingCopy())
			result.setSaveMode(TextFileChange.LEAVE_DIRTY);
		TextChangeCompatibility.addTextEdit(result, ReorgMessages.PasteAction_edit_name, rootEdit);
	} finally {
		RefactoringFileBuffers.release(getDestinationCu());
	}
	return result;
}
 
Example #18
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void replaceDuplicates(CompilationUnitChange result, int modifiers) {
	int numberOf= getNumberOfDuplicates();
	if (numberOf == 0 || !fReplaceDuplicates)
		return;
	String label= null;
	if (numberOf == 1)
		label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, BasicElementLabels.getJavaElementName(fMethodName));
	else
		label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, BasicElementLabels.getJavaElementName(fMethodName));

	TextEditGroup description= new TextEditGroup(label);
	result.addTextEditGroup(description);

	for (int d= 0; d < fDuplicates.length; d++) {
		SnippetFinder.Match duplicate= fDuplicates[d];
		if (!duplicate.isInvalidNode()) {
			if (isDestinationReachable(duplicate.getEnclosingMethod())) {
				ASTNode[] callNodes= createCallNodes(duplicate, modifiers);
				ASTNode[] duplicateNodes= duplicate.getNodes();
				for (int i= 0; i < duplicateNodes.length; i++) {
					ASTNode parent= duplicateNodes[i].getParent();
					if (parent instanceof ParenthesizedExpression) {
						duplicateNodes[i]= parent;
					}
				}
				new StatementRewrite(fRewriter, duplicateNodes).replace(callNodes, description);
			}
		}
	}
}
 
Example #19
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
protected static CompilationUnitChange createCompilationUnitChange(CompilationUnitRewrite rewrite) throws CoreException {
	CompilationUnitChange change= rewrite.createChange(true);
	if (change != null)
		change.setSaveMode(TextFileChange.KEEP_SAVE_STATE);

	return change;
}
 
Example #20
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private void replacePrimitiveStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields();
	for(FieldDeclaration fieldDeclaration : fieldDeclarations) {
		List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.equals(typeCheckElimination.getTypeField())) {
				if(fragments.size() == 1) {
					ListRewrite fragmentsRewriter = sourceRewriter.getListRewrite(fieldDeclaration, FieldDeclaration.FRAGMENTS_PROPERTY);
					fragmentsRewriter.remove(fragment, null);
					VariableDeclarationFragment typeFragment = createStateFieldVariableDeclarationFragment(sourceRewriter, contextAST);
					fragmentsRewriter.insertLast(typeFragment, null);
					sourceRewriter.set(fieldDeclaration, FieldDeclaration.TYPE_PROPERTY, contextAST.newSimpleName(abstractClassName), null);
				}
			}
		}
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Replace primitive type with State type", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #21
Source File: RenameNonVirtualMethodProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addDeclarationUpdate(TextChangeManager manager) throws CoreException {

		if (getDelegateUpdating()) {
			// create the delegate
			CompilationUnitRewrite rewrite= new CompilationUnitRewrite(getDeclaringCU());
			rewrite.setResolveBindings(true);
			MethodDeclaration methodDeclaration= ASTNodeSearchUtil.getMethodDeclarationNode(getMethod(), rewrite.getRoot());
			DelegateMethodCreator creator= new DelegateMethodCreator();
			creator.setDeclaration(methodDeclaration);
			creator.setDeclareDeprecated(getDeprecateDelegates());
			creator.setSourceRewrite(rewrite);
			creator.setCopy(true);
			creator.setNewElementName(getNewElementName());
			creator.prepareDelegate();
			creator.createEdit();
			CompilationUnitChange cuChange= rewrite.createChange(true);
			if (cuChange != null) {
				cuChange.setKeepPreviewEdits(true);
				manager.manage(getDeclaringCU(), cuChange);
			}
		}

		String editName= RefactoringCoreMessages.RenameMethodRefactoring_update_declaration;
		ISourceRange nameRange= getMethod().getNameRange();
		ReplaceEdit replaceEdit= new ReplaceEdit(nameRange.getOffset(), nameRange.getLength(), getNewElementName());
		addTextEdit(manager.get(getDeclaringCU()), editName, replaceEdit);
	}
 
Example #22
Source File: TextEditFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException {
	String label= fChangeDescription;
	CompilationUnitChange result= new CompilationUnitChange(label, fUnit);
	result.setEdit(fEdit);
	result.addTextEditGroup(new CategorizedTextEditGroup(label, new GroupCategorySet(new GroupCategory(label, label, label))));
	return result;
}
 
Example #23
Source File: CleanUpRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void findFilesToBeModified(CompositeChange change, List<IResource> result) throws JavaModelException {
	Change[] children= change.getChildren();
	for (int i= 0; i < children.length; i++) {
		Change child= children[i];
		if (child instanceof CompositeChange) {
			findFilesToBeModified((CompositeChange)child, result);
		} else if (child instanceof MultiStateCompilationUnitChange) {
			result.add(((MultiStateCompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
		} else if (child instanceof CompilationUnitChange) {
			result.add(((CompilationUnitChange)child).getCompilationUnit().getCorrespondingResource());
		}
	}
}
 
Example #24
Source File: RefactoringAdapterFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public Object getAdapter(Object object, Class key) {
	if (!TextEditChangeNode.class.equals(key))
		return null;
	if (!(object instanceof CompilationUnitChange) && !(object instanceof MultiStateCompilationUnitChange))
		return null;
	return new CompilationUnitChangeNode((TextEditBasedChange)object);
}
 
Example #25
Source File: InlineConstantRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CompilationUnitChange getChange() throws CoreException {
	for (int i= 0; i < fReferences.length; i++)
		inlineReference(fReferences[i]);

	removeConstantDeclarationIfNecessary();

	return fCuRewrite.createChange(true);
}
 
Example #26
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 5 votes vote down vote up
private void removePrimitiveStateField() {
	ASTRewrite sourceRewriter = ASTRewrite.create(sourceTypeDeclaration.getAST());
	AST contextAST = sourceTypeDeclaration.getAST();
	ListRewrite contextBodyRewrite = sourceRewriter.getListRewrite(sourceTypeDeclaration, TypeDeclaration.BODY_DECLARATIONS_PROPERTY);
	FieldDeclaration[] fieldDeclarations = sourceTypeDeclaration.getFields();
	for(FieldDeclaration fieldDeclaration : fieldDeclarations) {
		List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
		for(VariableDeclarationFragment fragment : fragments) {
			if(fragment.equals(typeCheckElimination.getTypeField())) {
				if(fragments.size() == 1) {
					contextBodyRewrite.remove(fragment.getParent(), null);
				}
				else {
					ListRewrite fragmentRewrite = sourceRewriter.getListRewrite(fragment.getParent(), FieldDeclaration.FRAGMENTS_PROPERTY);
					fragmentRewrite.remove(fragment, null);
				}
			}
		}
	}
	try {
		TextEdit sourceEdit = sourceRewriter.rewriteAST();
		ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
		CompilationUnitChange change = compilationUnitChanges.get(sourceICompilationUnit);
		change.getEdit().addChild(sourceEdit);
		change.addTextEditGroup(new TextEditGroup("Remove primitive field holding the current state", new TextEdit[] {sourceEdit}));
	} catch (JavaModelException e) {
		e.printStackTrace();
	}
}
 
Example #27
Source File: PromoteTempToFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
   	pm.beginTask("", 1); //$NON-NLS-1$
   	try {
   		if (fFieldName.length() == 0) {
   			fFieldName= getInitialFieldName();
   		}

   		ASTRewrite rewrite= ASTRewrite.create(fCompilationUnitNode.getAST());
   		if (fInitializeIn == INITIALIZE_IN_METHOD && tempHasInitializer())
   			addLocalDeclarationSplit(rewrite);
		else
			addLocalDeclarationRemoval(rewrite);
   		if (fInitializeIn == INITIALIZE_IN_CONSTRUCTOR)
   			addInitializersToConstructors(rewrite);
  			addTempRenames(rewrite);
   		addFieldDeclaration(rewrite);

		CompilationUnitChange result= new CompilationUnitChange(RefactoringCoreMessages.PromoteTempToFieldRefactoring_name, fCu);
		result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
		TextEdit resultingEdits= rewrite.rewriteAST();
		TextChangeCompatibility.addTextEdit(result, RefactoringCoreMessages.PromoteTempToFieldRefactoring_editName, resultingEdits);
		return result;

   	} finally {
   		pm.done();
   	}
   }
 
Example #28
Source File: InlineTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask(RefactoringCoreMessages.InlineTempRefactoring_preview, 2);
		final Map<String, String> arguments= new HashMap<String, String>();
		String project= null;
		IJavaProject javaProject= fCu.getJavaProject();
		if (javaProject != null)
			project= javaProject.getElementName();

		final IVariableBinding binding= getVariableDeclaration().resolveBinding();
		String text= null;
		final IMethodBinding method= binding.getDeclaringMethod();
		if (method != null)
			text= BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED);
		else
			text= BasicElementLabels.getJavaElementName('{' + JavaElementLabels.ELLIPSIS_STRING + '}');
		final String description= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(binding.getName()));
		final String header= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), text});
		final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
		comment.addSetting(Messages.format(RefactoringCoreMessages.InlineTempRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
		final InlineLocalVariableDescriptor descriptor= RefactoringSignatureDescriptorFactory.createInlineLocalVariableDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE);
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu));
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, String.valueOf(fSelectionStart) + ' ' + String.valueOf(fSelectionLength));

		CompilationUnitRewrite cuRewrite= new CompilationUnitRewrite(fCu, fASTRoot);

		inlineTemp(cuRewrite);
		removeTemp(cuRewrite);

		final CompilationUnitChange result= cuRewrite.createChange(RefactoringCoreMessages.InlineTempRefactoring_inline, false, new SubProgressMonitor(pm, 1));
		result.setDescriptor(new RefactoringChangeDescriptor(descriptor));
		return result;
	} finally {
		pm.done();
	}
}
 
Example #29
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public CompilationUnitChange createCompilationUnitChange(IProgressMonitor pm) throws CoreException {
final CompilationUnitRewrite rewrite= new CompilationUnitRewrite(fCu, fCompilationUnitNode);
final ITypeBinding[] typeParameters= getTypeParameters();
addNestedClass(rewrite, typeParameters);
modifyConstructorCall(rewrite, typeParameters);
return rewrite.createChange(RefactoringCoreMessages.ConvertAnonymousToNestedRefactoring_name, false, pm);
  }
 
Example #30
Source File: InferTypeArgumentsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void rewriteDeclarations(InferTypeArgumentsUpdate update, IProgressMonitor pm) throws CoreException {
	HashMap<ICompilationUnit, CuUpdate> updates= update.getUpdates();

	Set<Entry<ICompilationUnit, CuUpdate>> entrySet= updates.entrySet();
	pm.beginTask("", entrySet.size()); //$NON-NLS-1$
	pm.setTaskName(RefactoringCoreMessages.InferTypeArgumentsRefactoring_creatingChanges);
	for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter= entrySet.iterator(); iter.hasNext();) {
		if (pm.isCanceled())
			throw new OperationCanceledException();

		Entry<ICompilationUnit, CuUpdate> entry= iter.next();
		ICompilationUnit cu= entry.getKey();
		pm.worked(1);
		pm.subTask(BasicElementLabels.getFileName(cu));

		CompilationUnitRewrite rewrite= new CompilationUnitRewrite(cu);
		rewrite.setResolveBindings(false);
		CuUpdate cuUpdate= entry.getValue();

		for (Iterator<CollectionElementVariable2> cvIter= cuUpdate.getDeclarations().iterator(); cvIter.hasNext();) {
			ConstraintVariable2 cv= cvIter.next();
			rewriteConstraintVariable(cv, rewrite, fTCModel, fLeaveUnconstrainedRaw, null);
		}

		for (Iterator<CastVariable2> castsIter= cuUpdate.getCastsToRemove().iterator(); castsIter.hasNext();) {
			CastVariable2 castCv= castsIter.next();
			rewriteCastVariable(castCv, rewrite, fTCModel);
		}

		CompilationUnitChange change= rewrite.createChange(true);
		if (change != null) {
			fChangeManager.manage(cu, change);
		}
	}

}