下面列出了怎么用org.eclipse.lsp4j.CreateFile的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;
}
private static void convertCreateCompilationUnitChange(WorkspaceEdit edit, CreateCompilationUnitChange change) {
ICompilationUnit unit = change.getCu();
CreateFile createFile = new CreateFile();
createFile.setUri(JDTUtils.toURI(unit));
createFile.setOptions(new CreateFileOptions(false, true));
edit.getDocumentChanges().add(Either.forRight(createFile));
InsertEdit textEdit = new InsertEdit(0, change.getPreview());
convertTextEdit(edit, unit, textEdit);
}
@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 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();
}
private static void convertRenamePackcageChange(WorkspaceEdit edit, RenamePackageChange packageChange) throws CoreException {
IPackageFragment pack = (IPackageFragment) packageChange.getModifiedElement();
IPath newPackageFragment = new Path(packageChange.getNewName().replace('.', IPath.SEPARATOR));
IPath oldPackageFragment = new Path(packageChange.getOldName().replace('.', IPath.SEPARATOR));
IPath newPackagePath = pack.getResource().getLocation().removeLastSegments(oldPackageFragment.segmentCount()).append(newPackageFragment);
if (packageChange.getRenameSubpackages()) {
IPackageFragment[] allPackages = JavaElementUtil.getPackageAndSubpackages(pack);
String oldPrefix = packageChange.getOldName();
for (IPackageFragment currentPackage : allPackages) {
String newPkgName = packageChange.getNewName() + currentPackage.getElementName().substring(oldPrefix.length());
//update package's declaration
convertPackageUpdateEdit(currentPackage.getCompilationUnits(), newPkgName, edit);
}
RenameFile renameFile = new RenameFile();
renameFile.setNewUri(ResourceUtils.fixURI(newPackagePath.toFile().toURI()));
renameFile.setOldUri(ResourceUtils.fixURI(pack.getResource().getRawLocationURI()));
edit.getDocumentChanges().add(Either.forRight(renameFile));
} else {
//update package's declaration
convertPackageUpdateEdit(pack.getCompilationUnits(), packageChange.getNewName(), edit);
CreateFile createFile = new CreateFile();
createFile.setUri(ResourceUtils.fixURI(newPackagePath.append(TEMP_FILE_NAME).toFile().toURI()));
createFile.setOptions(new CreateFileOptions(false, true));
edit.getDocumentChanges().add(Either.forRight(createFile));
for (ICompilationUnit unit : pack.getCompilationUnits()) {
RenameFile cuResourceChange = new RenameFile();
cuResourceChange.setOldUri(ResourceUtils.fixURI(unit.getResource().getLocationURI()));
IPath newCUPath = newPackagePath.append(unit.getPath().lastSegment());
cuResourceChange.setNewUri(ResourceUtils.fixURI(newCUPath.toFile().toURI()));
edit.getDocumentChanges().add(Either.forRight(cuResourceChange));
}
// Workaround: https://github.com/Microsoft/language-server-protocol/issues/272
DeleteFile deleteFile = new DeleteFile();
deleteFile.setUri(ResourceUtils.fixURI(newPackagePath.append(TEMP_FILE_NAME).toFile().toURI()));
deleteFile.setOptions(new DeleteFileOptions(false, true));
edit.getDocumentChanges().add(Either.forRight(deleteFile));
}
}
private static void convertCreateFileChange(WorkspaceEdit edit, CreateFileChange createFileChange) {
CreateFile createFile = new CreateFile();
createFile.setUri(ResourceUtils.fixURI(createFileChange.getPath().toFile().toURI()));
createFile.setOptions(new CreateFileOptions(false, true));
edit.getDocumentChanges().add(Either.forRight(createFile));
}
@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 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()));
}
InnerResourceOperationTypeAdapter(TypeAdapterFactory factory, Gson gson) {
createFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(CreateFile.class));
deleteFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(DeleteFile.class));
renameFileAdapter = gson.getDelegateAdapter(factory, TypeToken.get(RenameFile.class));
}