下面列出了怎么用org.eclipse.lsp4j.Diagnostic的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
private void createMarkers(Editor editor, Document document, List<Diagnostic> diagnostics) {
RangeHighlighter[] rangeHighlighters = new RangeHighlighter[diagnostics.size()];
int index = 0;
for(Diagnostic diagnostic : diagnostics) {
int startOffset = LSPIJUtils.toOffset(diagnostic.getRange().getStart(), document);
int endOffset = LSPIJUtils.toOffset(diagnostic.getRange().getEnd(), document);
if (endOffset > document.getLineEndOffset(document.getLineCount() - 1)) {
endOffset = document.getLineEndOffset(document.getLineCount() - 1);
}
int layer = getLayer(diagnostic.getSeverity());
EffectType effectType = getEffectType(diagnostic.getSeverity());
Color color = getColor(diagnostic.getSeverity());
RangeHighlighter rangeHighlighter = editor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, layer, new TextAttributes(editor.getColorsScheme().getDefaultForeground(), editor.getColorsScheme().getDefaultBackground(), color, effectType, Font.PLAIN), HighlighterTargetArea.EXACT_RANGE);
rangeHighlighter.setErrorStripeTooltip(diagnostic);
rangeHighlighters[index++] = rangeHighlighter;
}
Map<String, RangeHighlighter[]> allMarkers = getAllMarkers(editor);
allMarkers.put(languageServerId, rangeHighlighters);
}
@Test
public void testMultilineDiagnostic_02() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("type Multiline_Demo2 {");
_builder.newLine();
_builder.append("string sample}");
_builder.newLine();
this.writeFile("MyType1.testlang", Strings.toUnixLineSeparator(_builder));
this.initialize();
final List<Diagnostic> problems = IterableExtensions.<Map.Entry<String, List<Diagnostic>>>head(this.getDiagnostics().entrySet()).getValue();
String _join = IterableExtensions.join(problems, "\n");
String _plus = ("problems found:\n" + _join);
Assert.assertEquals(_plus, 1, problems.size());
final Diagnostic problem = IterableExtensions.<Diagnostic>head(problems);
this.assertEquals("Test Validation to mark the whole type", problem.getMessage());
Assert.assertEquals(TestLanguageValidator.MULTILINE_PROBLEM, problem.getCode().get());
final Range range = problem.getRange();
Assert.assertEquals(0, range.getStart().getLine());
Assert.assertEquals(0, range.getStart().getCharacter());
Assert.assertEquals(1, range.getEnd().getLine());
Assert.assertEquals(14, range.getEnd().getCharacter());
}
/**
* ElementUnterminated tests
*
* @see https://wiki.xmldation.com/Support/Validator/ElementUnterminated
* @throws Exception
*/
@Test
public void elementUnterminated() throws Exception {
String xml = "<Id>\r\n" + //
" <OrgId\r\n" + //
" <Othr>\r\n" + //
" <Id> 222010012</Id>\r\n" + //
" </Othr>\r\n" + //
" </OrgId>\r\n" + //
" </Id>";
Diagnostic d = d(1, 11, 1, 16, XMLSyntaxErrorCode.ElementUnterminated);
testDiagnosticsFor(xml, d);
testCodeActionsFor(xml, d, //
ca(d, te(1, 16, 1, 16, "/>")), //
ca(d, te(1, 16, 1, 16, "></OrgId>")), //
ca(d, te(1, 16, 1, 16, ">")));
}
@Test
public void testDiagnosticAtEndOfLineIncludingNewline() {
StringConcatenation _builder = new StringConcatenation();
_builder.append("type");
_builder.newLine();
this.writeFile("MyType1.testlang", Strings.toUnixLineSeparator(_builder));
this.initialize();
final List<Diagnostic> problems = IterableExtensions.<Map.Entry<String, List<Diagnostic>>>head(this.getDiagnostics().entrySet()).getValue();
String _join = IterableExtensions.join(problems, "\n");
String _plus = ("problems found:\n" + _join);
Assert.assertEquals(_plus, 1, problems.size());
final Diagnostic problem = IterableExtensions.<Diagnostic>head(problems);
this.assertEquals("mismatched input \'<EOF>\' expecting RULE_ID", problem.getMessage());
Assert.assertEquals(org.eclipse.xtext.diagnostics.Diagnostic.SYNTAX_DIAGNOSTIC, problem.getCode().get());
final Range range = problem.getRange();
Assert.assertEquals(0, range.getStart().getLine());
Assert.assertEquals(4, range.getStart().getCharacter());
Assert.assertEquals(1, range.getEnd().getLine());
Assert.assertEquals(0, range.getEnd().getCharacter());
}
public static void assertDiagnostics(List<Diagnostic> actual, List<Diagnostic> expected, boolean filter) {
List<Diagnostic> received = actual;
final boolean filterMessage;
if (expected != null && !expected.isEmpty()
&& (expected.get(0).getMessage() == null || expected.get(0).getMessage().isEmpty())) {
filterMessage = true;
} else {
filterMessage = false;
}
if (filter) {
received = actual.stream().map(d -> {
Diagnostic simpler = new Diagnostic(d.getRange(), "");
simpler.setCode(d.getCode());
if (filterMessage) {
simpler.setMessage(d.getMessage());
}
return simpler;
}).collect(Collectors.toList());
}
Assert.assertEquals("Unexpected diagnostics:\n" + actual, expected, received);
}
@Test
public void cvc_enumeration_validOnText() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //
"<team\r\n" + //
" xmlns=\"team_namespace\"\r\n" + //
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //
" xsi:schemaLocation=\"team_namespace src/test/resources/xsd/team.xsd \">\r\n" + //
" <member\r\n" + //
" name=\"John\"\r\n" + //
" badgeNumber=\"1\"\r\n" + //
" role=\"architect\">\r\n" + //
" <skills>\r\n" + //
" <skill>XXXXX</skill>\r\n" + // <- error
" </skills> \r\n" + //
" <focus>\r\n" + //
" <server\r\n" + //
" language=\"Java\" />\r\n" + //
" </focus>\r\n" + //
" </member>\r\n" + //
"</team>";
Diagnostic d = d(10, 10, 10, 15, XMLSchemaErrorCode.cvc_enumeration_valid);
testDiagnosticsFor(xml, d, d(10, 10, 10, 15, XMLSchemaErrorCode.cvc_type_3_1_3));
testCodeActionsFor(xml, d, ca(d, te(10, 10, 10, 15, "Java")), ca(d, te(10, 10, 10, 15, "Node")),
ca(d, te(10, 10, 10, 15, "XML")));
}
/**
* 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;
}
@Test
public void testMavenMarkers() throws Exception {
String msg1 = "Some dependency is missing";
IMarker m1 = createMavenMarker(IMarker.SEVERITY_ERROR, msg1, 2, 95, 100);
IDocument d = mock(IDocument.class);
when(d.getLineOffset(1)).thenReturn(90);
List<Diagnostic> diags = WorkspaceDiagnosticsHandler.toDiagnosticsArray(d, new IMarker[] { m1, null }, true);
assertEquals(1, diags.size());
Range r;
Diagnostic d1 = diags.get(0);
assertEquals(msg1, d1.getMessage());
assertEquals(DiagnosticSeverity.Error, d1.getSeverity());
r = d1.getRange();
assertEquals(1, r.getStart().getLine());
assertEquals(95, r.getStart().getCharacter());
assertEquals(1, r.getEnd().getLine());
assertEquals(100, r.getEnd().getCharacter());
}
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
SharedSettings sharedSettings, IComponentProvider componentProvider) {
try {
int offset = document.offsetAt(range.getStart());
DOMNode node = document.findNodeAt(offset);
if (node != null && node.isElement()) {
DOMElement element = (DOMElement) node;
int startOffset = element.getStartTagOpenOffset();
int endOffset;
if (element.isSelfClosed()) {
endOffset = element.getEnd();
} else {
endOffset = element.getEndTagCloseOffset() + 1;
}
Range diagnosticRange = XMLPositionUtility.createRange(startOffset, endOffset, document);
CodeAction removeContentAction = CodeActionFactory.remove("Remove element", diagnosticRange, document.getTextDocument(), diagnostic);
codeActions.add(removeContentAction);
}
} catch (BadLocationException e) {
// Do nothing
}
}
@Test
public void cvc_pattern_valid_With_Buffer() throws Exception {
String xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\r\n" +
"<cpr xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \r\n" +
" xsi:noNamespaceSchemaLocation=\"https://www.dgai.de/cpr/schema/ev/cpr-ev-2.0.xsd\">\r\n" +
" <cprev>\r\n" +
" <VERSION>2.0</VERSION>\r\n" +
" <DATUM>2019-08-09</DATUM>\r\n" +
" <STOKENN>FIX_ERROR_RANGE_HERE</STOKENN>\r\n" + // <-- Error should follow pattern [0-9]{8}
" </cprev>\r\n" +
"</cpr>";
Diagnostic patternValid = d(6, 17, 6, 37, XMLSchemaErrorCode.cvc_pattern_valid);
Diagnostic cvcType313 = d(6, 17, 6, 37, XMLSchemaErrorCode.cvc_type_3_1_3);
Diagnostic cvcType24b = d(3, 5, 3, 10, XMLSchemaErrorCode.cvc_complex_type_2_4_b);
testDiagnosticsFor(xml, patternValid, cvcType313, cvcType24b);
}
@Test
public void testDeprecated() 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("import java.security.Certificate;\n");
ICompilationUnit cu = pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, monitor);
IProblem[] problems = astRoot.getProblems();
List<Diagnostic> diagnostics = DiagnosticsHandler.toDiagnosticsArray(cu, Arrays.asList(problems), true);
assertEquals(2, diagnostics.size());
List<DiagnosticTag> tags = diagnostics.get(0).getTags();
assertEquals(1, tags.size());
assertEquals(DiagnosticTag.Deprecated, tags.get(0));
}
public Collection<Diagnostic> converToLSPDiagnostics(Map<String, ConfigurationPropertiesValidationResult> configurationPropertiesErrors) {
List<Diagnostic> lspDiagnostics = new ArrayList<>();
for (Map.Entry<String, ConfigurationPropertiesValidationResult> errorEntry : configurationPropertiesErrors.entrySet()) {
ConfigurationPropertiesValidationResult validationResult = errorEntry.getValue();
String lineContentInError = errorEntry.getKey();
List<Diagnostic> unknownParameterDiagnostics = computeUnknowParameters(validationResult, lineContentInError);
lspDiagnostics.addAll(unknownParameterDiagnostics);
List<Diagnostic> invalidEnumDiagnostics = computeInvalidEnumsDiagnostic(validationResult, lineContentInError);
lspDiagnostics.addAll(invalidEnumDiagnostics);
if (invalidEnumDiagnostics.size() + unknownParameterDiagnostics.size() < validationResult.getNumberOfErrors()) {
lspDiagnostics.add(new Diagnostic(
computeRange(validationResult, lineContentInError, lineContentInError),
computeErrorMessage(validationResult),
DiagnosticSeverity.Error,
APACHE_CAMEL_VALIDATION,
null));
}
}
return lspDiagnostics;
}
@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());
}
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
SharedSettings sharedSettings, IComponentProvider componentProvider) {
String missingFilePath = getPathFromDiagnostic(diagnostic);
if (StringUtils.isEmpty(missingFilePath)) {
return;
}
Path p = Paths.get(missingFilePath);
if (p.toFile().exists()) {
return;
}
// Generate XSD from the DOM document
FileContentGeneratorManager generator = componentProvider.getComponent(FileContentGeneratorManager.class);
String schemaTemplate = generator.generate(document, sharedSettings, getFileContentGeneratorSettings());
// Create code action to create the XSD file with the generated XSD content
CodeAction makeSchemaFile = CodeActionFactory.createFile("Generate missing file '" + p.toFile().getName() + "'",
"file:///" + missingFilePath, schemaTemplate, diagnostic);
codeActions.add(makeSchemaFile);
}
@Test
public void fuzzyElementNameCodeActionTest() throws Exception {
String xml =
"<project xmlns=\"http://maven.apache.org/POM/4.0.0\" \r\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" +
" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\r\n" +
" <modules>\r\n" +
" <bodule></bodule>\r\n" + // should be 'module'
" </modules>\r\n" +
"</project>";
Diagnostic diagnostic = d(4, 7, 4, 13, XMLSchemaErrorCode.cvc_complex_type_2_4_a,
"Invalid element name:\n - bodule\n\nOne of the following is expected:\n - module\n\nError indicated by:\n {http://maven.apache.org/POM/4.0.0}\nwith code:");
testDiagnosticsFor(xml, diagnostic);
testCodeActionsFor(xml, diagnostic, ca(diagnostic, te(4, 7, 4, 13, "module"), te(4, 16, 4, 22, "module")));
}
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
SharedSettings sharedSettings, IComponentProvider componentProvider) {
String namespace = extractNamespace(diagnostic.getMessage());
if (StringUtils.isEmpty(namespace)) {
return;
}
DOMNode root = document.getDocumentElement();
if (root == null) {
return;
}
Position tagEnd = XMLPositionUtility.selectStartTagName(root).getEnd();
String quote = sharedSettings.getPreferences().getQuotationAsString();
// @formatter:off
CodeAction addNamespaceDecl = CodeActionFactory.insert(
"Declare '" + namespace + "' as the namespace",
tagEnd,
" xmlns=" + quote + namespace + quote,
document.getTextDocument(),
diagnostic);
// @formatter:on
codeActions.add(addNamespaceDecl);
}
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
SharedSettings sharedSettings, IComponentProvider componentProvider) {
try {
String prefix = document.getDocumentElement().getPrefix();
CodeAction namespace = createNamespaceCodeAction(diagnostic, range, document, prefix);
CodeAction targetNamespace = createTargetNamespaceCodeAction(diagnostic, document, prefix);
if (namespace != null) {
codeActions.add(namespace);
}
if (targetNamespace != null) {
codeActions.add(targetNamespace);
}
} catch (BadLocationException e) {
// Do nothing
}
}
@Test
public void cos_all_limited_2_multiple() throws BadLocationException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //
"<xs:schema \r\n" + //
" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\r\n" + //
" \r\n" + //
" <xs:complexType name=\"testType\">\r\n" + //
" <xs:all>\r\n" + //
" <xs:element name=\"testEle1\" minOccurs=\"2\" maxOccurs=\"unbounded\" type=\"xs:string\"/>\r\n" + //
" <xs:element name=\"testEle2\" minOccurs=\"2\" maxOccurs=\"unbounded\" type=\"xs:string\"/>\r\n" + //
" <xs:element name=\"test3\" minOccurs=\"2\" maxOccurs=\"unbounded\" type=\"xs:string\"/>\r\n" + //
" </xs:all>\r\n" + //
" </xs:complexType>\r\n" + //
"</xs:schema>";
Diagnostic first = d(6, 55, 6, 66, XSDErrorCode.cos_all_limited_2);
Diagnostic second = d(7, 55, 7, 66, XSDErrorCode.cos_all_limited_2);
Diagnostic third = d(8, 52, 8, 63, XSDErrorCode.cos_all_limited_2);
testDiagnosticsFor(xml, first, second, third);
}
@Test
public void src_import_1_2_different_range() throws BadLocationException {
String xml = "<?xml version=\'1.0\'?>\r\n" +
"<xs:schema xmlns:xs=\'http://www.w3.org/2001/XMLSchema\'>\r\n" +
" <xs:imp|ort></xs:import>\r\n" +
"</xs:schema>";
Diagnostic d = d(2, 2, 2, 11, XSDErrorCode.src_import_1_2);
testCodeActionsFor(xml, d, ca(d, te(2, 11, 2, 11, " namespace=\"\"")), ca(d, te(1, 54, 1, 54, " targetNamespace=\"\"")));
}
@Test
public void schemaWithUrlWithoutCache() throws Exception {
// Here we test the following context:
// - XML which have xsi:noNamespaceSchemaLocation="http://invoice.xsd"
// - XMLCacheResolverExtension which is disabled
// Result of test is to have one published diagnostics with several Xerces
// errors (schema)
Consumer<XMLLanguageService> configuration = ls -> {
ContentModelManager contentModelManager = ls.getComponent(ContentModelManager.class);
// Use cache on file system
contentModelManager.setUseCache(false);
};
String fileURI = "test.xml";
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //
"<invoice xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n" + //
" xsi:noNamespaceSchemaLocation=\"http://invoice.xsd\">\r\n" + //
"</invoice> \r\n" + //
"";
XMLAssert.testPublishDiagnosticsFor(xml, fileURI, configuration, pd(fileURI, //
new Diagnostic(r(2, 31, 2, 51),
"schema_reference.4: Failed to read schema document 'http://invoice.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.",
DiagnosticSeverity.Warning, "xml", "schema_reference.4"), //
new Diagnostic(r(1, 1, 1, 8), "cvc-elt.1.a: Cannot find the declaration of element 'invoice'.",
DiagnosticSeverity.Error, "xml", "cvc-elt.1.a")));
}
private void registerIssue(EObject object, CustomValidationMessageAcceptor messageAcceptor, Diagnostic diagnostic,
DocumentContext documentContext, Document doc, ProjectContext projectContext)
{
Optional<Class<? extends BSLDiagnostic>> diagnosticClass =
projectContext.diagnosticSupplier.getDiagnosticClass(diagnostic.getCode());
if (!diagnosticClass.isPresent())
return;
Class<? extends BSLDiagnostic> bslDiagnosticClass = diagnosticClass.get();
DiagnosticInfo diagnosticInfo = new DiagnosticInfo(bslDiagnosticClass, projectContext.diagnosticLanguage);
Integer[] offsetAndLength = getOffsetAndLength(diagnostic.getRange(), doc);
Integer offset = offsetAndLength[0];
Integer length = offsetAndLength[1];
StringBuilder issueData = getIssueData(diagnostic, bslDiagnosticClass, documentContext, doc, projectContext);
String diagnosticMessage = BSL_LS_PREFIX.concat(diagnostic.getMessage());
DiagnosticType diagnosticType = diagnosticInfo.getType();
if (diagnosticType.equals(DiagnosticType.ERROR) || diagnosticType.equals(DiagnosticType.VULNERABILITY))
messageAcceptor.acceptError(diagnosticMessage, object, offset, length, QUICKFIX_CODE, issueData.toString());
else
messageAcceptor.acceptWarning(diagnosticMessage, object, offset, length, QUICKFIX_CODE,
issueData.toString());
}
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
VirtualFile virtualFile = file.getVirtualFile();
if (virtualFile != null) {
Editor editor = LSPIJUtils.editorForFile(virtualFile);
if (editor != null) {
List<ProblemDescriptor> problemDescriptors = new ArrayList<>();
try {
for(LanguageServerWrapper wrapper : LanguageServiceAccessor.getInstance(file.getProject()).getLSWrappers(virtualFile, capabilities -> true)) {
RangeHighlighter[] highlighters = LSPDiagnosticsToMarkers.getMarkers(editor, wrapper.serverDefinition.id);
if (highlighters != null) {
for(RangeHighlighter highlighter : highlighters) {
PsiElement element = new LSPPSiElement(editor.getProject(), file, highlighter.getStartOffset(), highlighter.getEndOffset(), editor.getDocument().getText(new TextRange(highlighter.getStartOffset(), highlighter.getEndOffset())));
ProblemHighlightType highlightType = getHighlighType(((Diagnostic)highlighter.getErrorStripeTooltip()).getSeverity());
problemDescriptors.add(manager.createProblemDescriptor(element, ((Diagnostic)highlighter.getErrorStripeTooltip()).getMessage(), true, highlightType, isOnTheFly));
}
}
}
} catch (IOException e) {
LOGGER.warn(e.getLocalizedMessage(), e);
}
return problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()]);
}
}
return super.checkFile(file, manager, isOnTheFly);
}
@Override
public List<Diagnostic> collectDiagnostics(JavaDiagnosticsContext context) {
PsiFile typeRoot = context.getTypeRoot();
PsiElement[] elements = typeRoot.getChildren();
List<Diagnostic> diagnostics = new ArrayList<>();
collectDiagnostics(elements, diagnostics, context);
return diagnostics;
}
@Test
public void testMarkupEntityMismatchWithAttributes() throws Exception {
String xml = "<ABC a='' ";
Diagnostic d = d(0, 1, 0, 9, XMLSyntaxErrorCode.MarkupEntityMismatch);
testDiagnosticsFor(xml, d);
testCodeActionsFor(xml, d, //
ca(d, te(0, 9, 0, 9, "/>")), //
ca(d, te(0, 9, 0, 9, "></ABC>")), //
ca(d, te(0, 9, 0, 9, ">")));
}
protected String retrieveCurrentErrorValue(TextDocumentItem openedDocument, Diagnostic diagnostic) {
Range diagnosticRange = diagnostic.getRange();
String line = new ParserFileHelperUtil().getLine(openedDocument, diagnosticRange.getStart().getLine());
int endCharacter = diagnosticRange.getEnd().getCharacter();
if (line.length() > endCharacter) {
return line.substring(diagnosticRange.getStart().getCharacter(), endCharacter);
} else {
return null;
}
}
@Test
public void EntityNotDeclaredWithPrologNoDoctype() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" + //
"<article>\r\n" + //
" \r\n" + //
"</article>";
Diagnostic d = d(2, 1, 2, 7, DTDErrorCode.EntityNotDeclared, "The entity \"nbsp\" was referenced, but not declared.");
XMLAssert.testDiagnosticsFor(xml, d);
testCodeActionsFor(xml, d, ca(d, te(0, 38, 0, 38, "\r\n<!DOCTYPE article [\r\n" +
"\t<!ENTITY nbsp \"entity-value\">\r\n" +
"]>")));
}
@Test
public void testRestClientAnnotationMissingForInterface() throws Exception {
ApplicationManager.getApplication().invokeAndWait(() -> {
Module module = getModule("rest-client-quickstart.main");
MicroProfileJavaDiagnosticsParams params = new MicroProfileJavaDiagnosticsParams();
VirtualFile javaFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(ModuleUtilCore.getModuleDirPath(module) + "/src/main/java/org/acme/restclient/MyService.java");
String uri = VfsUtilCore.virtualToIoFile(javaFile).toURI().toString();
params.setUris(Arrays.asList(uri));
params.setDocumentFormat(DocumentFormat.Markdown);
Diagnostic d = d(2, 17, 26,
"The interface `MyService` does not have the @RegisterRestClient annotation. The 1 fields references will not be injected as CDI beans.",
DiagnosticSeverity.Warning, MicroProfileRestClientConstants.DIAGNOSTIC_SOURCE,
MicroProfileRestClientErrorCode.RegisterRestClientAnnotationMissing);
assertJavaDiagnostics(params, utils, //
d);
/*String uri = javaFile.getLocation().toFile().toURI().toString();
MicroProfileJavaCodeActionParams codeActionParams = createCodeActionParams(uri, d);
assertJavaCodeAction(codeActionParams, utils, //
ca(uri, "Insert @RegisterRestClient", d, //
te(0, 28, 2, 0,
"\r\n\r\nimport org.eclipse.microprofile.rest.client.inject.RegisterRestClient;\r\n\r\[email protected]\r\n")));*/
});
}
@Test
void testUnknownParameterPropertiesFile() throws Exception {
testDiagnostic("camel-with-unknownParameter", 1);
Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
Range range1 = diagnostic.getRange();
checkRange(range1, 0, 22, 0, 38);
assertThat(diagnostic.getMessage()).isEqualTo("Unknown option");
}
public void computeDiagnostics(String camelText, String uri) {
CompletableFuture.runAsync(() -> {
Map<CamelEndpointDetails, EndpointValidationResult> endpointErrors = endpointDiagnosticService.computeCamelEndpointErrors(camelText, uri);
TextDocumentItem openedDocument = camelLanguageServer.getTextDocumentService().getOpenedDocument(uri);
List<Diagnostic> diagnostics = endpointDiagnosticService.converToLSPDiagnostics(camelText, endpointErrors, openedDocument);
Map<String, ConfigurationPropertiesValidationResult> configurationPropertiesErrors = configurationPropertiesDiagnosticService.computeCamelConfigurationPropertiesErrors(camelText, uri);
diagnostics.addAll(configurationPropertiesDiagnosticService.converToLSPDiagnostics(configurationPropertiesErrors));
camelLanguageServer.getClient().publishDiagnostics(new PublishDiagnosticsParams(uri, diagnostics));
});
}