Java Code Examples for org.eclipse.lsp4j.FileEvent

The following examples show how to use org.eclipse.lsp4j.FileEvent. 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: n4js   Source File: LSPBuilder.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
	// TODO: Set watched files to client. Note: Client may have performance issues with lots of folders to watch.
	final List<URI> dirtyFiles = new ArrayList<>();
	final List<URI> deletedFiles = new ArrayList<>();
	for (FileEvent fileEvent : params.getChanges()) {
		URI uri = uriExtensions.toUri(fileEvent.getUri());

		String fileName = uri.lastSegment();
		boolean skipFile = fileName.equals(ProjectStatePersister.FILENAME);

		if (!skipFile && isSourceFile(uri)) {
			FileChangeType changeType = fileEvent.getType();

			if (changeType == FileChangeType.Deleted) {
				deletedFiles.add(uri);
			} else {
				dirtyFiles.add(uri);
			}
		}
	}
	if (!dirtyFiles.isEmpty() || !deletedFiles.isEmpty()) {
		runBuildable("didChangeWatchedFiles", () -> workspaceManager.didChangeFiles(dirtyFiles, deletedFiles));
	}
}
 
Example 2
Source Project: xtext-core   Source File: IndexOnlyProjectTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Shows that the resource is not validated during incremental build
 */
@Test
public void testIncrementalBuildNoValidation() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Test {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("NonExisting foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  this.writeFile("MyType1.testlang", _builder);
  this.initialize();
  Assert.assertTrue(IterableExtensions.join(this.getDiagnostics().entrySet(), ","), this.getDiagnostics().isEmpty());
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("type NonExisting {");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  final String path = this.writeFile("MyType2.testlang", _builder_1);
  WorkspaceService _workspaceService = this.languageServer.getWorkspaceService();
  FileEvent _fileEvent = new FileEvent(path, FileChangeType.Created);
  DidChangeWatchedFilesParams _didChangeWatchedFilesParams = new DidChangeWatchedFilesParams(Collections.<FileEvent>unmodifiableList(CollectionLiterals.<FileEvent>newArrayList(_fileEvent)));
  _workspaceService.didChangeWatchedFiles(_didChangeWatchedFilesParams);
  Assert.assertTrue(IterableExtensions.join(this.getDiagnostics().entrySet(), ","), this.getDiagnostics().isEmpty());
}
 
Example 3
Source Project: xtext-core   Source File: ServerTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testIncrementalDeletion() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Test {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("NonExisting foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final String path = this.writeFile("MyType1.testlang", _builder);
  this.initialize();
  this.assertEquals("Couldn\'t resolve reference to TypeDeclaration \'NonExisting\'.", 
    IterableExtensions.<Diagnostic>head(IterableExtensions.<List<Diagnostic>>head(this.getDiagnostics().values())).getMessage());
  this.deleteFile("MyType1.testlang");
  WorkspaceService _workspaceService = this.languageServer.getWorkspaceService();
  FileEvent _fileEvent = new FileEvent(path, FileChangeType.Deleted);
  DidChangeWatchedFilesParams _didChangeWatchedFilesParams = new DidChangeWatchedFilesParams(Collections.<FileEvent>unmodifiableList(CollectionLiterals.<FileEvent>newArrayList(_fileEvent)));
  _workspaceService.didChangeWatchedFiles(_didChangeWatchedFilesParams);
  Assert.assertTrue(IterableExtensions.<List<Diagnostic>>head(this.getDiagnostics().values()).isEmpty());
}
 
Example 4
Source Project: lemminx   Source File: XMLWorkspaceService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
	XMLTextDocumentService xmlTextDocumentService = (XMLTextDocumentService) xmlLanguageServer.getTextDocumentService();
	List<FileEvent> changes = params.getChanges();
	for (FileEvent change: changes) {
		if (!xmlTextDocumentService.documentIsOpen(change.getUri())) {
			xmlTextDocumentService.doSave(change.getUri());
		}
	}
}
 
Example 5
Source Project: n4js   Source File: AbstractIdeTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Change a non-opened file <u>on disk</u> and notify the LSP server.
 * <p>
 * Use method {@link #changeOpenedFile(String, Pair...)} instead if the file was previously opened with one of the
 * {@link #openFile(FileURI) #openFile()} methods.
 *
 * @param modification
 *            a function returning the desired new content when given the file's current content on disk.
 */
protected void changeNonOpenedFile(String moduleName, Function<String, String> modification) {
	FileURI fileURI = getFileURIFromModuleName(moduleName);
	if (isOpen(fileURI)) {
		Assert.fail("file is open: " + fileURI);
	}
	// 1) change on disk
	changeFileOnDiskWithoutNotification(fileURI, modification);
	// 2) notify LSP server
	List<FileEvent> fileEvents = Collections.singletonList(
			new FileEvent(fileURI.toString(), FileChangeType.Changed));
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(fileEvents);
	languageServer.didChangeWatchedFiles(params);
}
 
Example 6
public void didChangeWatchedFiles(DidChangeWatchedFilesParams param) {
	List<FileEvent> changes = param.getChanges().stream().distinct().collect(Collectors.toList());
	for (FileEvent fileEvent : changes) {
		CHANGE_TYPE changeType = toChangeType(fileEvent.getType());
		if (changeType == CHANGE_TYPE.DELETED) {
			cleanUpDiagnostics(fileEvent.getUri());
			handler.didClose(new DidCloseTextDocumentParams(new TextDocumentIdentifier(fileEvent.getUri())));
			discardWorkingCopies(fileEvent.getUri());
		}
		ICompilationUnit unit = JDTUtils.resolveCompilationUnit(fileEvent.getUri());
		if (unit != null && changeType == CHANGE_TYPE.CREATED && !unit.exists()) {
			final ICompilationUnit[] units = new ICompilationUnit[1];
			units[0] = unit;
			try {
				ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() {
					@Override
					public void run(IProgressMonitor monitor) throws CoreException {
						units[0] = createCompilationUnit(units[0]);
					}
				}, new NullProgressMonitor());
			} catch (CoreException e) {
				JavaLanguageServerPlugin.logException(e.getMessage(), e);
			}
			unit = units[0];
		}
		if (unit != null) {
			if (unit.isWorkingCopy()) {
				continue;
			}
			if (changeType == CHANGE_TYPE.DELETED || changeType == CHANGE_TYPE.CHANGED) {
				if (unit.equals(CoreASTProvider.getInstance().getActiveJavaElement())) {
					CoreASTProvider.getInstance().disposeAST();
				}
			}
		}
		pm.fileChanged(fileEvent.getUri(), changeType);
	}
}
 
Example 7
@Test
public void testDiscardStaleWorkingCopies() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IFolder src = javaProject.getProject().getFolder("src");
	IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(src);
	IPackageFragment mypack = srcRoot.createPackageFragment("mypack", true, null);
	// @formatter:off
	String contents = "package mypack;\n" +
					"public class Foo {" +
					"}\n";
	// @formatter:on
	ICompilationUnit unit = mypack.createCompilationUnit("Foo.java", contents, true, null);
	openDocument(unit, contents, 1);
	assertTrue(unit.isWorkingCopy());

	String oldUri = JDTUtils.getFileURI(srcRoot.getResource());
	String parentUri = JDTUtils.getFileURI(src);
	String newUri = oldUri.replace("mypack", "mynewpack");
	File oldPack = mypack.getResource().getLocation().toFile();
	File newPack = new File(oldPack.getParent(), "mynewpack");
	Files.move(oldPack, newPack);
	assertTrue(unit.isWorkingCopy());
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(Arrays.asList(
		new FileEvent(newUri, FileChangeType.Created),
		new FileEvent(parentUri, FileChangeType.Changed),
		new FileEvent(oldUri, FileChangeType.Deleted)
	));
	new WorkspaceEventsHandler(projectsManager, javaClient, lifeCycleHandler).didChangeWatchedFiles(params);
	assertFalse(unit.isWorkingCopy());
}
 
Example 8
@Test
public void testDeleteProjectFolder() throws Exception {
	importProjects("maven/multimodule3");

	IProject module2 = ProjectUtils.getProject("module2");
	assertTrue(module2 != null && module2.exists());

	String projectUri = JDTUtils.getFileURI(module2);
	FileUtils.deleteDirectory(module2.getLocation().toFile());
	assertTrue(module2.exists());

	clientRequests.clear();
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(Arrays.asList(
		new FileEvent(projectUri, FileChangeType.Deleted)
	));
	new WorkspaceEventsHandler(projectsManager, javaClient, lifeCycleHandler).didChangeWatchedFiles(params);
	waitForBackgroundJobs();
	assertFalse(module2.exists());

	List<PublishDiagnosticsParams> diags = getClientRequests("publishDiagnostics");
	assertEquals(9L, diags.size());
	assertEndsWith(diags.get(0).getUri(), "/module2");
	assertEndsWith(diags.get(1).getUri(), "/multimodule3");
	assertEndsWith(diags.get(2).getUri(), "/multimodule3/pom.xml");
	assertEndsWith(diags.get(3).getUri(), "/module2/pom.xml");
	assertEquals(0L, diags.get(3).getDiagnostics().size());
	assertEndsWith(diags.get(4).getUri(), "/module2");
	assertEquals(0L, diags.get(4).getDiagnostics().size());
	assertEndsWith(diags.get(5).getUri(), "/App.java");
	assertEquals(0L, diags.get(5).getDiagnostics().size());
	assertEndsWith(diags.get(6).getUri(), "/AppTest.java");
	assertEquals(0L, diags.get(6).getDiagnostics().size());
	assertEndsWith(diags.get(7).getUri(), "/multimodule3");
	assertEndsWith(diags.get(8).getUri(), "/multimodule3/pom.xml");
}
 
Example 9
Source Project: xtext-core   Source File: OpenDocumentTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testOpenedDocumentShadowsPersistedFile() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Test {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("NonExisting foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  final String firstFile = this.writeFile("MyType1.testlang", _builder);
  this.initialize();
  this.assertEquals("Couldn\'t resolve reference to TypeDeclaration \'NonExisting\'.", IterableExtensions.<Diagnostic>head(this.getDiagnostics().get(firstFile)).getMessage());
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("type Foo {");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  final String path = this.writeFile("MyType2.testlang", _builder_1);
  WorkspaceService _workspaceService = this.languageServer.getWorkspaceService();
  FileEvent _fileEvent = new FileEvent(path, FileChangeType.Created);
  DidChangeWatchedFilesParams _didChangeWatchedFilesParams = new DidChangeWatchedFilesParams(
    Collections.<FileEvent>unmodifiableList(CollectionLiterals.<FileEvent>newArrayList(_fileEvent)));
  _workspaceService.didChangeWatchedFiles(_didChangeWatchedFilesParams);
  this.assertEquals("Couldn\'t resolve reference to TypeDeclaration \'NonExisting\'.", IterableExtensions.<Diagnostic>head(this.getDiagnostics().get(firstFile)).getMessage());
  StringConcatenation _builder_2 = new StringConcatenation();
  _builder_2.append("type NonExisting {");
  _builder_2.newLine();
  _builder_2.append("}");
  _builder_2.newLine();
  this.open(path, _builder_2.toString());
  Assert.assertNull(IterableExtensions.<Diagnostic>head(this.getDiagnostics().get(firstFile)));
  this.close(path);
  this.assertEquals("Couldn\'t resolve reference to TypeDeclaration \'NonExisting\'.", IterableExtensions.<Diagnostic>head(this.getDiagnostics().get(firstFile)).getMessage());
}
 
Example 10
Source Project: xtext-core   Source File: ServerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testIncrementalBuildWithError() {
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Test {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("NonExisting foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  this.writeFile("MyType1.testlang", _builder);
  this.initialize();
  this.assertEquals("Couldn\'t resolve reference to TypeDeclaration \'NonExisting\'.", IterableExtensions.<Diagnostic>head(IterableExtensions.<List<Diagnostic>>head(this.getDiagnostics().values())).getMessage());
  StringConcatenation _builder_1 = new StringConcatenation();
  _builder_1.append("type NonExisting {");
  _builder_1.newLine();
  _builder_1.append("}");
  _builder_1.newLine();
  final String path = this.writeFile("MyType2.testlang", _builder_1);
  WorkspaceService _workspaceService = this.languageServer.getWorkspaceService();
  FileEvent _fileEvent = new FileEvent(path, FileChangeType.Created);
  DidChangeWatchedFilesParams _didChangeWatchedFilesParams = new DidChangeWatchedFilesParams(Collections.<FileEvent>unmodifiableList(CollectionLiterals.<FileEvent>newArrayList(_fileEvent)));
  _workspaceService.didChangeWatchedFiles(_didChangeWatchedFilesParams);
  Assert.assertNotNull(this.getDiagnostics().get(path));
  final Function1<List<Diagnostic>, Boolean> _function = (List<Diagnostic> it) -> {
    return Boolean.valueOf(it.isEmpty());
  };
  Assert.assertTrue(IterableExtensions.join(this.getDiagnostics().values(), ","), IterableExtensions.<List<Diagnostic>>forall(this.getDiagnostics().values(), _function));
}
 
Example 11
Source Project: xtext-core   Source File: ServerTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testTwoFilesDeleteClose() {
  final String fileURI = this.writeFile("Foo.testlang", "");
  this.initialize();
  final String referencingFileURI = this.getVirtualFile("Bar.testlang");
  StringConcatenation _builder = new StringConcatenation();
  _builder.append("type Bar {");
  _builder.newLine();
  _builder.append("    ");
  _builder.append("Foo foo");
  _builder.newLine();
  _builder.append("}");
  _builder.newLine();
  this.open(referencingFileURI, _builder.toString());
  Assert.assertFalse("Bar.testlang references missing type Foo from Foo.testlang: expect error", 
    this.getDiagnostics().get(referencingFileURI).isEmpty());
  this.open(fileURI, "type Foo {}");
  Assert.assertTrue("Bar.testlang references type Foo from Foo.testlang: expect no error", 
    this.getDiagnostics().get(referencingFileURI).isEmpty());
  this.deleteFile(fileURI);
  WorkspaceService _workspaceService = this.languageServer.getWorkspaceService();
  FileEvent _fileEvent = new FileEvent(fileURI, FileChangeType.Deleted);
  DidChangeWatchedFilesParams _didChangeWatchedFilesParams = new DidChangeWatchedFilesParams(Collections.<FileEvent>unmodifiableList(CollectionLiterals.<FileEvent>newArrayList(_fileEvent)));
  _workspaceService.didChangeWatchedFiles(_didChangeWatchedFilesParams);
  Assert.assertTrue("delete file on disk: expect no error", this.getDiagnostics().get(referencingFileURI).isEmpty());
  this.close(fileURI);
  Assert.assertFalse("close deleted file: expect error", this.getDiagnostics().get(referencingFileURI).isEmpty());
}
 
Example 12
Source Project: lsp4intellij   Source File: LSPFileEventManager.java    License: Apache License 2.0 4 votes vote down vote up
@NotNull
private static DidChangeWatchedFilesParams getDidChangeWatchedFilesParams(String fileUri, FileChangeType typ) {
    List<FileEvent> event = new ArrayList<>();
    event.add(new FileEvent(fileUri, typ));
    return new DidChangeWatchedFilesParams(event);
}
 
Example 13
Source Project: lemminx   Source File: XMLExternalTest.java    License: Eclipse Public License 2.0 4 votes vote down vote up
private void didChangedWatchedFiles(XMLLanguageServer ls, File file) {
	List<FileEvent> changes = new ArrayList<>();
	changes.add(new FileEvent(file.toURI().toString(), FileChangeType.Changed));
	DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams(changes);
	ls.getWorkspaceService().didChangeWatchedFiles(params);
}
 
Example 14
@Override
public void didChangeWatchedFiles(DidChangeWatchedFilesParams params) {
	List<FileEvent> settings = params.getChanges();
	LOGGER.info("SERVER: changeWatchedFiles: size -> {}", settings.size());
}
 
Example 15
Source Project: vscode-as3mxml   Source File: ActionScriptServices.java    License: Apache License 2.0 4 votes vote down vote up
private void createSourcePathWatcher()
{
    try
    {
        sourcePathWatcher = FileSystems.getDefault().newWatchService();
    }
    catch (IOException e)
    {
        System.err.println("Failed to get watch service for source paths.");
        e.printStackTrace(System.err);
    }
    sourcePathWatcherThread = new Thread()
    {
        public void run()
        {
            while(true)
            {
                WatchKey watchKey = null;
                try
                {
                    //pause the thread while there are no changes pending,
                    //for better performance
                    watchKey = sourcePathWatcher.take();
                }
                catch(InterruptedException e)
                {
                    return;
                }
                List<FileEvent> changes = new ArrayList<>();
                while (watchKey != null)
                {
                    for (WorkspaceFolder folder : workspaceFolderManager.getWorkspaceFolders())
                    {
                        WorkspaceFolderData folderData = workspaceFolderManager.getWorkspaceFolderData(folder);
                        if(!folderData.sourceOrLibraryPathWatchKeys.containsKey(watchKey))
                        {
                            continue;
                        }
                        Path path = folderData.sourceOrLibraryPathWatchKeys.get(watchKey);
                        for (WatchEvent<?> event : watchKey.pollEvents())
                        {
                            WatchEvent.Kind<?> kind = event.kind();
                            Path childPath = (Path) event.context();
                            childPath = path.resolve(childPath);
                            if(java.nio.file.Files.isDirectory(childPath))
                            {
                                if(kind.equals(StandardWatchEventKinds.ENTRY_CREATE))
                                {
                                    //if a new directory has been created under
                                    //an existing that we're already watching,
                                    //then start watching the new one too.
                                    watchNewSourceOrLibraryPath(childPath, folderData);
                                }
                            }
                            FileChangeType changeType = FileChangeType.Changed;
                            if(kind.equals(StandardWatchEventKinds.ENTRY_CREATE))
                            {
                                changeType = FileChangeType.Created;
                            }
                            else if(kind.equals(StandardWatchEventKinds.ENTRY_DELETE))
                            {
                                changeType = FileChangeType.Deleted;
                            }
                            changes.add(new FileEvent(childPath.toUri().toString(), changeType));
                        }
                        boolean valid = watchKey.reset();
                        if (!valid)
                        {
                            folderData.sourceOrLibraryPathWatchKeys.remove(watchKey);
                        }
                    }
                    //keep handling new changes until we run out
                    watchKey = sourcePathWatcher.poll();
                }
                if (changes.size() > 0)
                {
                    //convert to DidChangeWatchedFilesParams and pass
                    //to didChangeWatchedFiles, as if a notification
                    //had been sent from the client.
                    DidChangeWatchedFilesParams params = new DidChangeWatchedFilesParams();
                    params.setChanges(changes);
                    didChangeWatchedFiles(params);
                }
            }
        }
    };
    sourcePathWatcherThread.start();
}
 
Example 16
Source Project: lsp4j   Source File: DidChangeWatchedFilesParams.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public DidChangeWatchedFilesParams() {
  this(new ArrayList<FileEvent>());
}
 
Example 17
Source Project: lsp4j   Source File: DidChangeWatchedFilesParams.java    License: Eclipse Public License 2.0 4 votes vote down vote up
public DidChangeWatchedFilesParams(@NonNull final List<FileEvent> changes) {
  this.changes = Preconditions.<List<FileEvent>>checkNotNull(changes, "changes");
}
 
Example 18
Source Project: lsp4j   Source File: DidChangeWatchedFilesParams.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * The actual file events.
 */
@Pure
@NonNull
public List<FileEvent> getChanges() {
  return this.changes;
}
 
Example 19
Source Project: lsp4j   Source File: DidChangeWatchedFilesParams.java    License: Eclipse Public License 2.0 4 votes vote down vote up
/**
 * The actual file events.
 */
public void setChanges(@NonNull final List<FileEvent> changes) {
  this.changes = Preconditions.checkNotNull(changes, "changes");
}