org.eclipse.lsp4j.PublishDiagnosticsParams Java Examples

The following examples show how to use org.eclipse.lsp4j.PublishDiagnosticsParams. 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: LanguageClientImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void publishDiagnostics(PublishDiagnosticsParams pdp) {
    try {
        FileObject file = URLMapper.findFileObject(new URI(pdp.getUri()).toURL());
        EditorCookie ec = file.getLookup().lookup(EditorCookie.class);
        Document doc = ec != null ? ec.getDocument() : null;
        if (doc == null)
            return ; //ignore...
        List<ErrorDescription> diags = pdp.getDiagnostics().stream().map(d -> {
            LazyFixList fixList = allowCodeActions ? new DiagnosticFixList(pdp.getUri(), d) : ErrorDescriptionFactory.lazyListForFixes(Collections.emptyList());
            return ErrorDescriptionFactory.createErrorDescription(severityMap.get(d.getSeverity()), d.getMessage(), fixList, file, Utils.getOffset(doc, d.getRange().getStart()), Utils.getOffset(doc, d.getRange().getEnd()));
        }).collect(Collectors.toList());
        HintsController.setErrors(doc, LanguageClientImpl.class.getName(), diags);
    } catch (URISyntaxException | MalformedURLException ex) {
        LOG.log(Level.FINE, null, ex);
    }
}
 
Example #2
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void assertNewProblemReported(ExpectedProblemReport... expectedReports) {
	List<PublishDiagnosticsParams> diags = getClientRequests("publishDiagnostics");
	assertEquals(expectedReports.length, diags.size());

	for (int i = 0; i < expectedReports.length; i++) {
		PublishDiagnosticsParams diag = diags.get(i);
		ExpectedProblemReport expected = expectedReports[i];
		assertEquals(JDTUtils.toURI(expected.cu), diag.getUri());
		if (expected.problemCount != diag.getDiagnostics().size()) {
			String message = "";
			for (Diagnostic d : diag.getDiagnostics()) {
				message += d.getMessage() + ", ";
			}
			assertEquals(message, expected.problemCount, diag.getDiagnostics().size());
		}

	}
	diags.clear();
}
 
Example #3
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testReconcile() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("test1", false, null);
	StringBuilder buf = new StringBuilder();
	buf.append("package test1;\n");
	buf.append("public class E123 {\n");
	buf.append("    public void testing() {\n");
	buf.append("        int someIntegerChanged = 5;\n");
	buf.append("        int i = someInteger + 5\n");
	buf.append("    }\n");
	buf.append("}\n");
	ICompilationUnit cu1 = pack1.createCompilationUnit("E123.java", buf.toString(), false, null);
	openDocument(cu1, cu1.getSource(), 1);
	assertEquals(true, cu1.isWorkingCopy());
	assertEquals(false, cu1.hasUnsavedChanges());
	List<PublishDiagnosticsParams> diagnosticsParams = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticsParams.size());
	PublishDiagnosticsParams diagnosticsParam = diagnosticsParams.get(0);
	List<Diagnostic> diagnostics = diagnosticsParam.getDiagnostics();
	assertEquals(2, diagnostics.size());
	diagnosticsParams.clear();
	closeDocument(cu1);
}
 
Example #4
Source File: N4jscLanguageClient.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {
	List<Diagnostic> issueList = diagnostics.getDiagnostics();
	if (issueList.isEmpty()) {
		return;
	}

	synchronized (this) {
		N4jscConsole.println(issueSerializer.uri(diagnostics.getUri()));
		for (Diagnostic diag : issueList) {
			N4jscConsole.println(issueSerializer.diagnostics(diag));
			switch (diag.getSeverity()) {
			case Error:
				errCount++;
				break;
			case Warning:
				wrnCount++;
				break;
			default:
				break;
			}
		}
	}
}
 
Example #5
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testProjectLevelMarkers() throws Exception {
	//import project
	importProjects("maven/broken");
	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());
	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	Collections.reverse(allCalls);
	projectsManager.setConnection(client);
	Optional<PublishDiagnosticsParams> projectDiags = allCalls.stream().filter(p -> p.getUri().endsWith("maven/broken")).findFirst();
	assertTrue("No maven/broken errors were found", projectDiags.isPresent());
	List<Diagnostic> diags = projectDiags.get().getDiagnostics();
	Collections.sort(diags, DIAGNOSTICS_COMPARATOR);
	assertEquals(diags.toString(), 3, diags.size());
	assertTrue(diags.get(2).getMessage().startsWith("The compiler compliance specified is 1.7 but a JRE 1.8 is used"));
	Optional<PublishDiagnosticsParams> pomDiags = allCalls.stream().filter(p -> p.getUri().endsWith("pom.xml")).findFirst();
	assertTrue("No pom.xml errors were found", pomDiags.isPresent());
	diags = pomDiags.get().getDiagnostics();
	Collections.sort(diags, DIAGNOSTICS_COMPARATOR);
	assertEquals(diags.toString(), 1, diags.size());
	assertTrue(diags.get(0).getMessage().startsWith("Project build error: "));
}
 
Example #6
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDidOpenNotOnClasspath() throws Exception {
	importProjects("eclipse/hello");
	IProject project = WorkspaceHelper.getProject("hello");
	URI uri = project.getFile("nopackage/Test2.java").getRawLocationURI();
	ICompilationUnit cu = JDTUtils.resolveCompilationUnit(uri);
	String source = FileUtils.readFileToString(FileUtils.toFile(uri.toURL()));
	openDocument(cu, source, 1);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	assertEquals(project, cu.getJavaProject().getProject());
	assertEquals(source, cu.getSource());
	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(2, diagParam.getDiagnostics().size());
	closeDocument(cu);
	Job.getJobManager().join(DocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);
	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(0, diagParam.getDiagnostics().size());
}
 
Example #7
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static void publishDiagnostics(DOMDocument xmlDocument, List<PublishDiagnosticsParams> actual,
		XMLLanguageService languageService) {
	CompletableFuture<Path> error = languageService.publishDiagnostics(xmlDocument, params -> {
		actual.add(params);
	}, (doc) -> {
		// Retrigger validation
		publishDiagnostics(xmlDocument, actual, languageService);
	}, null, () -> {
	});

	if (error != null) {
		try {
			error.join();
			// Wait for 500 ms to collect the last params
			Thread.sleep(200);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example #8
Source File: XMLAssert.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
public static void testPublishDiagnosticsFor(String xml, String fileURI, Consumer<XMLLanguageService> configuration,
		PublishDiagnosticsParams... expected) {
	List<PublishDiagnosticsParams> actual = new ArrayList<>();
	XMLLanguageService xmlLanguageService = new XMLLanguageService();
	if (configuration != null) {
		xmlLanguageService.initializeIfNeeded();
		configuration.accept(xmlLanguageService);
	}
	DOMDocument xmlDocument = DOMParser.getInstance().parse(xml, fileURI,
			xmlLanguageService.getResolverExtensionManager());
	xmlLanguageService.setDocumentProvider((uri) -> xmlDocument);

	publishDiagnostics(xmlDocument, actual, xmlLanguageService);

	assertEquals(expected.length, actual.size());
	for (int i = 0; i < expected.length; i++) {
		assertEquals(fileURI, actual.get(i).getUri());
		assertDiagnostics(actual.get(i).getDiagnostics(), expected[i].getDiagnostics(), false);
	}
}
 
Example #9
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDidOpenStandaloneFile() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {"+
			"	public void method1(){\n"+
			"		super.whatever();"+
			"	}\n"+
			"}";
	// @formatter:on
	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(1, diagParam.getDiagnostics().size());
	Diagnostic d = diagParam.getDiagnostics().get(0);
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", d.getMessage());
}
 
Example #10
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private void testDiagnostic(List<PublishDiagnosticsParams> allCalls) {
	List<Diagnostic> projectDiags = new ArrayList<>();
	List<Diagnostic> pomDiags = new ArrayList<>();
	for (PublishDiagnosticsParams diag : allCalls) {
		if (diag.getUri().endsWith("maven/salut")) {
			projectDiags.addAll(diag.getDiagnostics());
		} else if (diag.getUri().endsWith("pom.xml")) {
			pomDiags.addAll(diag.getDiagnostics());
		}
	}
	assertTrue("No maven/salut errors were found", projectDiags.size() > 0);
	Optional<Diagnostic> projectDiag = projectDiags.stream().filter(p -> p.getMessage().contains("references non existing library")).findFirst();
	assertTrue("No 'references non existing library' diagnostic", projectDiag.isPresent());
	assertEquals(projectDiag.get().getSeverity(), DiagnosticSeverity.Error);
	assertTrue("No pom.xml errors were found", pomDiags.size() > 0);
	Optional<Diagnostic> pomDiag = pomDiags.stream().filter(p -> p.getMessage().startsWith("Missing artifact")).findFirst();
	assertTrue("No 'missing artifact' diagnostic", pomDiag.isPresent());
	assertTrue(pomDiag.get().getMessage().startsWith("Missing artifact"));
	assertEquals(pomDiag.get().getRange().getStart().getLine(), 19);
	assertEquals(pomDiag.get().getRange().getStart().getCharacter(), 3);
	assertEquals(pomDiag.get().getRange().getEnd().getLine(), 19);
	assertEquals(pomDiag.get().getRange().getEnd().getCharacter(), 14);
	assertEquals(pomDiag.get().getSeverity(), DiagnosticSeverity.Error);
}
 
Example #11
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDeletePackage() throws Exception {
	importProjects("eclipse/unresolvedtype");
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("unresolvedtype");
	List<IMarker> markers = ResourceUtils.getErrorMarkers(project);
	assertTrue("unresolved type in Foo.java", markers.stream().anyMatch((marker) -> marker.getResource() != null && ((IFile) marker.getResource()).getName().endsWith("Foo.java")));

	reset(connection);
	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	IFolder folder = project.getFolder("/src/pckg");
	assertTrue(folder.exists());
	folder.delete(true, new NullProgressMonitor());
	waitForBackgroundJobs();

	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());
	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	List<PublishDiagnosticsParams> errors = allCalls.stream().filter((p) -> p.getUri().endsWith("Foo.java")).collect(Collectors.toList());
	assertTrue("Should update the children's diagnostics of the deleted package", errors.size() == 1);
	assertTrue("Should clean up the children's diagnostics of the deleted package", errors.get(0).getDiagnostics().isEmpty());
}
 
Example #12
Source File: ProblemTracker.java    From vscode-as3mxml with Apache License 2.0 6 votes vote down vote up
public void releaseStale()
{
    //if any files have been removed, they will still appear in this set, so
    //clear the errors so that they don't persist
    for (URI uri : staleFilesWithProblems)
    {
        PublishDiagnosticsParams publish = new PublishDiagnosticsParams();
        publish.setDiagnostics(new ArrayList<>());
        publish.setUri(uri.toString());
        if (languageClient != null)
        {
            languageClient.publishDiagnostics(publish);
        }
    }
    staleFilesWithProblems.clear();
    HashSet<URI> temp = newFilesWithProblems;
    newFilesWithProblems = staleFilesWithProblems;
    staleFilesWithProblems = temp;
}
 
Example #13
Source File: LSPDiagnosticsToMarkers.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void accept(PublishDiagnosticsParams publishDiagnosticsParams) {
    ApplicationManager.getApplication().invokeLater(() -> {
        VirtualFile file = null;
        try {
            file = LSPIJUtils.findResourceFor(new URI(publishDiagnosticsParams.getUri()));
        } catch (URISyntaxException e) {
            LOGGER.warn(e.getLocalizedMessage(), e);
        }
        if (file != null) {
            Document document = FileDocumentManager.getInstance().getDocument(file);
            if (document != null) {
                Editor[] editors  = LSPIJUtils.editorsForFile(file, document);
                for(Editor editor : editors) {
                    cleanMarkers(editor);
                    createMarkers(editor, document, publishDiagnosticsParams.getDiagnostics());
                }
            }
        }
    });
}
 
Example #14
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDidClose() throws Exception {
	URI fileURI = openFile("maven/salut4", "src/main/java/java/TestSyntaxError.java");
	Job.getJobManager().join(SyntaxDocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);

	String fileUri = ResourceUtils.fixURI(fileURI);
	TextDocumentIdentifier identifier = new TextDocumentIdentifier(fileUri);
	server.didClose(new DidCloseTextDocumentParams(identifier));
	Job.getJobManager().join(SyntaxDocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	PublishDiagnosticsParams params = diagnosticReports.get(1);
	assertEquals(fileUri, params.getUri());
	assertNotNull(params.getDiagnostics());
	assertTrue(params.getDiagnostics().isEmpty());
}
 
Example #15
Source File: AbstractLanguageServerTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
protected Map<String, List<Diagnostic>> getDiagnostics() {
  try {
    final Function1<CancelIndicator, HashMap<String, List<Diagnostic>>> _function = (CancelIndicator it) -> {
      final HashMap<String, List<Diagnostic>> result = CollectionLiterals.<String, List<Diagnostic>>newHashMap();
      final Function1<Pair<String, Object>, Object> _function_1 = (Pair<String, Object> it_1) -> {
        return it_1.getValue();
      };
      Iterable<PublishDiagnosticsParams> _filter = Iterables.<PublishDiagnosticsParams>filter(ListExtensions.<Pair<String, Object>, Object>map(this.notifications, _function_1), PublishDiagnosticsParams.class);
      for (final PublishDiagnosticsParams diagnostic : _filter) {
        result.put(diagnostic.getUri(), diagnostic.getDiagnostics());
      }
      return result;
    };
    return this.languageServer.getRequestManager().<HashMap<String, List<Diagnostic>>>runRead(_function).get();
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example #16
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
private void clearProblemsForURI(URI uri)
{
    PublishDiagnosticsParams publish = new PublishDiagnosticsParams();
    ArrayList<Diagnostic> diagnostics = new ArrayList<>();
    publish.setDiagnostics(diagnostics);
    publish.setUri(uri.toString());
    if (languageClient != null)
    {
        languageClient.publishDiagnostics(publish);
    }
}
 
Example #17
Source File: ActionScriptServices.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
private void addCompilerProblem(ICompilerProblem problem, PublishDiagnosticsParams publish, boolean isConfigFile)
{
    if (!compilerProblemFilter.isAllowed(problem))
    {
        return;
    }
    Diagnostic diagnostic = LanguageServerCompilerUtils.getDiagnosticFromCompilerProblem(problem);
    if(isConfigFile)
    {
        //clear the range because it isn't relevant
        diagnostic.setRange(new Range(new Position(0, 0), new Position(0, 0)));
    }
    List<Diagnostic> diagnostics = publish.getDiagnostics();
    diagnostics.add(diagnostic);
}
 
Example #18
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testBadLocationException() throws Exception {
	//import project
	importProjects("eclipse/hello");
	IProject project = getProject("hello");
	IFile iFile = project.getFile("/src/test1/A.java");
	File file = iFile.getRawLocation().toFile();
	assertTrue(file.exists());
	iFile = project.getFile("/src/test1/A1.java");
	File destFile = iFile.getRawLocation().toFile();
	assertFalse(destFile.exists());
	FileUtils.copyFile(file, destFile, false);
	String uri = destFile.toPath().toUri().toString();
	project.refreshLocal(IResource.DEPTH_INFINITE, null);
	waitForBackgroundJobs();
	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());
	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	Collections.reverse(allCalls);
	projectsManager.setConnection(client);
	Optional<PublishDiagnosticsParams> param = allCalls.stream().filter(p -> p.getUri().equals(uri)).findFirst();
	assertTrue(param.isPresent());
	List<Diagnostic> diags = param.get().getDiagnostics();
	assertEquals(diags.toString(), 2, diags.size());
	Optional<Diagnostic> d = diags.stream().filter(p -> p.getMessage().equals("The type A is already defined")).findFirst();
	assertTrue(d.isPresent());
	Diagnostic diag = d.get();
	assertTrue(diag.getRange().getStart().getLine() >= 0);
	assertTrue(diag.getRange().getStart().getCharacter() >= 0);
	assertTrue(diag.getRange().getEnd().getLine() >= 0);
	assertTrue(diag.getRange().getEnd().getCharacter() >= 0);
}
 
Example #19
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testProjectConfigurationIsNotUpToDate() throws Exception {
	//import project
	importProjects("maven/salut");
	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject("salut");
	IFile pom = project.getFile("/pom.xml");
	assertTrue(pom.exists());
	ResourceUtils.setContent(pom, ResourceUtils.getContent(pom).replaceAll("1.7", "1.8"));

	ResourcesPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
	assertNoErrors(project);
	List<IMarker> warnings = ResourceUtils.getWarningMarkers(project);

	Optional<IMarker> outOfDateWarning = warnings.stream().filter(w -> Messages.ProjectConfigurationUpdateRequired.equals(ResourceUtils.getMessage(w))).findFirst();
	assertTrue("No out-of-date warning found", outOfDateWarning.isPresent());

	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());
	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	Collections.reverse(allCalls);
	projectsManager.setConnection(client);
	Optional<PublishDiagnosticsParams> projectDiags = allCalls.stream().filter(p -> p.getUri().endsWith("maven/salut")).findFirst();
	assertTrue("No maven/salut errors were found", projectDiags.isPresent());
	List<Diagnostic> diags = projectDiags.get().getDiagnostics();
	assertEquals(diags.toString(), 2, diags.size());
	Optional<PublishDiagnosticsParams> pomDiags = allCalls.stream().filter(p -> p.getUri().endsWith("pom.xml")).findFirst();
	assertTrue("No pom.xml errors were found", pomDiags.isPresent());
	diags = pomDiags.get().getDiagnostics();
	assertEquals(diags.toString(), 1, diags.size());
	Diagnostic diag = diags.get(0);
	assertTrue(diag.getMessage().equals(WorkspaceDiagnosticsHandler.PROJECT_CONFIGURATION_IS_NOT_UP_TO_DATE_WITH_POM_XML));
	assertEquals(diag.getSeverity(), DiagnosticSeverity.Warning);
}
 
Example #20
Source File: GroovyServicesTypeDefinitionTests.java    From groovy-language-server with Apache License 2.0 5 votes vote down vote up
@BeforeEach
void setup() {
	workspaceRoot = Paths.get(System.getProperty("user.dir")).resolve(PATH_WORKSPACE);
	srcRoot = workspaceRoot.resolve(PATH_SRC);
	if (!Files.exists(srcRoot)) {
		srcRoot.toFile().mkdirs();
	}

	services = new GroovyServices(new CompilationUnitFactory());
	services.setWorkspaceRoot(workspaceRoot);
	services.connect(new LanguageClient() {

		@Override
		public void telemetryEvent(Object object) {

		}

		@Override
		public CompletableFuture<MessageActionItem> showMessageRequest(ShowMessageRequestParams requestParams) {
			return null;
		}

		@Override
		public void showMessage(MessageParams messageParams) {

		}

		@Override
		public void publishDiagnostics(PublishDiagnosticsParams diagnostics) {

		}

		@Override
		public void logMessage(MessageParams message) {

		}
	});
}
 
Example #21
Source File: WorkspaceEventHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@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 #22
Source File: DocumentLifeCycleHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testDidOpenStandaloneFileWithSyntaxError() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals("Unexpected number of errors " + diagParam.getDiagnostics(), 2, diagParam.getDiagnostics().size());
	Diagnostic d = diagParam.getDiagnostics().get(0);
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", d.getMessage());
	assertRange(0, 0, 1, d.getRange());
	d = diagParam.getDiagnostics().get(1);
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", d.getMessage());
	assertRange(3, 17, 18, d.getRange());
}
 
Example #23
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMarkerListening() throws Exception {
	//import project
	importProjects("maven/broken");

	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());

	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	Collections.reverse(allCalls);
	projectsManager.setConnection(client);

	/* With Maven 3.6.2 (m2e 1.14), source folders are no longer configured if dependencies are malformed (missing version tag here)
	Optional<PublishDiagnosticsParams> fooDiags = allCalls.stream().filter(p -> p.getUri().endsWith("Foo.java")).findFirst();
	assertTrue("No Foo.java errors were found", fooDiags.isPresent());
	List<Diagnostic> diags = fooDiags.get().getDiagnostics();
	Collections.sort(diags, DIAGNOSTICS_COMPARATOR );
	assertEquals(diags.toString(), 2, diags.size());
	assertEquals("The import org cannot be resolved", diags.get(0).getMessage());
	assertEquals("StringUtils cannot be resolved", diags.get(1).getMessage());
	*/

	Optional<PublishDiagnosticsParams> pomDiags = allCalls.stream().filter(p -> p.getUri().endsWith("pom.xml")).findFirst();
	assertTrue("No pom.xml errors were found", pomDiags.isPresent());
	List<Diagnostic> diags = pomDiags.get().getDiagnostics();
	assertEquals(diags.toString(), 1, diags.size());
	assertEquals("Project build error: 'dependencies.dependency.version' for org.apache.commons:commons-lang3:jar is missing.", diags.get(0).getMessage());
}
 
Example #24
Source File: LanguageServerImpl.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
private void publishDiagnostics(URI uri, Iterable<? extends Issue> issues) {
	initialized.thenAccept((initParams) -> {
		PublishDiagnosticsParams publishDiagnosticsParams = new PublishDiagnosticsParams();
		publishDiagnosticsParams.setUri(uriExtensions.toUriString(uri));
		publishDiagnosticsParams.setDiagnostics(toDiagnostics(issues));
		client.publishDiagnostics(publishDiagnosticsParams);
	});
}
 
Example #25
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMissingNatures() throws Exception {
	//import project
	importProjects("eclipse/wtpproject");
	ArgumentCaptor<PublishDiagnosticsParams> captor = ArgumentCaptor.forClass(PublishDiagnosticsParams.class);
	verify(connection, atLeastOnce()).publishDiagnostics(captor.capture());
	List<PublishDiagnosticsParams> allCalls = captor.getAllValues();
	Collections.reverse(allCalls);
	projectsManager.setConnection(client);
	Optional<PublishDiagnosticsParams> projectDiags = allCalls.stream().filter(p -> p.getUri().endsWith("eclipse/wtpproject")).findFirst();
	assertTrue(projectDiags.isPresent());
	assertEquals("Unexpected diagnostics:\n" + projectDiags.get().getDiagnostics(), 0, projectDiags.get().getDiagnostics().size());
}
 
Example #26
Source File: DiagnosticsCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshDiagnosticsWithReportSyntaxErrors() throws Exception {
	JavaLanguageServerPlugin.getNonProjectDiagnosticsState().setGlobalErrorLevel(ErrorLevel.COMPILATION_ERROR);
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(4, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage());

	DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", true);

	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(2, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(1).getMessage());
}
 
Example #27
Source File: DiagnosticsCommandTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRefreshDiagnosticsWithReportAllErrors() throws Exception {
	IJavaProject javaProject = newDefaultProject();
	IPackageFragmentRoot sourceFolder = javaProject.getPackageFragmentRoot(javaProject.getProject().getFolder("src"));
	IPackageFragment pack1 = sourceFolder.createPackageFragment("java", false, null);

	// @formatter:off
	String standaloneFileContent =
			"package java;\n"+
			"public class Foo extends UnknownType {\n"+
			"	public void method1(){\n"+
			"		super.whatever()\n"+
			"	}\n"+
			"}";
	// @formatter:on

	ICompilationUnit cu1 = pack1.createCompilationUnit("Foo.java", standaloneFileContent, false, null);

	openDocument(cu1, cu1.getSource(), 1);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams diagParam = diagnosticReports.get(0);
	assertEquals(2, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only syntax errors are reported", diagParam.getDiagnostics().get(0).getMessage());

	DiagnosticsCommand.refreshDiagnostics(JDTUtils.toURI(cu1), "thisFile", false);

	diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(2, diagnosticReports.size());
	diagParam = diagnosticReports.get(1);
	assertEquals(4, diagParam.getDiagnostics().size());
	assertEquals("Foo.java is a non-project file, only JDK classes are added to its build path", diagParam.getDiagnostics().get(0).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(1).getMessage());
	assertEquals("UnknownType cannot be resolved to a type", diagParam.getDiagnostics().get(2).getMessage());
	assertEquals("Syntax error, insert \";\" to complete BlockStatements", diagParam.getDiagnostics().get(3).getMessage());
}
 
Example #28
Source File: SyntaxServerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testSyntaxDiagnostics() throws Exception {
	URI fileURI = openFile("maven/salut4", "src/main/java/java/TestSyntaxError.java");
	Job.getJobManager().join(SyntaxDocumentLifeCycleHandler.DOCUMENT_LIFE_CYCLE_JOBS, monitor);

	List<PublishDiagnosticsParams> diagnosticReports = getClientRequests("publishDiagnostics");
	assertEquals(1, diagnosticReports.size());
	PublishDiagnosticsParams params = diagnosticReports.get(0);
	assertEquals(ResourceUtils.fixURI(fileURI), params.getUri());
	assertNotNull(params.getDiagnostics());
	assertEquals(1, params.getDiagnostics().size());
	assertEquals("Syntax error, insert \";\" to complete FieldDeclaration", params.getDiagnostics().get(0).getMessage());
}
 
Example #29
Source File: WorkspaceDiagnosticsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void cleanUpDiagnostics(IResource resource, boolean addTrailingSlash) {
	String uri = JDTUtils.getFileURI(resource);
	if (uri != null) {
		if (addTrailingSlash && !uri.endsWith("/")) {
			uri = uri + "/";
		}
		this.connection.publishDiagnostics(new PublishDiagnosticsParams(ResourceUtils.toClientUri(uri), Collections.emptyList()));
	}
}
 
Example #30
Source File: WorkspaceDiagnosticsHandler.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private void publishMarkers(IProject project, IMarker[] markers) throws CoreException {
	Range range = new Range(new Position(0, 0), new Position(0, 0));

	List<IMarker> projectMarkers = new ArrayList<>(markers.length);

	String uri = JDTUtils.getFileURI(project);
	IFile pom = project.getFile("pom.xml");
	List<IMarker> pomMarkers = new ArrayList<>();
	for (IMarker marker : markers) {
		if (!marker.exists() || CheckMissingNaturesListener.MARKER_TYPE.equals(marker.getType())) {
			continue;
		}
		if (IMavenConstants.MARKER_CONFIGURATION_ID.equals(marker.getType())) {
			pomMarkers.add(marker);
		} else {
			projectMarkers.add(marker);
		}
	}
	List<Diagnostic> diagnostics = toDiagnosticArray(range, projectMarkers, isDiagnosticTagSupported);
	String clientUri = ResourceUtils.toClientUri(uri);
	connection.publishDiagnostics(new PublishDiagnosticsParams(clientUri, diagnostics));
	if (pom.exists()) {
		IDocument document = JsonRpcHelpers.toDocument(pom);
		diagnostics = toDiagnosticsArray(document, pom.findMarkers(null, true, IResource.DEPTH_ZERO), isDiagnosticTagSupported);
		List<Diagnostic> diagnosicts2 = toDiagnosticArray(range, pomMarkers, isDiagnosticTagSupported);
		diagnostics.addAll(diagnosicts2);
		String pomSuffix = clientUri.endsWith("/") ? "pom.xml" : "/pom.xml";
		connection.publishDiagnostics(new PublishDiagnosticsParams(ResourceUtils.toClientUri(clientUri + pomSuffix), diagnostics));
	}
}