Java Code Examples for org.eclipse.lsp4j.TextDocumentEdit

The following examples show how to use org.eclipse.lsp4j.TextDocumentEdit. These examples are extracted from open source projects. 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 Project: lemminx   Source File: CodeActionFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public static CodeAction replaceAt(String title, String replaceText, TextDocumentItem document,
		Diagnostic diagnostic, Collection<Range> ranges) {
	CodeAction insertContentAction = new CodeAction(title);
	insertContentAction.setKind(CodeActionKind.QuickFix);
	insertContentAction.setDiagnostics(Arrays.asList(diagnostic));

	VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(
			document.getUri(), document.getVersion());
	List<TextEdit> edits = new ArrayList<TextEdit>();
	for (Range range : ranges) {
		TextEdit edit = new TextEdit(range, replaceText);
		edits.add(edit);
	}
	TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, edits);
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));

	insertContentAction.setEdit(workspaceEdit);
	return insertContentAction;
}
 
Example 2
Source Project: lemminx   Source File: CodeActionFactory.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source Project: eclipse.jdt.ls   Source File: ChangeUtil.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 4
Source Project: eclipse.jdt.ls   Source File: ChangeUtilTest.java    License: 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 5
Source Project: eclipse.jdt.ls   Source File: ChangeUtilTest.java    License: 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 6
Source Project: lemminx   Source File: CodeActionFactory.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create a CodeAction to insert a new content at the end of the given range.
 * 
 * @param title
 * @param range
 * @param insertText
 * @param document
 * @param diagnostic
 * 
 * @return the CodeAction to insert a new content at the end of the given range.
 */
public static CodeAction insert(String title, Position position, String insertText, TextDocumentItem document,
		Diagnostic diagnostic) {
	CodeAction insertContentAction = new CodeAction(title);
	insertContentAction.setKind(CodeActionKind.QuickFix);
	insertContentAction.setDiagnostics(Arrays.asList(diagnostic));
	TextDocumentEdit textDocumentEdit = insertEdit(insertText, position, document);
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));

	insertContentAction.setEdit(workspaceEdit);
	return insertContentAction;
}
 
Example 7
private static CodeAction createGrammarFileAndBindIt(String title, String grammarURI, String grammarContent,
		String insertText, int insertOffset, DOMDocument document, Diagnostic diagnostic)
		throws BadLocationException {
	Position position = document.positionAt(insertOffset);
	TextDocumentEdit insertEdit = CodeActionFactory.insertEdit(insertText, position, document.getTextDocument());
	return createGrammarFileAndBindIt(title, grammarURI, grammarContent, insertEdit, diagnostic);
}
 
Example 8
Source Project: lemminx   Source File: XMLAssert.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public static CodeAction ca(Diagnostic d, TextEdit... te) {
	CodeAction codeAction = new CodeAction();
	codeAction.setTitle("");
	codeAction.setDiagnostics(Arrays.asList(d));

	VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier(FILE_URI,
			0);

	TextDocumentEdit textDocumentEdit = new TextDocumentEdit(versionedTextDocumentIdentifier, Arrays.asList(te));
	WorkspaceEdit workspaceEdit = new WorkspaceEdit(Collections.singletonList(Either.forLeft(textDocumentEdit)));
	codeAction.setEdit(workspaceEdit);
	return codeAction;
}
 
Example 9
Source Project: lemminx   Source File: XMLAssert.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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;
}
 
Example 10
Source Project: n4js   Source File: StringLSP4J.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** @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());
	}
}
 
Example 11
Source Project: n4js   Source File: StringLSP4J.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/** @return string for given element */
public String toString(TextDocumentEdit edit) {
	if (edit == null) {
		return "";
	}
	String str = Strings.join(", ",
			toString(edit.getTextDocument()),
			Strings.toString(this::toString, edit.getEdits()));

	return "(" + str + ")";
}
 
Example 12
Source Project: eclipse.jdt.ls   Source File: RenameHandlerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example 13
Source Project: eclipse.jdt.ls   Source File: ReorgQuickFixTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
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());
}
 
Example 14
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);
}
 
Example 15
protected String _toExpectation(final TextDocumentEdit e) {
  StringConcatenation _builder = new StringConcatenation();
  String _expectation = this.toExpectation(e.getTextDocument());
  _builder.append(_expectation);
  _builder.append(" : ");
  String _expectation_1 = this.toExpectation(e.getEdits());
  _builder.append(_expectation_1);
  _builder.newLineIfNotEmpty();
  return _builder.toString();
}
 
Example 16
Source Project: xtext-core   Source File: ChangeConverter2.java    License: Eclipse Public License 2.0 5 votes vote down vote up
protected Object addTextEdit(String theUri, Document document, TextEdit... textEdits) {
	if (useDocumentChanges) {
		TextDocumentEdit textDocumentEdit = new TextDocumentEdit();
		VersionedTextDocumentIdentifier versionedTextDocumentIdentifier = new VersionedTextDocumentIdentifier();
		versionedTextDocumentIdentifier.setUri(theUri);
		versionedTextDocumentIdentifier.setVersion(document.getVersion());
		textDocumentEdit.setTextDocument(versionedTextDocumentIdentifier);
		textDocumentEdit.setEdits(Arrays.asList(textEdits));
		return edit.getDocumentChanges().add(Either.forLeft(textDocumentEdit));
	} else {
		return edit.getChanges().put(theUri, Arrays.asList(textEdits));
	}
}
 
Example 17
Source Project: lsp4j   Source File: ResourceChangeListAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
	Predicate<JsonElement> leftChecker = new PropertyChecker("current").or(new PropertyChecker("newUri"));
	Predicate<JsonElement> rightChecker = new PropertyChecker("textDocument").and(new PropertyChecker("edits"));
	TypeAdapter<Either<ResourceChange, TextDocumentEdit>> elementTypeAdapter = new EitherTypeAdapter<>(gson,
			ELEMENT_TYPE, leftChecker, rightChecker);
	return (TypeAdapter<T>) new CollectionTypeAdapter<>(gson, ELEMENT_TYPE.getType(), elementTypeAdapter, ArrayList::new);
}
 
Example 18
Source Project: lsp4j   Source File: DocumentChangeListAdapter.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
private static CodeAction createGrammarFileAndBindIt(String title, String grammarURI, String grammarContent,
		TextDocumentEdit boundEdit, Diagnostic diagnostic) {
	CodeAction codeAction = CodeActionFactory.createFile(title, grammarURI, grammarContent, diagnostic);
	codeAction.getEdit().getDocumentChanges().add(Either.forLeft(boundEdit));
	return codeAction;
}
 
Example 20
Source Project: lemminx   Source File: XMLAssert.java    License: Eclipse Public License 2.0 4 votes vote down vote up
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));
}
 
Example 21
Source Project: lemminx   Source File: XMLAssert.java    License: Eclipse Public License 2.0 4 votes vote down vote up
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))));
}
 
Example 22
Source Project: netbeans   Source File: UtilsTest.java    License: Apache License 2.0 4 votes vote down vote up
public void testApplyChanges() throws Exception {
    clearWorkDir();
    FileObject wd = FileUtil.toFileObject(getWorkDir());
    FileObject sourceFile1 = wd.createData("Test1.txt");
    try (OutputStream out = sourceFile1.getOutputStream()) {
        out.write(("0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n").getBytes("UTF-8"));
    }
    FileObject sourceFile2 = wd.createData("Test2.txt");
    try (OutputStream out = sourceFile2.getOutputStream()) {
        out.write(("0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n" +
                   "0123456789\n").getBytes("UTF-8"));
    }
    FileObject sourceFile3 = wd.createData("Test3.txt");
    WorkspaceEdit edit = new WorkspaceEdit(Arrays.asList(Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(Utils.toURI(sourceFile1), -1), Arrays.asList(new TextEdit(new Range(new Position(2, 3), new Position(2, 6)), "a"),
                                                                                                                                                                              new TextEdit(new Range(new Position(1, 2), new Position(1, 6)), "b"),
                                                                                                                                                                              new TextEdit(new Range(new Position(3, 1), new Position(4, 4)), "c")))),
                                                         Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(Utils.toURI(sourceFile2), -1), Arrays.asList(new TextEdit(new Range(new Position(2, 3), new Position(2, 6)), "a"),
                                                                                                                                                                              new TextEdit(new Range(new Position(1, 2), new Position(1, 6)), "b"),
                                                                                                                                                                              new TextEdit(new Range(new Position(3, 1), new Position(4, 4)), "c")))),
                                                         Either.forRight(new CreateFile(Utils.toURI(sourceFile2).replace("Test2", "Test4"))),
                                                         Either.forLeft(new TextDocumentEdit(new VersionedTextDocumentIdentifier(Utils.toURI(sourceFile2).replace("Test2", "Test4"), -1), Arrays.asList(new TextEdit(new Range(new Position(1, 1), new Position(1, 1)), "new content")))),
                                                         Either.forRight(new DeleteFile(Utils.toURI(sourceFile3))),
                                                         Either.forRight(new RenameFile(Utils.toURI(sourceFile1), Utils.toURI(sourceFile1).replace("Test1", "Test1a")))));
    Utils.applyWorkspaceEdit(edit);
    assertContent("0123456789\n" +
                  "01b6789\n" +
                  "012a6789\n" +
                  "0c456789\n",
                  wd.getFileObject("Test1a.txt"));
    assertContent("0123456789\n" +
                  "01b6789\n" +
                  "012a6789\n" +
                  "0c456789\n",
                  wd.getFileObject("Test2.txt"));
    assertContent("new content", wd.getFileObject("Test4.txt"));
    assertNull(wd.getFileObject("Test3.txt"));
    LifecycleManager.getDefault().saveAll();
}
 
Example 23
Source Project: eclipse.jdt.ls   Source File: TextEditConverter.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public TextDocumentEdit convertToTextDocumentEdit(int version) {
	String uri = JDTUtils.toURI(compilationUnit);
	VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(version);
	identifier.setUri(uri);
	return new TextDocumentEdit(identifier, this.convert());
}
 
Example 24
Source Project: eclipse.jdt.ls   Source File: ChangeUtilTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@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());
}
 
Example 25
@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"
			);
}
 
Example 26
@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"
			);
}
 
Example 27
Source Project: eclipse.jdt.ls   Source File: RenameHandlerTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@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));
}
 
Example 28
Source Project: eclipse.jdt.ls   Source File: RenameHandlerTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@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());
}
 
Example 29
Source Project: eclipse.jdt.ls   Source File: MoveHandlerTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@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());
}
 
Example 30
Source Project: eclipse.jdt.ls   Source File: MoveHandlerTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@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());
}