Java Code Examples for org.eclipse.jdt.core.refactoring.CompilationUnitChange#setEdit()

The following examples show how to use org.eclipse.jdt.core.refactoring.CompilationUnitChange#setEdit() . 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: 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 2
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 3
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 4
Source File: RenameLocalVariableProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void createEdits() {
	TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition());
	TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit);

	TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length];
	TextEdit unparentedDeclarationEdit= null;

	fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu);
	MultiTextEdit rootEdit= new MultiTextEdit();
	fChange.setEdit(rootEdit);
	fChange.setKeepPreviewEdits(true);

	for (int i= 0; i < allRenameEdits.length; i++) {
		if (fIsComposite) {
			// Add a copy of the text edit (text edit may only have one
			// parent) to keep problem reporting code clean
			TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet);

			// Add a separate copy for problem reporting
			allUnparentedRenameEdits[i]= allRenameEdits[i].copy();
			if (allRenameEdits[i].equals(declarationEdit))
				unparentedDeclarationEdit= allUnparentedRenameEdits[i];
		}
		rootEdit.addChild(allRenameEdits[i]);
		fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i]));
	}

	// store information for analysis
	if (fIsComposite) {
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits);
	} else
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits);
}
 
Example 5
Source File: UpdateCopyrightFix.java    From saneclipse with Eclipse Public License 1.0 5 votes vote down vote up
public static ICleanUpFix createCleanUp(ICompilationUnit compilationUnit, boolean updateIbmCopyright) throws CoreException {
	if (!updateIbmCopyright)
		return null;
	
	IBuffer buffer= compilationUnit.getBuffer();
	String contents= buffer.getContents();
	
	for (SearchReplacePattern pattern : SEARCH_REPLACE_PATTERNS) {
		Matcher matcher= pattern.getSearchPattern().matcher(contents);
		if (matcher.find(0)) {
			int start= matcher.start();
			int end= matcher.end();
			String substring= contents.substring(start, end);
			
			matcher= pattern.getSearchPattern().matcher(substring);
			String replacement= matcher.replaceFirst(pattern.getReplaceString());
			if (substring.equals(replacement))
				return null;
			
			ReplaceEdit edit= new ReplaceEdit(start, substring.length(), replacement);
			
			CompilationUnitChange change= new CompilationUnitChange("Update Copyright", compilationUnit); //$NON-NLS-1$
			change.setEdit(edit);
			
			return new UpdateCopyrightFix(change);
		}
	}
	
	return null;
}
 
Example 6
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 7
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 8
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 9
Source File: RenameLocalVariableProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void createEdits() {
	TextEdit declarationEdit= createRenameEdit(fTempDeclarationNode.getName().getStartPosition());
	TextEdit[] allRenameEdits= getAllRenameEdits(declarationEdit);

	TextEdit[] allUnparentedRenameEdits= new TextEdit[allRenameEdits.length];
	TextEdit unparentedDeclarationEdit= null;

	fChange= new CompilationUnitChange(RefactoringCoreMessages.RenameTempRefactoring_rename, fCu);
	MultiTextEdit rootEdit= new MultiTextEdit();
	fChange.setEdit(rootEdit);
	fChange.setKeepPreviewEdits(true);

	for (int i= 0; i < allRenameEdits.length; i++) {
		if (fIsComposite) {
			// Add a copy of the text edit (text edit may only have one
			// parent) to keep problem reporting code clean
			TextChangeCompatibility.addTextEdit(fChangeManager.get(fCu), RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i].copy(), fCategorySet);

			// Add a separate copy for problem reporting
			allUnparentedRenameEdits[i]= allRenameEdits[i].copy();
			if (allRenameEdits[i].equals(declarationEdit)) {
				unparentedDeclarationEdit= allUnparentedRenameEdits[i];
			}
		}
		rootEdit.addChild(allRenameEdits[i]);
		fChange.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.RenameTempRefactoring_changeName, allRenameEdits[i]));
	}

	// store information for analysis
	if (fIsComposite) {
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(unparentedDeclarationEdit, allUnparentedRenameEdits);
	} else {
		fLocalAnalyzePackage= new RenameAnalyzeUtil.LocalAnalyzePackage(declarationEdit, allRenameEdits);
	}
}
 
Example 10
Source File: ChangeTypeRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Apply all changes related to a single ICompilationUnit
 * @param icu the compilation unit
 * @param vars
 * @param unitChange
 * @throws CoreException
 */
private void addAllChangesFor(ICompilationUnit icu, Set<ConstraintVariable> vars, CompilationUnitChange unitChange) throws CoreException {
	CompilationUnit	unit= new RefactoringASTParser(ASTProvider.SHARED_AST_LEVEL).parse(icu, true);
	ASTRewrite unitRewriter= ASTRewrite.create(unit.getAST());
	MultiTextEdit root= new MultiTextEdit();
	unitChange.setEdit(root); // Adam sez don't need this, but then unitChange.addGroupDescription() fails an assertion!

	String typeName= updateImports(unit, root);
	updateCu(unit, vars, unitChange, unitRewriter, typeName);
	root.addChild(unitRewriter.rewriteAST());
}
 
Example 11
Source File: AddResourcesToClientBundleAction.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void run(IProgressMonitor monitor) throws CoreException {
  ICompilationUnit icu = clientBundle.getCompilationUnit();
  CompilationUnit cu = JavaASTUtils.parseCompilationUnit(icu);
  ImportRewrite importRewrite = StubUtility.createImportRewrite(cu, true);

  // Find the target type declaration
  TypeDeclaration typeDecl = JavaASTUtils.findTypeDeclaration(cu,
      clientBundle.getFullyQualifiedName());
  if (typeDecl == null) {
    throw new CoreException(
        StatusUtilities.newErrorStatus("Missing ClientBundle type "
            + clientBundle.getFullyQualifiedName(), GWTPlugin.PLUGIN_ID));
  }

  // We need to rewrite the AST of the ClientBundle type declaration
  ASTRewrite astRewrite = ASTRewrite.create(cu.getAST());
  ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(typeDecl);
  ListRewrite listRewriter = astRewrite.getListRewrite(typeDecl, property);

  // Add the new resource methods
  boolean addComments = StubUtility.doAddComments(icu.getJavaProject());
  for (ClientBundleResource resource : resources) {
    listRewriter.insertLast(resource.createMethodDeclaration(clientBundle,
        astRewrite, importRewrite, addComments), null);
  }

  // Create the edit to add the methods and update the imports
  TextEdit rootEdit = new MultiTextEdit();
  rootEdit.addChild(astRewrite.rewriteAST());
  rootEdit.addChild(importRewrite.rewriteImports(null));

  // Apply the change to the compilation unit
  CompilationUnitChange cuChange = new CompilationUnitChange(
      "Update ClientBundle", icu);
  cuChange.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
  cuChange.setEdit(rootEdit);
  cuChange.perform(new NullProgressMonitor());
}
 
Example 12
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.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 = CodeStyleConfiguration.createImportRewrite((CompilationUnit) name.getRoot(), true);
	importRewrite.addImport(fullyQualifiedName);
	cuChange.setEdit(importRewrite.rewriteImports(null));
	return cuChange;
}
 
Example 13
Source File: NewCUProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private CompilationUnitChange constructNewCUChange(ICompilationUnit cu) throws CoreException {
	String lineDelimiter = StubUtility.getLineDelimiterUsed(fCompilationUnit.getJavaProject());
	String typeStub = constructTypeStub(cu, fTypeNameWithParameters, Flags.AccPublic, lineDelimiter);
	String cuContent = constructCUContent(cu, typeStub, lineDelimiter);
	CompilationUnitChange cuChange = new CompilationUnitChange("", cu);
	cuChange.setEdit(new InsertEdit(0, cuContent));
	return cuChange;
}
 
Example 14
Source File: InlineMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask("", 20); //$NON-NLS-1$
	fChangeManager= new TextChangeManager();
	RefactoringStatus result= new RefactoringStatus();
	fSourceProvider.initialize();
	fTargetProvider.initialize();

	pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
	RefactoringStatus searchStatus= new RefactoringStatus();
	String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
	ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
	ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
	binaryRefs.addErrorIfNecessary(searchStatus);
	if (searchStatus.hasFatalError()) {
		result.merge(searchStatus);
		return result;
	}

	IFile[] filesToBeModified= getFilesToBeModified(units);
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
	if (result.hasFatalError())
		return result;
	result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
	checkOverridden(result, new SubProgressMonitor(pm, 4));
	IProgressMonitor sub= new SubProgressMonitor(pm, 15);
	sub.beginTask("", units.length * 3); //$NON-NLS-1$
	for (int c= 0; c < units.length; c++) {
		ICompilationUnit unit= units[c];
		sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing,  BasicElementLabels.getFileName(unit)));
		CallInliner inliner= null;
		try {
			boolean added= false;
			MultiTextEdit root= new MultiTextEdit();
			CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
			change.setEdit(root);
			BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
			if (bodies.length == 0)
				continue;
			inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
			for (int b= 0; b < bodies.length; b++) {
				BodyDeclaration body= bodies[b];
				inliner.initialize(body);
				RefactoringStatus nestedInvocations= new RefactoringStatus();
				ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
					fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
				for (int i= 0; i < invocations.length; i++) {
					ASTNode invocation= invocations[i];
					result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
					if (result.hasFatalError())
						break;
					if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
						added= true;
						TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
						change.addTextEditGroup(group);
						result.merge(inliner.perform(group));
					} else {
						fDeleteSource= false;
					}
				}
				// do this after we have inlined the method calls. We still want
				// to generate the modifications.
				if (!nestedInvocations.isOK()) {
					result.merge(nestedInvocations);
					fDeleteSource= false;
				}
			}
			if (!added) {
				fChangeManager.remove(unit);
			} else {
				root.addChild(inliner.getModifications());
				ImportRewrite rewrite= inliner.getImportEdit();
				if (rewrite.hasRecordedChanges()) {
					TextEdit edit= rewrite.rewriteImports(null);
					if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
						root.addChild(edit);
						change.addTextEditGroup(
							new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
					}
				}
			}
		} finally {
			if (inliner != null)
				inliner.dispose();
		}
		sub.worked(1);
		if (sub.isCanceled())
			throw new OperationCanceledException();
	}
	result.merge(searchStatus);
	sub.done();
	pm.done();
	return result;
}
 
Example 15
Source File: ReplaceInvocationsRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
	pm.beginTask("", 20); //$NON-NLS-1$
	fChangeManager= new TextChangeManager();
	RefactoringStatus result= new RefactoringStatus();

	fSourceProvider= resolveSourceProvider(fMethodBinding, result);
	if (result.hasFatalError())
		return result;

	result.merge(fSourceProvider.checkActivation());
	if (result.hasFatalError())
		return result;

	fSourceProvider.initialize();
	fTargetProvider.initialize();

	pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
	RefactoringStatus searchStatus= new RefactoringStatus();
	String binaryRefsDescription= Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description , BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
	ReferencesInBinaryContext binaryRefs= new ReferencesInBinaryContext(binaryRefsDescription);
	ICompilationUnit[] units= fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
	binaryRefs.addErrorIfNecessary(searchStatus);

	if (searchStatus.hasFatalError()) {
		result.merge(searchStatus);
		return result;
	}
	IFile[] filesToBeModified= getFilesToBeModified(units);
	result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
	if (result.hasFatalError())
		return result;
	result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
	checkOverridden(result, new SubProgressMonitor(pm, 4));
	IProgressMonitor sub= new SubProgressMonitor(pm, 15);
	sub.beginTask("", units.length * 3); //$NON-NLS-1$
	for (int c= 0; c < units.length; c++) {
		ICompilationUnit unit= units[c];
		sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing,  BasicElementLabels.getFileName(unit)));
		CallInliner inliner= null;
		try {
			boolean added= false;
			MultiTextEdit root= new MultiTextEdit();
			CompilationUnitChange change= (CompilationUnitChange)fChangeManager.get(unit);
			change.setEdit(root);
			BodyDeclaration[] bodies= fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
			if (bodies.length == 0)
				continue;
			inliner= new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
			for (int b= 0; b < bodies.length; b++) {
				BodyDeclaration body= bodies[b];
				inliner.initialize(body);
				RefactoringStatus nestedInvocations= new RefactoringStatus();
				ASTNode[] invocations= removeNestedCalls(nestedInvocations, unit,
					fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
				for (int i= 0; i < invocations.length; i++) {
					ASTNode invocation= invocations[i];
					result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
					if (result.hasFatalError())
						break;
					if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
						added= true;
						TextEditGroup group= new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
						change.addTextEditGroup(group);
						result.merge(inliner.perform(group));
					}
				}
				// do this after we have inlined the method calls. We still want
				// to generate the modifications.
				result.merge(nestedInvocations);
			}
			if (!added) {
				fChangeManager.remove(unit);
			} else {
				root.addChild(inliner.getModifications());
				ImportRewrite rewrite= inliner.getImportEdit();
				if (rewrite.hasRecordedChanges()) {
					TextEdit edit= rewrite.rewriteImports(null);
					if (edit instanceof MultiTextEdit ? ((MultiTextEdit)edit).getChildrenSize() > 0 : true) {
						root.addChild(edit);
						change.addTextEditGroup(
							new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] {edit}));
					}
				}
			}
		} finally {
			if (inliner != null)
				inliner.dispose();
		}
		sub.worked(1);
		if (sub.isCanceled())
			throw new OperationCanceledException();
	}
	result.merge(searchStatus);
	sub.done();
	pm.done();
	return result;
}
 
Example 16
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
	 * Add all changes necessary on the <code>ICompilationUnit</code> in the given
	 * <code>SearchResultGroup</code> to implement the refactoring transformation
	 * to the given <code>CompilationUnitChange</code>.
	 * @param rg the <code>SearchResultGroup</code> for which changes should be created
	 * @param unitHandle
	 * @param unitChange the CompilationUnitChange object for the compilation unit in question
	 * @return <code>true</code> iff a change has been added
	 * @throws CoreException
	 */
	private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit	unitHandle, CompilationUnitChange unitChange) throws CoreException {
//		ICompilationUnit	unitHandle= rg.getCompilationUnit();
		Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
		CompilationUnit		unit= getASTFor(unitHandle);
		ASTRewrite			unitRewriter= ASTRewrite.create(unit.getAST());
		MultiTextEdit		root= new MultiTextEdit();
		boolean				someChange= false;

		unitChange.setEdit(root);
		fImportRewriter= StubUtility.createImportRewrite(unit, true);

		// First create the factory method
		if (unitHandle.equals(fFactoryUnitHandle)) {
			TextEditGroup	factoryGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);

			createFactoryChange(unitRewriter, unit, factoryGD);
			unitChange.addTextEditGroup(factoryGD);
			someChange= true;
		}

		// Now rewrite all the constructor calls to use the factory method
		if (rg != null)
			if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
				someChange= true;

		// Finally, make the constructor private, if requested.
		if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
			TextEditGroup	declGD= new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);

			if (protectConstructor(unit, unitRewriter, declGD)) {
				unitChange.addTextEditGroup(declGD);
				someChange= true;
			}
		}

		if (someChange) {
			root.addChild(unitRewriter.rewriteAST());
			root.addChild(fImportRewriter.rewriteImports(null));
		}

		return someChange;
	}
 
Example 17
Source File: UnimplementedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static IProposableFix createAddUnimplementedMethodsFix(final CompilationUnit root, IProblemLocation problem) {
	ASTNode typeNode= getSelectedTypeNode(root, problem);
	if (typeNode == null)
		return null;

	if (isTypeBindingNull(typeNode))
		return null;

	AddUnimplementedMethodsOperation operation= new AddUnimplementedMethodsOperation(typeNode);
	if (operation.getMethodsToImplement().length > 0) {
		return new UnimplementedCodeFix(CorrectionMessages.UnimplementedMethodsCorrectionProposal_description, root, new CompilationUnitRewriteOperation[] { operation });
	} else {
		return new IProposableFix() {
			public CompilationUnitChange createChange(IProgressMonitor progressMonitor) throws CoreException {
				CompilationUnitChange change= new CompilationUnitChange(CorrectionMessages.UnimplementedMethodsCorrectionProposal_description, (ICompilationUnit) root.getJavaElement()) {
					@Override
					public Change perform(IProgressMonitor pm) throws CoreException {
						Shell shell= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
						String dialogTitle= CorrectionMessages.UnimplementedMethodsCorrectionProposal_description;
						IStatus status= getStatus();
						ErrorDialog.openError(shell, dialogTitle, CorrectionMessages.UnimplementedCodeFix_DependenciesErrorMessage, status);

						return new NullChange();
					}
				};
				change.setEdit(new MultiTextEdit());
				return change;
			}

			public String getAdditionalProposalInfo() {
				return new String();
			}

			public String getDisplayString() {
				return CorrectionMessages.UnimplementedMethodsCorrectionProposal_description;
			}

			public IStatus getStatus() {
				return new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, CorrectionMessages.UnimplementedCodeFix_DependenciesStatusMessage);
			}
		};
	}
}
 
Example 18
Source File: CompilationUnitRewrite.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Creates a compilation unit change based on the events recorded by this compilation unit rewrite.
 * @param name the name of the change to create
 * @param generateGroups <code>true</code> to generate text edit groups, <code>false</code> otherwise
 * @param monitor the progress monitor or <code>null</code>
 * @return a {@link CompilationUnitChange}, or <code>null</code> for an empty change
 * @throws CoreException when text buffer acquisition or import rewrite text edit creation fails
 * @throws IllegalArgumentException when the AST rewrite encounters problems
 */
public CompilationUnitChange createChange(String name, boolean generateGroups, IProgressMonitor monitor) throws CoreException {
	CompilationUnitChange cuChange= new CompilationUnitChange(name, fCu);
	MultiTextEdit multiEdit= new MultiTextEdit();
	cuChange.setEdit(multiEdit);
	return attachChange(cuChange, generateGroups, monitor);
}