org.eclipse.ltk.core.refactoring.Change Java Examples

The following examples show how to use org.eclipse.ltk.core.refactoring.Change. 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: UpdateAcceptorTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test public void testAddTextEdit() throws Exception {

		updateAcceptor.accept(resourceURI0, new ReplaceEdit(0, 1, "foo"));
		updateAcceptor.accept(resourceURI1, new ReplaceEdit(1, 2, "bar"));
		updateAcceptor.accept(resourceURI0, new ReplaceEdit(3, 4, "baz"));

		Change change = updateAcceptor.createCompositeChange(CHANGE_NAME, new NullProgressMonitor());
		assertTrue(change instanceof CompositeChange);
		Change[] children = ((CompositeChange) change).getChildren();
		assertEquals(2, children.length);
		assertTrue(children[0] instanceof MockChange);
		MockChange change0 = (MockChange) children[0];
		assertEquals(CHANGE_NAME, change0.getName());
		assertTrue(children[1] instanceof MockChange);
		MockChange change1 = (MockChange) children[1];
		assertEquals(CHANGE_NAME, change1.getName());
		assertTrue(change0.getTextEdit() instanceof MultiTextEdit);
		assertTrue(change1.getTextEdit() instanceof MultiTextEdit);
		assertEquals(
				3,
				((MultiTextEdit) change0.getTextEdit()).getChildrenSize()
						+ ((MultiTextEdit) change1.getTextEdit()).getChildrenSize());
	}
 
Example #2
Source File: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm, INewNameQueries newNameQueries) throws JavaModelException {
	NewNameProposer nameProposer= new NewNameProposer();
	IPackageFragment[] fragments= getPackages();
	pm.beginTask("", fragments.length); //$NON-NLS-1$
	CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_copy_package);
	composite.markAsSynthetic();
	IPackageFragmentRoot root= getDestinationAsPackageFragmentRoot();
	for (int i= 0; i < fragments.length; i++) {
		if (root == null) {
			composite.add(createChange(fragments[i], (IContainer) getResourceDestination(), nameProposer, newNameQueries));
		} else {
			composite.add(createChange(fragments[i], root, nameProposer, newNameQueries));
		}
		pm.worked(1);
	}
	pm.done();
	return composite;
}
 
Example #3
Source File: CopyResourceChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	try{
		pm.beginTask(getName(), 2);

		String newName= getNewResourceName();
		IResource resource= getResource();
		boolean performReorg= deleteIfAlreadyExists(new SubProgressMonitor(pm, 1), newName);
		if (!performReorg)
			return null;

		getResource().copy(getDestinationPath(newName), getReorgFlags(), new SubProgressMonitor(pm, 1));

		markAsExecuted(resource);
		return null;
	} finally {
		pm.done();
	}
}
 
Example #4
Source File: TextChangeCombinerTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testMixedChanges() throws Exception {
	IFile file1 = IResourcesSetupUtil.createFile(PROJECT + "/file1.txt", MODEL);
	ITextEditor editor1 = openInEditor(file1);
	CompositeChange compositeChange = new CompositeChange("test");
	compositeChange.add(createEditorDocumentChange(editor1, 1, 1, "foo"));
	compositeChange.add(createTextFileChange(file0, 1, 1, "foo"));
	CompositeChange compositeChange1 = new CompositeChange("test");
	compositeChange.add(compositeChange1);
	compositeChange1.add(createEditorDocumentChange(editor1, 3, 1, "baz"));
	compositeChange1.add(createTextFileChange(file0, 1, 1, "foo"));
	compositeChange1.add(createTextFileChange(file0, 3, 1, "baz"));
	Change combined = combiner.combineChanges(compositeChange);
	Change undo = combined.perform(new NullProgressMonitor());
	IDocument document1 = getDocument(editor1);
	assertEquals(MODEL.replace("123", "foo2baz"), document1.get());
	assertEquals(MODEL.replace("123", "foo2baz"), getContents(file0));
	undo.perform(new NullProgressMonitor());
	assertEquals(MODEL, document1.get());
	assertEquals(MODEL, getContents(file0));
}
 
Example #5
Source File: PairedInterfaceRenameParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Ensures each compilation unit change in the tree rooted at the given change
 * will be wrapped with a
 * {@link com.google.gwt.eclipse.core.refactoring.regionupdater.RegionUpdaterChange}
 * to update text regions at change perform-time.
 */
private void weaveChange(Change change) {
  String oldName = typeContainer.getBaseType().getElementName();
  String newName = getTypeRefactoringSupport().getNewElement().getElementName();
  RenamedElementAstMatcher astMatcher = new RenamedElementAstMatcher(oldName,
      newName);

  String oldCuName = typeContainer.getBaseType().getCompilationUnit().getElementName();
  String newCuName = getTypeRefactoringSupport().getNewType().getCompilationUnit().getElementName();
  CompilationUnitRenamedReferenceUpdater cuValidator = new CompilationUnitRenamedReferenceUpdater(
      oldName, newName,
      oldCuName, newCuName);

  // Walk through the created change tree and weave a change that, at
  // perform-time, will update the text regions
  ChangeUtilities.acceptOnChange(change,
      new RegionUpdaterChangeWeavingVisitor(astMatcher, cuValidator));
}
 
Example #6
Source File: RenameJavaProjectProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public Change createChange(IProgressMonitor monitor) throws CoreException {
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		final String description= Messages.format(RefactoringCoreMessages.RenameJavaProjectProcessor_descriptor_description_short, BasicElementLabels.getJavaElementName(fProject.getElementName()));
		final String header= Messages.format(RefactoringCoreMessages.RenameJavaProjectChange_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fProject.getElementName()), BasicElementLabels.getJavaElementName(getNewElementName())});
		final String comment= new JDTRefactoringDescriptorComment(null, this, header).asString();
		final int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE | RefactoringDescriptor.BREAKING_CHANGE;
		final RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_JAVA_PROJECT);
		descriptor.setProject(null);
		descriptor.setDescription(description);
		descriptor.setComment(comment);
		descriptor.setFlags(flags);
		descriptor.setJavaElement(fProject);
		descriptor.setNewName(getNewElementName());
		descriptor.setUpdateReferences(fUpdateReferences);
		return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.RenameJavaProjectRefactoring_rename, new Change[] { new RenameJavaProjectChange(fProject, getNewElementName(), fUpdateReferences)});
	} finally {
		monitor.done();
	}
}
 
Example #7
Source File: ReplaceTypeCodeWithStateStrategy.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<Change> changes = new ArrayList<Change>();
		changes.addAll(compilationUnitChanges.values());
		changes.addAll(createCompilationUnitChanges.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 Type Code with State/Strategy in method ''{0}''", new Object[] { typeCheckElimination.getTypeCheckMethod().getName().getIdentifier()});
				String comment = null;
				return new RefactoringChangeDescriptor(new ReplaceTypeCodeWithStateStrategyDescriptor(project, description, comment,
						sourceFile, sourceCompilationUnit, sourceTypeDeclaration, typeCheckElimination));
			}
		};
		return change;
	} finally {
		pm.done();
	}
}
 
Example #8
Source File: RenamePackageProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Change postCreateChange(Change[] participantChanges, IProgressMonitor pm) throws CoreException {
	if (fQualifiedNameSearchResult != null) {
		CompositeChange parent= (CompositeChange) fRenamePackageChange.getParent();
		try {
			/*
			 * Sneak text changes in before the package rename to ensure
			 * modified files are still at original location (see
			 * https://bugs.eclipse.org/bugs/show_bug.cgi?id=154238)
			 */
			parent.remove(fRenamePackageChange);
			parent.add(fQualifiedNameSearchResult.getSingleChange(Changes.getModifiedFiles(participantChanges)));
		} finally {
			fQualifiedNameSearchResult= null;
			parent.add(fRenamePackageChange);
			fRenamePackageChange= null;
		}
	}
	return null;
}
 
Example #9
Source File: CopyResourceChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	try{
		pm.beginTask(getName(), 2);

		String newName= getNewResourceName();
		IResource resource= getResource();
		boolean performReorg= deleteIfAlreadyExists(new SubProgressMonitor(pm, 1), newName);
		if (!performReorg) {
			return null;
		}

		getResource().copy(getDestinationPath(newName), getReorgFlags(), new SubProgressMonitor(pm, 1));

		markAsExecuted(resource);
		return null;
	} finally {
		pm.done();
	}
}
 
Example #10
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 #11
Source File: AbstractJavaElementRenameChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public final Change perform(IProgressMonitor pm) throws CoreException {
	try {
		pm.beginTask(RefactoringCoreMessages.AbstractRenameChange_Renaming, 1);
		IResource resource= getResource();
		IPath newPath= createNewPath();
		Change result= createUndoChange(resource.getModificationStamp());
		doRename(new SubProgressMonitor(pm, 1));
		if (fStampToRestore != IResource.NULL_STAMP) {
			IResource newResource= ResourcesPlugin.getWorkspace().getRoot().findMember(newPath);
			newResource.revertModificationStamp(fStampToRestore);
		}
		return result;
	} finally {
		pm.done();
	}
}
 
Example #12
Source File: ReorgPolicyFactory.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public Change createChange(IProgressMonitor pm) throws JavaModelException {
	IPackageFragmentRoot[] roots= getPackageFragmentRoots();
	pm.beginTask("", roots.length); //$NON-NLS-1$
	CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.ReorgPolicy_move_source_folder);
	composite.markAsSynthetic();
	IJavaProject destination= getDestinationJavaProject();
	for (int i= 0; i < roots.length; i++) {
		if (destination == null) {
			composite.add(new MovePackageFragmentRootChange(roots[i], (IContainer) getResourceDestination(), null));
		} else {
			composite.add(createChange(roots[i], destination));
		}
		pm.worked(1);
	}
	pm.done();
	return composite;
}
 
Example #13
Source File: DeleteChangeCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Change createPackageFragmentRootDeleteChange(IPackageFragmentRoot root) throws JavaModelException {
	IResource resource= root.getResource();
	if (resource != null && resource.isLinked()){
		//XXX using this code is a workaround for jcore bug 31998
		//jcore cannot handle linked stuff
		//normally, we should always create DeletePackageFragmentRootChange
		CompositeChange composite= new DynamicValidationStateChange(RefactoringCoreMessages.DeleteRefactoring_delete_package_fragment_root);

		ClasspathChange change= ClasspathChange.removeEntryChange(root.getJavaProject(), root.getRawClasspathEntry());
		if (change != null) {
			composite.add(change);
		}
		Assert.isTrue(! Checks.isClasspathDelete(root));//checked in preconditions
		composite.add(createDeleteChange(resource));

		return composite;
	} else {
		Assert.isTrue(! root.isExternal());
		// TODO remove the query argument
		return new DeletePackageFragmentRootChange(root, true, null);
	}
}
 
Example #14
Source File: ReplaceFileContentChange.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Change perform(IProgressMonitor pm) throws CoreException {
	byte[] oldContents = getOldContents();
	Change change = null;
	try (ByteArrayInputStream newContentsIS = new ByteArrayInputStream(newContents)) {
		file.setContents(newContentsIS, true, true, pm);
		change = new ReplaceFileContentChange(file, oldContents);
	} catch (IOException e) {
		LOG.error("Error closing stream", e);
	}
	return change;
}
 
Example #15
Source File: DeleteSourceManipulationChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Change doDelete(IProgressMonitor pm) throws CoreException {
	ISourceManipulation element= getSourceManipulation();
	// we have to save dirty compilation units before deleting them. Otherwise
	// we will end up showing ghost compilation units in the package explorer
	// since the primary working copy still exists.
	if (element instanceof ICompilationUnit) {
		pm.beginTask("", 2); //$NON-NLS-1$
		ICompilationUnit unit= (ICompilationUnit)element;
		saveCUnitIfNeeded(unit, new SubProgressMonitor(pm, 1));

		IResource resource= unit.getResource();
		//			ResourceDescription resourceDescription = ResourceDescription.fromResource(resource);
		//			element.delete(false, new SubProgressMonitor(pm, 1));
		//			resourceDescription.recordStateFromHistory(resource, new SubProgressMonitor(pm, 1));
		return new UndoDeleteResourceChange(ResourceUndoState.fromResource(resource));

	} else if (element instanceof IPackageFragment) {
		ICompilationUnit[] units= ((IPackageFragment)element).getCompilationUnits();
		pm.beginTask("", units.length + 1); //$NON-NLS-1$
		for (int i = 0; i < units.length; i++) {
			// fix https://bugs.eclipse.org/bugs/show_bug.cgi?id=66835
			saveCUnitIfNeeded(units[i], new SubProgressMonitor(pm, 1));
		}
		element.delete(false, new SubProgressMonitor(pm, 1));
		return new NullChange(); // caveat: real undo implemented by UndoablePackageDeleteChange

	} else {
		element.delete(false, pm);
		return null; //should not happen
	}
}
 
Example #16
Source File: ChangeUtil.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void convertSingleChange(Change change, WorkspaceEdit edit) throws CoreException {
	if (change instanceof CompositeChange) {
		return;
	}

	if (change instanceof TextChange) {
		convertTextChange((TextChange) change, edit);
	} else if (change instanceof ResourceChange) {
		convertResourceChange((ResourceChange) change, edit);
	}
}
 
Example #17
Source File: ArtifactProjectDeleteParticipant.java    From developer-studio with Apache License 2.0 5 votes vote down vote up
/**
 * This method gets executed before the refactoring gets executed on
 * original file which means this method is executed before the actual
 * project is deleted from the workspace. If you have any task need to run
 * before the project is deleted, you need to generate Changes for those
 * tasks in this method.
 */
@Override
public Change createPreChange(IProgressMonitor arg0) throws CoreException, OperationCanceledException {

	CompositeChange deleteChange = new CompositeChange("Delete Artifact Project");

	IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();

	for (IProject project : projects) {
		if (project.isOpen() && project.hasNature("org.wso2.developerstudio.eclipse.distribution.project.nature")) {
			try {
				IFile pomFile = project.getFile(POM_XML);
				MavenProject mavenProject = ProjectRefactorUtils.getMavenProject(project);
				Dependency projectDependency = ProjectRefactorUtils.getDependencyForTheProject(originalProject);
				if (mavenProject != null) {
					List<?> dependencies = mavenProject.getDependencies();
					if (projectDependency != null) {
						for (Iterator<?> iterator = dependencies.iterator(); iterator.hasNext();) {
							Dependency dependency = (Dependency) iterator.next();
							if (ProjectRefactorUtils.isDependenciesEqual(projectDependency, dependency)) {
								deleteChange.add(new MavenConfigurationFileDeleteChange(project.getName(), pomFile,
								                                                        originalProject));
							}
						}
					}
				}
			} catch (Exception e) {
				log.error("Error occured while trying to generate the Refactoring", e);
			}
		}
	}

	return deleteChange;
}
 
Example #18
Source File: DisplayChangeWrapperTest.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Test 
public void testNullChange() throws CoreException {
	Change change = new NullChange("my change");
	Change wrapped = DisplayChangeWrapper.wrap(change);
	assertFalse(wrapped instanceof TextEditBasedChange);
	assertTrue(wrapped instanceof DisplayChangeWrapper.Wrapper);
	assertEquals(change, ((DisplayChangeWrapper.Wrapper) wrapped).getDelegate());
	Change undo = wrapped.perform(new NullProgressMonitor());
	assertTrue(undo instanceof DisplayChangeWrapper.Wrapper);
}
 
Example #19
Source File: ChangeUtilities.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Visits the given change and all its descendents.
 */
public static void acceptOnChange(Change change, ChangeVisitor visitor) {
  if (change instanceof CompositeChange) {
    CompositeChange compositeChange = (CompositeChange) change;
    for (Change curChange : compositeChange.getChildren()) {
      acceptOnChange(curChange, visitor);
    }
  }

  visitor.visit(change);
}
 
Example #20
Source File: ExtractVariableRefactoring.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	TextEdit textEdit = replaceConverter.convertToTextEdit(rewriter.getChanges());
	EditorDocumentChange change = new EditorDocumentChange("Extract local variable", editor, false);
	change.setEdit(textEdit);
	change.setTextType(resourceURI.fileExtension());
	return change;
}
 
Example #21
Source File: DeleteChangeCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Change createDeleteChange(IJavaElement javaElement) throws JavaModelException {
	Assert.isTrue(! ReorgUtils.isInsideCompilationUnit(javaElement));

	switch(javaElement.getElementType()){
		case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			return createPackageFragmentRootDeleteChange((IPackageFragmentRoot)javaElement);

		case IJavaElement.PACKAGE_FRAGMENT:
			return createSourceManipulationDeleteChange((IPackageFragment)javaElement);

		case IJavaElement.COMPILATION_UNIT:
			return createSourceManipulationDeleteChange((ICompilationUnit)javaElement);

		case IJavaElement.CLASS_FILE:
			//if this assert fails, it means that a precondition is missing
			Assert.isTrue(((IClassFile)javaElement).getResource() instanceof IFile);
			return createDeleteChange(((IClassFile)javaElement).getResource());

		case IJavaElement.JAVA_MODEL: //cannot be done
			Assert.isTrue(false);
			return null;

		case IJavaElement.JAVA_PROJECT: //handled differently
			Assert.isTrue(false);
			return null;

		case IJavaElement.TYPE:
		case IJavaElement.FIELD:
		case IJavaElement.METHOD:
		case IJavaElement.INITIALIZER:
		case IJavaElement.PACKAGE_DECLARATION:
		case IJavaElement.IMPORT_CONTAINER:
		case IJavaElement.IMPORT_DECLARATION:
			Assert.isTrue(false);//not done here
			return new NullChange();
		default:
			Assert.isTrue(false);//there's no more kinds
			return new NullChange();
	}
}
 
Example #22
Source File: PackageFragmentRootReorgChange.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public final Change perform(IProgressMonitor pm) throws CoreException, OperationCanceledException {
	pm.beginTask(getName(), 2);
	try {
		String newName= getNewResourceName();
		IPackageFragmentRoot root= getRoot();
		ResourceMapping mapping= JavaElementResourceMapping.create(root);
		final Change result= doPerformReorg(getDestinationProjectPath().append(newName), new SubProgressMonitor(pm, 1));
		markAsExecuted(root, mapping);
		return result;
	} finally {
		pm.done();
	}
}
 
Example #23
Source File: AbstractPythonRefactoring.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Change createChange(IProgressMonitor pm) {
    IChangeProcessor changeProcessor = new CompositeChangeProcessor(getName(), getChangeProcessors());

    try {
        return changeProcessor.createChange();
    } catch (MisconfigurationException e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: DynamicValidationStateChange.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void workspaceChanged() {
	long currentTime = System.currentTimeMillis();
	if (currentTime - fTimeStamp < LIFE_TIME) {
		return;
	}
	fValidationState = RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.DynamicValidationStateChange_workspace_changed);
	// remove listener from workspace tracker
	WorkspaceTracker.INSTANCE.removeListener(this);
	fListenerRegistered = false;
	// clear up the children to not hang onto too much memory
	Change[] children = clear();
	for (int i = 0; i < children.length; i++) {
		final Change change = children[i];
		SafeRunner.run(new ISafeRunnable() {
			@Override
			public void run() throws Exception {
				change.dispose();
			}

			@Override
			public void handleException(Throwable exception) {
				JavaLanguageServerPlugin.logException("Exception happened inside DynamicValidationStateChange: ", exception);
			}
		});
	}
}
 
Example #25
Source File: ChangeBuilder.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a change (or returns a previously created change).
 */
public Change createChange() throws RefactoringException {
  if (change != null) {
    return change;
  }

  if (refactoring == null) {
    refactoring = createRefactoring();
  }

  change = ChangeUtilities.createChange(workspace,
      new NullProgressMonitor(), refactoring, RefactoringStatus.FATAL);

  return change;
}
 
Example #26
Source File: DefaultRefactoringDocumentProvider.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Change createChange(String name, TextEdit textEdit) {
	EditorDocumentChange documentChange = new EditorDocumentChange(getName(), editor, doSave);
	documentChange.setEdit(textEdit);
	documentChange.setTextType(getURI().fileExtension());
	return documentChange;
}
 
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: ReorgPolicyFactory.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private Change createChange(IPackageFragmentRoot root, IContainer destination, NewNameProposer nameProposer, INewNameQueries copyQueries) {
	IResource res= root.getResource();

	String newName= nameProposer.createNewName(res, destination);
	INewNameQuery nameQuery;
	if (newName == null) {
		nameQuery= copyQueries.createNullQuery();
	} else {
		nameQuery= copyQueries.createNewResourceNameQuery(res, newName);
	}

	return new CopyResourceChange(res, destination, nameQuery);
}
 
Example #29
Source File: DisplayChangeWrapper.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
public static Change wrap(Change delegate) {
	if(delegate instanceof TextEditBasedChange) {
		return new TextEditBased((TextEditBasedChange) delegate);
	} else if (delegate != null) {
		return new Generic(delegate);
	} else {
		return null;
	}
}
 
Example #30
Source File: DeleteChangeCreator.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static Change createDeleteChange(IJavaElement javaElement) throws JavaModelException {
	Assert.isTrue(! ReorgUtils.isInsideCompilationUnit(javaElement));

	switch(javaElement.getElementType()){
		case IJavaElement.PACKAGE_FRAGMENT_ROOT:
			return createPackageFragmentRootDeleteChange((IPackageFragmentRoot)javaElement);

		case IJavaElement.PACKAGE_FRAGMENT:
			return createSourceManipulationDeleteChange((IPackageFragment)javaElement);

		case IJavaElement.COMPILATION_UNIT:
			return createSourceManipulationDeleteChange((ICompilationUnit)javaElement);

		case IJavaElement.CLASS_FILE:
			//if this assert fails, it means that a precondition is missing
			Assert.isTrue(((IClassFile)javaElement).getResource() instanceof IFile);
			return createDeleteChange(((IClassFile)javaElement).getResource());

		case IJavaElement.JAVA_MODEL: //cannot be done
			Assert.isTrue(false);
			return null;

		case IJavaElement.JAVA_PROJECT: //handled differently
			Assert.isTrue(false);
			return null;

		case IJavaElement.TYPE:
		case IJavaElement.FIELD:
		case IJavaElement.METHOD:
		case IJavaElement.INITIALIZER:
		case IJavaElement.PACKAGE_DECLARATION:
		case IJavaElement.IMPORT_CONTAINER:
		case IJavaElement.IMPORT_DECLARATION:
			Assert.isTrue(false);//not done here
			return new NullChange();
		default:
			Assert.isTrue(false);//there's no more kinds
			return new NullChange();
	}
}