org.eclipse.lsp4j.TextDocumentEdit Java Examples

The following examples show how to use org.eclipse.lsp4j.TextDocumentEdit. 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: CodeActionFactory.java    From lemminx with 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 File: CodeActionFactory.java    From lemminx with 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 File: ChangeUtilTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConvertSimpleCompositeChange() throws CoreException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
	CompositeChange change = new CompositeChange("simple composite change");

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

	WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);
	assertEquals(edit.getDocumentChanges().size(), 2);
	assertTrue(edit.getDocumentChanges().get(0).getRight() instanceof RenameFile);
	assertTrue(edit.getDocumentChanges().get(1).getLeft() instanceof TextDocumentEdit);
}
 
Example #4
Source File: ChangeUtilTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConvertCompilationUnitChange() throws CoreException {
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	ICompilationUnit cu = pack1.createCompilationUnit("E.java", "", false, null);
	CompilationUnitChange change = new CompilationUnitChange("insertText", cu);
	String newText = "// some content";
	change.setEdit(new InsertEdit(0, newText));

	WorkspaceEdit edit = ChangeUtil.convertToWorkspaceEdit(change);

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

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

	TextEdit textEdit = textDocumentEdit.getEdits().get(0);
	assertEquals(textEdit.getNewText(), newText);
}
 
Example #5
Source File: ChangeUtil.java    From eclipse.jdt.ls with 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 #6
Source File: StringLSP4J.java    From n4js with 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 #7
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with 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 #8
Source File: ReorgQuickFixTest.java    From eclipse.jdt.ls with 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 #9
Source File: AbstractQuickFixTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
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 #10
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
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 #11
Source File: StringLSP4J.java    From n4js with 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 #12
Source File: ChangeConverter2.java    From xtext-core with 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 #13
Source File: ResourceChangeListAdapter.java    From lsp4j with 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 #14
Source File: XMLAssert.java    From lemminx with 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 #15
Source File: XMLAssert.java    From lemminx with 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 #16
Source File: DocumentChangeListAdapter.java    From lsp4j with 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 #17
Source File: NoGrammarConstraintsCodeAction.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
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 #18
Source File: CodeActionFactory.java    From lemminx with 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 #19
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@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()));
}
 
Example #20
Source File: WorkspaceEdit.java    From lsp4j with Eclipse Public License 2.0 4 votes vote down vote up
public WorkspaceEdit(final List<Either<TextDocumentEdit, ResourceOperation>> documentChanges) {
  this.documentChanges = documentChanges;
}
 
Example #21
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@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()));
}
 
Example #22
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@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()));
}
 
Example #23
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@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()));
}
 
Example #24
Source File: CompletionTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@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());
  }
}
 
Example #25
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
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());
  }
}
 
Example #26
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@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()));
}
 
Example #27
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with 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());
}
 
Example #28
Source File: MoveHandlerTest.java    From eclipse.jdt.ls with 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 #29
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with 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 #30
Source File: RenameHandlerTest.java    From eclipse.jdt.ls with 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));
}