下面列出了怎么用org.eclipse.lsp4j.ResourceOperation的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Makes a CodeAction to create a file and add content to the file.
*
* @param title The displayed name of the CodeAction
* @param docURI The file to create
* @param content The text to put into the newly created document.
* @param diagnostic The diagnostic that this CodeAction will fix
*/
public static CodeAction createFile(String title, String docURI, String content, Diagnostic diagnostic) {
List<Either<TextDocumentEdit, ResourceOperation>> actionsToTake = new ArrayList<>(2);
// 1. create an empty file
actionsToTake.add(Either.forRight(new CreateFile(docURI, new CreateFileOptions(false, true))));
// 2. update the created file with the given content
VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(docURI, 0);
TextEdit te = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), content);
actionsToTake.add(Either.forLeft(new TextDocumentEdit(identifier, Collections.singletonList(te))));
WorkspaceEdit createAndAddContentEdit = new WorkspaceEdit(actionsToTake);
CodeAction codeAction = new CodeAction(title);
codeAction.setEdit(createAndAddContentEdit);
codeAction.setDiagnostics(Collections.singletonList(diagnostic));
codeAction.setKind(CodeActionKind.QuickFix);
return codeAction;
}
/**
* Converts changes to resource operations if resource operations are supported
* by the client otherwise converts to TextEdit changes.
*
* @param resourceChange
* resource changes after Refactoring operation
* @param edit
* instance of workspace edit changes
* @throws CoreException
*/
private static void convertResourceChange(ResourceChange resourceChange, WorkspaceEdit edit) throws CoreException {
if (!JavaLanguageServerPlugin.getPreferencesManager().getClientPreferences().isResourceOperationSupported()) {
return;
}
List<Either<TextDocumentEdit, ResourceOperation>> changes = edit.getDocumentChanges();
if (changes == null) {
changes = new ArrayList<>();
edit.setDocumentChanges(changes);
}
// Resource change is needed and supported by client
if (resourceChange instanceof RenameCompilationUnitChange) {
convertCUResourceChange(edit, (RenameCompilationUnitChange) resourceChange);
} else if (resourceChange instanceof RenamePackageChange) {
convertRenamePackcageChange(edit, (RenamePackageChange) resourceChange);
} else if (resourceChange instanceof MoveCompilationUnitChange) {
convertMoveCompilationUnitChange(edit, (MoveCompilationUnitChange) resourceChange);
} else if (resourceChange instanceof CreateFileChange) {
convertCreateFileChange(edit, (CreateFileChange) resourceChange);
} else if (resourceChange instanceof CreateCompilationUnitChange) {
convertCreateCompilationUnitChange(edit, (CreateCompilationUnitChange) resourceChange);
}
}
@Test
public void testConvertRenameCompilationUnitChange() throws CoreException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
String newName = "ENew.java";
RenameCompilationUnitChange change = new RenameCompilationUnitChange(cu, newName);
String oldUri = JDTUtils.toURI(cu);
String newUri = ResourceUtils.fixURI(URI.create(oldUri).resolve(newName));
WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
assertEquals(edit.getDocumentChanges().size(), 1);
ResourceOperation resourceOperation = edit.getDocumentChanges().get(0).getRight();
assertTrue(resourceOperation instanceof RenameFile);
assertEquals(((RenameFile) resourceOperation).getOldUri(), oldUri);
assertEquals(((RenameFile) resourceOperation).getNewUri(), newUri);
}
@Override
public ResourceOperation read(JsonReader in) throws IOException {
JsonObject objectJson = new JsonParser().parse(in).getAsJsonObject();
JsonElement value = objectJson.get("kind");
if (value != null && value.isJsonPrimitive()) {
String kindValue = value.getAsString();
if (ResourceOperationKind.Create.equals(kindValue)) {
return createFileAdapter.fromJsonTree(objectJson);
} else if (ResourceOperationKind.Delete.equals(kindValue)) {
return deleteFileAdapter.fromJsonTree(objectJson);
} else if (ResourceOperationKind.Rename.equals(kindValue)) {
return renameFileAdapter.fromJsonTree(objectJson);
}
}
throw new JsonParseException(
"The ResourceOperation object either has null \"kind\" value or the \"kind\" value is not valid.");
}
public static CodeAction ca(Diagnostic d, Either<TextDocumentEdit, ResourceOperation>... ops) {
CodeAction codeAction = new CodeAction();
codeAction.setDiagnostics(Collections.singletonList(d));
codeAction.setEdit(new WorkspaceEdit(Arrays.asList(ops)));
codeAction.setTitle("");
return codeAction;
}
/** @return string for given element */
public String toString6(Either<TextDocumentEdit, ResourceOperation> documentChanges) {
if (documentChanges == null) {
return "";
}
if (documentChanges.isLeft()) {
return toString(documentChanges.getLeft());
} else {
return toString(documentChanges.getRight());
}
}
/** @return string for given element */
public String toString(ResourceOperation operation) {
if (operation == null) {
return "";
}
return operation.getKind();
}
@Test(expected = ResponseErrorException.class)
public void testRenameTypeWithErrors() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes = { "package test1;\n",
"public class Newname {\n",
" }\n",
"}\n" };
StringBuilder builder = new StringBuilder();
mergeCode(builder, codes);
ICompilationUnit cu = pack1.createCompilationUnit("Newname.java", builder.toString(), false, null);
String[] codes1 = { "package test1;\n",
"public class E|* {\n",
" public E() {\n",
" }\n",
" public int bar() {\n", " }\n",
" public int foo() {\n",
" this.bar();\n",
" }\n",
"}\n" };
builder = new StringBuilder();
Position pos = mergeCode(builder, codes1);
cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);
WorkspaceEdit edit = getRenameEdit(cu, pos, "Newname");
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> resourceChanges = edit.getDocumentChanges();
assertEquals(resourceChanges.size(), 3);
}
private void assertRenameFileOperation(Either<Command, CodeAction> codeAction, String newUri) {
WorkspaceEdit edit = getWorkspaceEdit(codeAction);
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = edit.getDocumentChanges();
assertNotNull(documentChanges);
assertEquals(1, documentChanges.size());
ResourceOperation resourceOperation = documentChanges.get(0).getRight();
assertNotNull(resourceOperation);
assertTrue(resourceOperation instanceof RenameFile);
assertEquals(newUri, ((RenameFile) resourceOperation).getNewUri());
}
private String evaluateChanges(List<Either<TextDocumentEdit, ResourceOperation>> documentChanges) throws BadLocationException, JavaModelException {
List<TextDocumentEdit> changes = documentChanges.stream().filter(e -> e.isLeft()).map(e -> e.getLeft()).collect(Collectors.toList());
assertFalse("No edits generated", changes.isEmpty());
Set<String> uris = changes.stream().map(tde -> tde.getTextDocument().getUri()).distinct().collect(Collectors.toSet());
assertEquals("Only one resource should be modified", 1, uris.size());
String uri = uris.iterator().next();
List<TextEdit> edits = changes.stream().flatMap(e -> e.getEdits().stream()).collect(Collectors.toList());
return evaluateChanges(uri, edits);
}
protected String _toExpectation(final ResourceOperation it) {
StringConcatenation _builder = new StringConcatenation();
_builder.append("kind : ");
String _kind = it.getKind();
_builder.append(_kind);
_builder.newLineIfNotEmpty();
return _builder.toString();
}
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
Predicate<JsonElement> leftChecker = new PropertyChecker("textDocument").and(new PropertyChecker("edits"));
Predicate<JsonElement> rightChecker = new PropertyChecker("kind");
TypeAdapter<Either<TextDocumentEdit, ResourceOperation>> elementTypeAdapter = new EitherTypeAdapter<>(gson,
ELEMENT_TYPE, leftChecker, rightChecker);
return (TypeAdapter<T>) new CollectionTypeAdapter<>(gson, ELEMENT_TYPE.getType(), elementTypeAdapter, ArrayList::new);
}
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ResourceOperation.class.isAssignableFrom(type.getRawType())) {
return null;
}
return (TypeAdapter<T>) new InnerResourceOperationTypeAdapter(this, gson).nullSafe();
}
@Override
public void write(JsonWriter out, ResourceOperation value) throws IOException {
if (value.getClass().isAssignableFrom(CreateFile.class)) {
createFileAdapter.write(out, (CreateFile) value);
} else if (value.getClass().isAssignableFrom(DeleteFile.class)) {
deleteFileAdapter.write(out, (DeleteFile) value);
} else if (value.getClass().isAssignableFrom(RenameFile.class)) {
renameFileAdapter.write(out, (RenameFile) value);
}
}
public static Either<TextDocumentEdit, ResourceOperation> createFile(String uri, boolean overwrite) {
CreateFileOptions options = new CreateFileOptions();
options.setIgnoreIfExists(!overwrite);
options.setOverwrite(overwrite);
return Either.forRight(new CreateFile(uri, options));
}
public static Either<TextDocumentEdit, ResourceOperation> teOp(String uri, int startLine, int startChar,
int endLine, int endChar, String newText) {
return Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(uri, 0),
Collections.singletonList(te(startLine, startChar, endLine, endChar, newText))));
}
@Test
public void testMergeChanges() {
WorkspaceEdit editA = new WorkspaceEdit();
String uriA = "uriA";
TextEdit textEdit = new TextEdit(
new Range(new Position(0, 0), new Position(0, 0)),
"package test;");
editA.getChanges().put(uriA, Arrays.asList(textEdit));
WorkspaceEdit root = ChangeUtil.mergeChanges(null, editA);
assertNotNull(root);
assertNotNull(root.getChanges());
assertNotNull(root.getChanges().get(uriA));
assertEquals(1, root.getChanges().size());
assertEquals(1, root.getChanges().get(uriA).size());
WorkspaceEdit editB = new WorkspaceEdit();
editB.getChanges().put(uriA, Arrays.asList(textEdit));
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = new ArrayList<>();
TextDocumentEdit textDocumentEdit = new TextDocumentEdit(
new VersionedTextDocumentIdentifier(uriA, 1), Arrays.asList(textEdit));
documentChanges.add(Either.forLeft(textDocumentEdit));
ResourceOperation resourceOperation = new RenameFile("uriA", "uriB");
documentChanges.add(Either.forRight(resourceOperation));
editB.setDocumentChanges(documentChanges);
root = ChangeUtil.mergeChanges(editA, editB);
assertNotNull(root);
assertNotNull(root.getChanges());
assertNotNull(root.getChanges().get(uriA));
assertEquals(1, root.getChanges().size());
assertEquals(2, root.getChanges().get(uriA).size());
assertNotNull(root.getDocumentChanges());
assertEquals(2, root.getDocumentChanges().size());
assertTrue(root.getDocumentChanges().get(0).isLeft());
assertEquals(textDocumentEdit, root.getDocumentChanges().get(0).getLeft());
assertTrue(root.getDocumentChanges().get(1).isRight());
assertEquals(resourceOperation, root.getDocumentChanges().get(1).getRight());
root = ChangeUtil.mergeChanges(editA, editB, true);
assertNotNull(root);
assertNotNull(root.getChanges());
assertNotNull(root.getChanges().get(uriA));
assertEquals(1, root.getChanges().size());
assertEquals(2, root.getChanges().get(uriA).size());
assertNotNull(root.getDocumentChanges());
assertEquals(1, root.getDocumentChanges().size());
assertTrue(root.getDocumentChanges().get(0).isLeft());
assertEquals(textDocumentEdit, root.getDocumentChanges().get(0).getLeft());
}
@Test
public void testRenamePackage() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("parent.pack1", false, null);
IPackageFragment pack2 = sourceFolder.createPackageFragment("parent.pack2", false, null);
StringBuilder codeA = new StringBuilder();
codeA.append("package parent.pack1;\n");
codeA.append("import parent.pack2.B;\n");
codeA.append("public class A {\n");
codeA.append(" public void foo() {\n");
codeA.append(" B b = new B();\n");
codeA.append(" b.foo();\n");
codeA.append(" }\n");
codeA.append("}\n");
StringBuilder codeB = new StringBuilder();
codeB.append("package parent.pack2;\n");
codeB.append("public class B {\n");
codeB.append(" public B() {}\n");
codeB.append(" public void foo() {}\n");
codeB.append("}\n");
ICompilationUnit cuA = pack1.createCompilationUnit("A.java", codeA.toString(), false, null);
ICompilationUnit cuB = pack2.createCompilationUnit("B.java", codeB.toString(), false, null);
String pack2Uri = JDTUtils.getFileURI(pack2.getResource());
String newPack2Uri = pack2Uri.replace("pack2", "newpack2");
WorkspaceEdit edit = FileEventHandler.handleWillRenameFiles(new FileRenameParams(Arrays.asList(new FileRenameEvent(pack2Uri, newPack2Uri))), new NullProgressMonitor());
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = edit.getDocumentChanges();
assertEquals(2, documentChanges.size());
assertTrue(documentChanges.get(0).isLeft());
assertEquals(documentChanges.get(0).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuA));
assertEquals(TextEditUtil.apply(codeA.toString(), documentChanges.get(0).getLeft().getEdits()),
"package parent.pack1;\n" +
"import parent.newpack2.B;\n" +
"public class A {\n" +
" public void foo() {\n" +
" B b = new B();\n" +
" b.foo();\n" +
" }\n" +
"}\n"
);
assertTrue(documentChanges.get(1).isLeft());
assertEquals(documentChanges.get(1).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuB));
assertEquals(TextEditUtil.apply(codeB.toString(), documentChanges.get(1).getLeft().getEdits()),
"package parent.newpack2;\n" +
"public class B {\n" +
" public B() {}\n" +
" public void foo() {}\n" +
"}\n"
);
}
@Test
public void testRenameSubPackage() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment parentPack = sourceFolder.createPackageFragment("parent", false, null);
IPackageFragment pack1 = sourceFolder.createPackageFragment("parent.pack1", false, null);
IPackageFragment pack2 = sourceFolder.createPackageFragment("parent.pack2", false, null);
StringBuilder codeA = new StringBuilder();
codeA.append("package parent.pack1;\n");
codeA.append("import parent.pack2.B;\n");
codeA.append("public class A {\n");
codeA.append(" public void foo() {\n");
codeA.append(" B b = new B();\n");
codeA.append(" b.foo();\n");
codeA.append(" }\n");
codeA.append("}\n");
StringBuilder codeB = new StringBuilder();
codeB.append("package parent.pack2;\n");
codeB.append("public class B {\n");
codeB.append(" public B() {}\n");
codeB.append(" public void foo() {}\n");
codeB.append("}\n");
ICompilationUnit cuA = pack1.createCompilationUnit("A.java", codeA.toString(), false, null);
ICompilationUnit cuB = pack2.createCompilationUnit("B.java", codeB.toString(), false, null);
String parentPackUri = JDTUtils.getFileURI(parentPack.getResource());
String newParentPackUri = parentPackUri.replace("parent", "newparent");
WorkspaceEdit edit = FileEventHandler.handleWillRenameFiles(new FileRenameParams(Arrays.asList(new FileRenameEvent(parentPackUri, newParentPackUri))), new NullProgressMonitor());
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> documentChanges = edit.getDocumentChanges();
assertEquals(3, documentChanges.size());
assertTrue(documentChanges.get(0).isLeft());
assertEquals(documentChanges.get(0).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuA));
assertTrue(documentChanges.get(1).isLeft());
assertEquals(documentChanges.get(1).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuA));
List<TextEdit> edits = new ArrayList<>();
edits.addAll(documentChanges.get(0).getLeft().getEdits());
edits.addAll(documentChanges.get(1).getLeft().getEdits());
assertEquals(TextEditUtil.apply(codeA.toString(), edits),
"package newparent.pack1;\n" +
"import newparent.pack2.B;\n" +
"public class A {\n" +
" public void foo() {\n" +
" B b = new B();\n" +
" b.foo();\n" +
" }\n" +
"}\n"
);
assertTrue(documentChanges.get(2).isLeft());
assertEquals(documentChanges.get(2).getLeft().getTextDocument().getUri(), JDTUtils.toURI(cuB));
assertEquals(TextEditUtil.apply(codeB.toString(), documentChanges.get(2).getLeft().getEdits()),
"package newparent.pack2;\n" +
"public class B {\n" +
" public B() {}\n" +
" public void foo() {}\n" +
"}\n"
);
}
@Test
public void testRenameTypeWithResourceChanges() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
String[] codes = { "package test1;\n",
"public class E|* {\n",
" public E() {\n",
" }\n",
" public int bar() {\n", " }\n",
" public int foo() {\n",
" this.bar();\n",
" }\n",
"}\n" };
StringBuilder builder = new StringBuilder();
Position pos = mergeCode(builder, codes);
ICompilationUnit cu = pack1.createCompilationUnit("E.java", builder.toString(), false, null);
WorkspaceEdit edit = getRenameEdit(cu, pos, "Newname");
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> resourceChanges = edit.getDocumentChanges();
assertEquals(resourceChanges.size(), 2);
Either<TextDocumentEdit, ResourceOperation> change = resourceChanges.get(1);
RenameFile resourceChange = (RenameFile) change.getRight();
assertEquals(JDTUtils.toURI(cu), resourceChange.getOldUri());
assertEquals(JDTUtils.toURI(cu).replaceFirst("(?s)E(?!.*?E)", "Newname"), resourceChange.getNewUri());
List<TextEdit> testChanges = new LinkedList<>();
testChanges.addAll(resourceChanges.get(0).getLeft().getEdits());
String expected = "package test1;\n" +
"public class Newname {\n" +
" public Newname() {\n" +
" }\n" +
" public int bar() {\n" +
" }\n" +
" public int foo() {\n" +
" this.bar();\n" +
" }\n" +
"}\n";
assertEquals(expected, TextEditUtil.apply(builder.toString(), testChanges));
}
@Test
public void testRenamePackage() throws JavaModelException, BadLocationException {
when(clientPreferences.isResourceOperationSupported()).thenReturn(true);
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
IPackageFragment pack2 = sourceFolder.createPackageFragment("parent.test2", false, null);
String[] codes1= {
"package test1;\n",
"import parent.test2.B;\n",
"public class A {\n",
" public void foo(){\n",
" B b = new B();\n",
" b.foo();\n",
" }\n",
"}\n"
};
String[] codes2 = {
"package parent.test2|*;\n",
"public class B {\n",
" public B() {}\n",
" public void foo() {}\n",
"}\n"
};
StringBuilder builderA = new StringBuilder();
mergeCode(builderA, codes1);
ICompilationUnit cuA = pack1.createCompilationUnit("A.java", builderA.toString(), false, null);
StringBuilder builderB = new StringBuilder();
Position pos = mergeCode(builderB, codes2);
ICompilationUnit cuB = pack2.createCompilationUnit("B.java", builderB.toString(), false, null);
WorkspaceEdit edit = getRenameEdit(cuB, pos, "parent.newpackage");
assertNotNull(edit);
List<Either<TextDocumentEdit, ResourceOperation>> resourceChanges = edit.getDocumentChanges();
assertEquals(5, resourceChanges.size());
List<TextEdit> testChangesA = new LinkedList<>();
testChangesA.addAll(resourceChanges.get(0).getLeft().getEdits());
List<TextEdit> testChangesB = new LinkedList<>();
testChangesB.addAll(resourceChanges.get(1).getLeft().getEdits());
String expectedA =
"package test1;\n" +
"import parent.newpackage.B;\n" +
"public class A {\n" +
" public void foo(){\n" +
" B b = new B();\n" +
" b.foo();\n" +
" }\n" +
"}\n";
String expectedB =
"package parent.newpackage;\n" +
"public class B {\n" +
" public B() {}\n" +
" public void foo() {}\n" +
"}\n";
assertEquals(expectedA, TextEditUtil.apply(builderA.toString(), testChangesA));
assertEquals(expectedB, TextEditUtil.apply(builderB.toString(), testChangesB));
//moved package
CreateFile resourceChange = (CreateFile) resourceChanges.get(2).getRight();
assertEquals(ResourceUtils.fixURI(pack2.getResource().getRawLocationURI()).replaceFirst("test2[/]?", "newpackage/.temp"), resourceChange.getUri());
//moved class B
RenameFile resourceChange2 = (RenameFile) resourceChanges.get(3).getRight();
assertEquals(ResourceUtils.fixURI(cuB.getResource().getRawLocationURI()), resourceChange2.getOldUri());
assertEquals(ResourceUtils.fixURI(cuB.getResource().getRawLocationURI()).replace("test2", "newpackage"), resourceChange2.getNewUri());
}
@Test
public void testMoveFile() throws JavaModelException, BadLocationException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("jdtls.test1", false, null);
//@formatter:off
ICompilationUnit unitA = pack1.createCompilationUnit("A.java", "package jdtls.test1;\r\n" +
"import jdtls.test2.B;\r\n" +
"\r\n" +
"public class A {\r\n" +
" private B b = new B();\r\n" +
"}", true, null);
//@formatter:on
IPackageFragment pack2 = sourceFolder.createPackageFragment("jdtls.test2", false, null);
//@formatter:off
ICompilationUnit unitB = pack2.createCompilationUnit("B.java", "package jdtls.test2;\r\n" +
"\r\n" +
"public class B {\r\n" +
"}", true, null);
//@formatter:on
IPackageFragment pack3 = sourceFolder.createPackageFragment("jdtls.test3", false, null);
String packageUri = JDTUtils.getFileURI(pack3.getResource());
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveResource", new String[] { JDTUtils.toURI(unitB) }, packageUri, true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(4, changes.size());
//@formatter:off
String expected = "package jdtls.test1;\r\n" +
"import jdtls.test3.B;\r\n" +
"\r\n" +
"public class A {\r\n" +
" private B b = new B();\r\n" +
"}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(unitA.getSource(), textEdit.getEdits()));
//@formatter:off
expected = "package jdtls.test3;\r\n" +
"\r\n" +
"public class B {\r\n" +
"}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
List<TextEdit> edits = new ArrayList<>(textEdit.getEdits());
textEdit = changes.get(2).getLeft();
assertNotNull(textEdit);
edits.addAll(textEdit.getEdits());
assertEquals(expected, TextEditUtil.apply(unitB.getSource(), edits));
RenameFile renameFile = (RenameFile) changes.get(3).getRight();
assertNotNull(renameFile);
assertEquals(JDTUtils.toURI(unitB), renameFile.getOldUri());
assertEquals(ResourceUtils.fixURI(unitB.getResource().getRawLocationURI()).replace("test2", "test3"), renameFile.getNewUri());
}
@Test
public void testMoveMultiFiles() throws JavaModelException, BadLocationException {
IPackageFragment pack1 = sourceFolder.createPackageFragment("jdtls.test1", false, null);
//@formatter:off
ICompilationUnit unitA = pack1.createCompilationUnit("A.java", "package jdtls.test1;\r\n" +
"\r\n" +
"public class A {\r\n" +
" private B b = new B();\r\n" +
"}", true, null);
//@formatter:on
//@formatter:off
ICompilationUnit unitB = pack1.createCompilationUnit("B.java", "package jdtls.test1;\r\n" +
"\r\n" +
"public class B {\r\n" +
"}", true, null);
//@formatter:on
IPackageFragment pack2 = sourceFolder.createPackageFragment("jdtls.test2", false, null);
String packageUri = JDTUtils.getFileURI(pack2.getResource());
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveResource", new String[] { JDTUtils.toURI(unitA), JDTUtils.toURI(unitB) }, packageUri, true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(6, changes.size());
//@formatter:off
String expected = "package jdtls.test2;\r\n" +
"\r\n" +
"public class A {\r\n" +
" private B b = new B();\r\n" +
"}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
List<TextEdit> edits = new ArrayList<>(textEdit.getEdits());
textEdit = changes.get(4).getLeft();
assertNotNull(textEdit);
edits.addAll(textEdit.getEdits());
assertEquals(expected, TextEditUtil.apply(unitA.getSource(), edits));
//@formatter:off
expected = "package jdtls.test2;\r\n" +
"\r\n" +
"public class B {\r\n" +
"}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
edits = new ArrayList<>(textEdit.getEdits());
textEdit = changes.get(2).getLeft();
assertNotNull(textEdit);
edits.addAll(textEdit.getEdits());
assertEquals(expected, TextEditUtil.apply(unitB.getSource(), edits));
RenameFile renameFileB = (RenameFile) changes.get(3).getRight();
assertNotNull(renameFileB);
assertEquals(JDTUtils.toURI(unitB), renameFileB.getOldUri());
assertEquals(ResourceUtils.fixURI(unitB.getResource().getRawLocationURI()).replace("test1", "test2"), renameFileB.getNewUri());
RenameFile renameFileA = (RenameFile) changes.get(5).getRight();
assertNotNull(renameFileA);
assertEquals(JDTUtils.toURI(unitA), renameFileA.getOldUri());
assertEquals(ResourceUtils.fixURI(unitA.getResource().getRawLocationURI()).replace("test1", "test2"), renameFileA.getNewUri());
}
@Test
public void testMoveInstanceMethod() throws Exception {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
ICompilationUnit cuSecond = pack1.createCompilationUnit("Second.java", "package test1;\n"
+ "\n"
+ "public class Second {\n"
+ " public void foo() {\n"
+ " }\n"
+ "}",
false, null);
//@formatter:on
//@formatter:off
pack1.createCompilationUnit("Third.java", "package test1;\n"
+ "\n"
+ "public class Third {\n"
+ " public void bar() {\n"
+ " }\n"
+ "}",
false, null);
//@formatter:on
//@formatter:off
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " Second s;\n"
+ " String name;\n"
+ " int id;\n"
+ " public void print(Third t) {\n"
+ " System.out.println(name);\n"
+ " s.foo();\n"
+ " t.bar();\n"
+ " }\n"
+ "\n"
+ " public void log(Third t) {\n"
+ " print(t);\n"
+ " }\n"
+ "}",
false, null);
//@formatter:on
CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, "s.foo");
MoveParams moveParams = new MoveParams("moveInstanceMethod", new String[] { JDTUtils.toURI(cu) }, params);
MoveDestinationsResponse response = MoveHandler.getMoveDestinations(moveParams);
assertNotNull(response);
assertNull(response.errorMessage);
assertNotNull(response.destinations);
assertEquals(2, response.destinations.length);
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveInstanceMethod", params, response.destinations[1], true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(2, changes.size());
//@formatter:off
String expected = "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " Second s;\n"
+ " String name;\n"
+ " int id;\n"
+ " public void log(Third t) {\n"
+ " s.print(this, t);\n"
+ " }\n"
+ "}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cu.getSource(), textEdit.getEdits()));
//@formatter:off
expected = "package test1;\n"
+ "\n"
+ "public class Second {\n"
+ " public void foo() {\n"
+ " }\n"
+ "\n"
+ " public void print(E e, Third t) {\n"
+ " System.out.println(e.name);\n"
+ " foo();\n"
+ " t.bar();\n"
+ " }\n"
+ "}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cuSecond.getSource(), textEdit.getEdits()));
}
@Test
public void testMoveStaticMethod() throws Exception {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " public static void foo() {\n"
+ " /*[*//*]*/\n"
+ " }\n"
+ "\n"
+ " public void bar() {\n"
+ " foo();\n"
+ " }\n"
+ "}",
false, null);
//@formatter:on
//@formatter:off
ICompilationUnit unitFoo = pack1.createCompilationUnit("Foo.java", "package test1;\n"
+ "\n"
+ "public class Foo {\n"
+ "}", false, null);
//@formatter:on
CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, "/*[*//*]*/");
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveStaticMember", params, "Foo", true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(2, changes.size());
//@formatter:off
String expected = "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " public void bar() {\n"
+ " Foo.foo();\n"
+ " }\n"
+ "}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cu.getSource(), textEdit.getEdits()));
//@formatter:off
expected = "package test1;\n"
+ "\n"
+ "public class Foo {\n"
+ "\n"
+ " public static void foo() {\n"
+ " /*[*//*]*/\n"
+ " }\n"
+ "}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(unitFoo.getSource(), textEdit.getEdits()));
}
@Test
public void testMoveStaticField() throws Exception {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
pack1.createCompilationUnit("Foo.java", "package test1;\n"
+ "\n"
+ "public class Foo {\n"
+ " public void foo() {\n"
+ " }\n"
+ "}", false, null);
//@formatter:on
//@formatter:off
ICompilationUnit unitUtility = pack1.createCompilationUnit("Utility.java", "package test1;\n"
+ "\n"
+ "public class Utility {\n"
+ "}", false, null);
//@formatter:on
//@formatter:off
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " static Foo foo = new Foo();\n"
+ " public void print() {\n"
+ " foo.foo();\n"
+ " }\n"
+ "}",
false, null);
//@formatter:on
CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, "new Foo()");
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveStaticMember", params, "Utility", true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(2, changes.size());
//@formatter:off
String expected = "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " public void print() {\n"
+ " Utility.foo.foo();\n"
+ " }\n"
+ "}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cu.getSource(), textEdit.getEdits()));
//@formatter:off
expected = "package test1;\n"
+ "\n"
+ "public class Utility {\n"
+ "\n"
+ " static Foo foo = new Foo();\n"
+ "}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(unitUtility.getSource(), textEdit.getEdits()));
}
@Test
public void testMoveStaticInnerType() throws Exception {
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
ICompilationUnit unitFoo = pack1.createCompilationUnit("Foo.java", "package test1;\n"
+ "\n"
+ "public class Foo {\n"
+ "}", false, null);
//@formatter:on
//@formatter:off
ICompilationUnit cu = pack1.createCompilationUnit("E.java", "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " public void print() {\n"
+ " new Inner().run();\n"
+ " }\n"
+ " static class Inner {\n"
+ " void run() {\n"
+ " }\n"
+ " }\n"
+ "}", false, null);
//@formatter:on
CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, "class Inner");
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveTypeToClass", params, "Foo", true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(2, changes.size());
//@formatter:off
String expected = "package test1;\n"
+ "\n"
+ "public class E {\n"
+ " public void print() {\n"
+ " new Foo.Inner().run();\n"
+ " }\n"
+ "}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cu.getSource(), textEdit.getEdits()));
//@formatter:off
expected = "package test1;\n"
+ "\n"
+ "public class Foo {\n"
+ "\n"
+ " static class Inner {\n"
+ " void run() {\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
textEdit = changes.get(1).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(unitFoo.getSource(), textEdit.getEdits()));
}
@Test
public void testMoveInnerTypeToFile() throws Exception {
System.setProperty("line.separator", "\n");
IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
//@formatter:off
ICompilationUnit cu = pack1.createCompilationUnit("Top.java", "package test1;\n"
+ "\n"
+ "public class Top {\n"
+ " String name;\n\n"
+ " public class Inner {\n"
+ " public void print() {\n"
+ " System.out.println(Top.this.name);\n"
+ " }\n"
+ " }\n"
+ "}", false, null);
//@formatter:on
CodeActionParams params = CodeActionUtil.constructCodeActionParams(cu, "class Inner");
RefactorWorkspaceEdit refactorEdit = MoveHandler.move(new MoveParams("moveTypeToNewFile", params, "Foo", true), new NullProgressMonitor());
assertNotNull(refactorEdit);
assertNotNull(refactorEdit.edit);
List<Either<TextDocumentEdit, ResourceOperation>> changes = refactorEdit.edit.getDocumentChanges();
assertEquals(3, changes.size());
//@formatter:off
String expected = "package test1;\n"
+ "\n"
+ "public class Top {\n"
+ " String name;\n"
+ "}";
//@formatter:on
TextDocumentEdit textEdit = changes.get(0).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(cu.getSource(), textEdit.getEdits()));
ResourceOperation resourceOperation = changes.get(1).getRight();
assertNotNull(resourceOperation);
assertTrue(resourceOperation instanceof CreateFile);
assertEquals(ResourceUtils.fixURI(cu.getResource().getRawLocationURI()).replace("Top", "Inner"), ((CreateFile) resourceOperation).getUri());
//@formatter:off
expected = "package test1;\n"
+ "\n"
+ "public class Inner {\n"
+ " /**\n"
+ " *\n"
+ " */\n"
+ " private final Top top;\n\n"
+ " /**\n"
+ " * @param top\n"
+ " */\n"
+ " Inner(Top top) {\n"
+ " this.top = top;\n"
+ " }\n\n"
+ " public void print() {\n"
+ " System.out.println(this.top.name);\n"
+ " }\n"
+ "}";
//@formatter:on
textEdit = changes.get(2).getLeft();
assertNotNull(textEdit);
assertEquals(expected, TextEditUtil.apply(pack1.getCompilationUnit("Inner.java").getWorkingCopy(null), textEdit.getEdits()));
}
@Override
protected String toExpectation(final Object it) {
if (it instanceof Integer) {
return _toExpectation((Integer)it);
} else if (it instanceof List) {
return _toExpectation((List<?>)it);
} else if (it instanceof DocumentHighlightKind) {
return _toExpectation((DocumentHighlightKind)it);
} else if (it instanceof String) {
return _toExpectation((String)it);
} else if (it instanceof VersionedTextDocumentIdentifier) {
return _toExpectation((VersionedTextDocumentIdentifier)it);
} else if (it instanceof Pair) {
return _toExpectation((Pair<SemanticHighlightingInformation, List<List<String>>>)it);
} else if (it == null) {
return _toExpectation((Void)null);
} else if (it instanceof Map) {
return _toExpectation((Map<Object, Object>)it);
} else if (it instanceof CodeAction) {
return _toExpectation((CodeAction)it);
} else if (it instanceof CodeLens) {
return _toExpectation((CodeLens)it);
} else if (it instanceof Command) {
return _toExpectation((Command)it);
} else if (it instanceof CompletionItem) {
return _toExpectation((CompletionItem)it);
} else if (it instanceof DocumentHighlight) {
return _toExpectation((DocumentHighlight)it);
} else if (it instanceof DocumentSymbol) {
return _toExpectation((DocumentSymbol)it);
} else if (it instanceof Hover) {
return _toExpectation((Hover)it);
} else if (it instanceof Location) {
return _toExpectation((Location)it);
} else if (it instanceof MarkupContent) {
return _toExpectation((MarkupContent)it);
} else if (it instanceof Position) {
return _toExpectation((Position)it);
} else if (it instanceof Range) {
return _toExpectation((Range)it);
} else if (it instanceof ResourceOperation) {
return _toExpectation((ResourceOperation)it);
} else if (it instanceof SignatureHelp) {
return _toExpectation((SignatureHelp)it);
} else if (it instanceof SymbolInformation) {
return _toExpectation((SymbolInformation)it);
} else if (it instanceof TextDocumentEdit) {
return _toExpectation((TextDocumentEdit)it);
} else if (it instanceof TextEdit) {
return _toExpectation((TextEdit)it);
} else if (it instanceof WorkspaceEdit) {
return _toExpectation((WorkspaceEdit)it);
} else if (it instanceof Either) {
return _toExpectation((Either<?, ?>)it);
} else {
throw new IllegalArgumentException("Unhandled parameter types: " +
Arrays.<Object>asList(it).toString());
}
}
protected String toExpectation(final Object it) {
if (it instanceof Integer) {
return _toExpectation((Integer)it);
} else if (it instanceof List) {
return _toExpectation((List<?>)it);
} else if (it instanceof DocumentHighlightKind) {
return _toExpectation((DocumentHighlightKind)it);
} else if (it instanceof String) {
return _toExpectation((String)it);
} else if (it instanceof VersionedTextDocumentIdentifier) {
return _toExpectation((VersionedTextDocumentIdentifier)it);
} else if (it instanceof Pair) {
return _toExpectation((Pair<SemanticHighlightingInformation, List<List<String>>>)it);
} else if (it == null) {
return _toExpectation((Void)null);
} else if (it instanceof Map) {
return _toExpectation((Map<Object, Object>)it);
} else if (it instanceof CodeAction) {
return _toExpectation((CodeAction)it);
} else if (it instanceof CodeLens) {
return _toExpectation((CodeLens)it);
} else if (it instanceof Command) {
return _toExpectation((Command)it);
} else if (it instanceof CompletionItem) {
return _toExpectation((CompletionItem)it);
} else if (it instanceof DocumentHighlight) {
return _toExpectation((DocumentHighlight)it);
} else if (it instanceof DocumentSymbol) {
return _toExpectation((DocumentSymbol)it);
} else if (it instanceof Hover) {
return _toExpectation((Hover)it);
} else if (it instanceof Location) {
return _toExpectation((Location)it);
} else if (it instanceof MarkupContent) {
return _toExpectation((MarkupContent)it);
} else if (it instanceof Position) {
return _toExpectation((Position)it);
} else if (it instanceof Range) {
return _toExpectation((Range)it);
} else if (it instanceof ResourceOperation) {
return _toExpectation((ResourceOperation)it);
} else if (it instanceof SignatureHelp) {
return _toExpectation((SignatureHelp)it);
} else if (it instanceof SymbolInformation) {
return _toExpectation((SymbolInformation)it);
} else if (it instanceof TextDocumentEdit) {
return _toExpectation((TextDocumentEdit)it);
} else if (it instanceof TextEdit) {
return _toExpectation((TextEdit)it);
} else if (it instanceof WorkspaceEdit) {
return _toExpectation((WorkspaceEdit)it);
} else if (it instanceof Either) {
return _toExpectation((Either<?, ?>)it);
} else {
throw new IllegalArgumentException("Unhandled parameter types: " +
Arrays.<Object>asList(it).toString());
}
}