org.eclipse.lsp4j.Diagnostic Java Examples

The following examples show how to use org.eclipse.lsp4j.Diagnostic. 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: MicroProfileForJavaAssert.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
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);
}
 
Example #2
Source File: XMLSchemaDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: ValidatorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #5
Source File: ConfigurationPropertiesDiagnosticService.java    From camel-language-server with Apache License 2.0 6 votes vote down vote up
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;
}
 
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 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 #7
Source File: AbstractFixMissingGrammarCodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #8
Source File: XMLSchemaDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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")));
}
 
Example #9
Source File: s4s_elt_invalid_content_3CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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
	}
}
 
Example #10
Source File: TargetNamespace_2CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: XMLSyntaxDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 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, ">")));
}
 
Example #12
Source File: ValidatorTest.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: src_import_1_2CodeAction.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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
	}
}
 
Example #14
Source File: XMLSchemaDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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")));
}
 
Example #15
Source File: LSPDiagnosticsToMarkers.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
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);

}
 
Example #16
Source File: CodeActionFactory.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Makes a CodeAction to create a file and add content to the file.
 * 
 * @param title      The displayed name of the CodeAction
 * @param docURI     The file to create
 * @param content    The text to put into the newly created document.
 * @param diagnostic The diagnostic that this CodeAction will fix
 */
public static CodeAction createFile(String title, String docURI, String content, Diagnostic diagnostic) {

	List<Either<TextDocumentEdit, ResourceOperation>> actionsToTake = new ArrayList<>(2);

	// 1. create an empty file
	actionsToTake.add(Either.forRight(new CreateFile(docURI, new CreateFileOptions(false, true))));

	// 2. update the created file with the given content
	VersionedTextDocumentIdentifier identifier = new VersionedTextDocumentIdentifier(docURI, 0);
	TextEdit te = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), content);
	actionsToTake.add(Either.forLeft(new TextDocumentEdit(identifier, Collections.singletonList(te))));

	WorkspaceEdit createAndAddContentEdit = new WorkspaceEdit(actionsToTake);

	CodeAction codeAction = new CodeAction(title);
	codeAction.setEdit(createAndAddContentEdit);
	codeAction.setDiagnostics(Collections.singletonList(diagnostic));
	codeAction.setKind(CodeActionKind.QuickFix);

	return codeAction;
}
 
Example #17
Source File: WorkspaceDiagnosticsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@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());
}
 
Example #18
Source File: XSDValidationExtensionsTest.java    From lemminx with Eclipse Public License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
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 #20
Source File: LSPUtils.java    From vscode-as3mxml with Apache License 2.0 5 votes vote down vote up
public static Diagnostic createDiagnosticWithoutRange()
{
    Diagnostic diagnostic = new Diagnostic();
    Range range = new Range();
    range.setStart(new Position());
    range.setEnd(new Position());
    diagnostic.setRange(range);
    return diagnostic;
}
 
Example #21
Source File: EntityNotDeclaredCodeAction.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void doCodeAction(Diagnostic diagnostic, Range range, DOMDocument document, List<CodeAction> codeActions,
		SharedSettings sharedSettings, IComponentProvider componentProvider) {

	try {
		String entityName = getEntityName(diagnostic, range, document);

		if (entityName == null) {
			return;
		}
		
		DOMDocumentType docType = document.getDoctype();
		if (docType != null) {

			// Case 1: <!DOCTYPE exists
			// Add <!ENTITY nbsp "entity-value"> in the subset.
			// If the subset does not exist, add subset too
			
			// ie:
			// <!DOCTYPE article [
			// <!ELEMENT article (#PCDATA)>
			// <!ENTITY nbsp "entity-value">
			// ]>
			addEntityCodeAction(entityName, diagnostic, document, sharedSettings, codeActions);
		} else {
			// Case 2: <!DOCTYPE does not exist
			// Generate:
			// <!DOCTYPE article [
			//     <!ENTITY nbsp "entity-value">
			// ]>
			addDoctypeAndEntityCodeAction(entityName, diagnostic, document, sharedSettings, codeActions);
		}
	} catch (BadLocationException e) {
		LOGGER.log(Level.SEVERE, "In EntityNotDeclaredCodeAction the DOMDocument offset(s) is at a BadLocation", e);
	}
}
 
Example #22
Source File: DiagnosticHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMultipleLineRange() throws Exception {
	IJavaProject javaProject = newEmptyProject();
	Hashtable<String, String> options = JavaCore.getOptions();
	options.put(JavaCore.COMPILER_PB_DEAD_CODE, JavaCore.WARNING);
	javaProject.setOptions(options);
	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 E {\n");
	buf.append("    public boolean foo(boolean b1) {\n");
	buf.append("        if (false) {\n");
	buf.append("            return true;\n");
	buf.append("        }\n");
	buf.append("        return false;\n");
	buf.append("    }\n");
	buf.append("}\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(1, diagnostics.size());
	Range range = diagnostics.get(0).getRange();
	assertNotEquals(range.getStart().getLine(), range.getEnd().getLine());
}
 
Example #23
Source File: InvalidEnumQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testReturnCodeActionForQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();

	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
	CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), Collections.singletonList(CodeActionKind.QuickFix));
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	checkRetrievedCodeAction(textDocumentIdentifier, diagnostic, codeActions);
}
 
Example #24
Source File: UnknownPropertyQuickfixTest.java    From camel-language-server with Apache License 2.0 5 votes vote down vote up
@Test
void testReturnNoCodeActionForOtherThanQuickfix() throws FileNotFoundException, InterruptedException, ExecutionException {
	TextDocumentIdentifier textDocumentIdentifier = initAnLaunchDiagnostic();
	
	 List<String> codeActionKinds = Stream.of(CodeActionKind.Refactor, CodeActionKind.RefactorExtract, CodeActionKind.RefactorInline, CodeActionKind.RefactorRewrite, CodeActionKind.Source, CodeActionKind.SourceOrganizeImports)
		      .collect(Collectors.toList());
	
	Diagnostic diagnostic = lastPublishedDiagnostics.getDiagnostics().get(0);
	CodeActionContext context = new CodeActionContext(lastPublishedDiagnostics.getDiagnostics(), codeActionKinds);
	CompletableFuture<List<Either<Command,CodeAction>>> codeActions = camelLanguageServer.getTextDocumentService().codeAction(new CodeActionParams(textDocumentIdentifier, diagnostic.getRange(), context));
	
	assertThat(codeActions.get()).isEmpty();
}
 
Example #25
Source File: XSDValidationExtensionsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@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=\"\"")));
}
 
Example #26
Source File: AbstractLSPErrorReporter.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public boolean addDiagnostic(Range adjustedRange, String message, DiagnosticSeverity severity, String key) {
	Diagnostic d = new Diagnostic(adjustedRange, message, severity, source, key);
	if (diagnostics.contains(d)) {
		return false;
	}
	// Fill diagnostic
	diagnostics.add(d);
	return true;
}
 
Example #27
Source File: XMLSyntaxDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testMarkupEntityMismatchWithTextAndNewLine() throws Exception {
	String xml = "<ABC>def\r\n";
	Diagnostic d = d(0, 1, 0, 4, XMLSyntaxErrorCode.MarkupEntityMismatch);
	testDiagnosticsFor(xml, d);
	testCodeActionsFor(xml, d, ca(d, te(0, 8, 0, 8, "</ABC>")));
}
 
Example #28
Source File: XMLCodeActions.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public List<CodeAction> doCodeActions(CodeActionContext context, Range range, DOMDocument document,
		SharedSettings sharedSettings) {
	List<CodeAction> codeActions = new ArrayList<>();
	if (context.getDiagnostics() != null) {
		for (Diagnostic diagnostic : context.getDiagnostics()) {
			for (ICodeActionParticipant codeActionParticipant : extensionsRegistry.getCodeActionsParticipants()) {
				codeActionParticipant.doCodeAction(diagnostic, range, document, codeActions,
						sharedSettings, extensionsRegistry);
			}
		}
	}
	return codeActions;
}
 
Example #29
Source File: CodeActionService.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<Either<Command, CodeAction>> getCodeActions(ICodeActionService2.Options options) {
	List<Either<Command, CodeAction>> actions = new ArrayList<>();
	for (Diagnostic d : options.getCodeActionParams().getContext().getDiagnostics()) {
		Object code = d.getCode().get();
		if (TestLanguageValidator.INVALID_NAME.equals(code)) {
			actions.add(Either.forLeft(fixInvalidName(d, options)));
		} else if (TestLanguageValidator.UNSORTED_MEMBERS.equals(code)) {
			actions.add(Either.forRight(fixUnsortedMembers(d, options)));
		}
	}
	return actions;
}
 
Example #30
Source File: XMLSyntaxDiagnosticsTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testETagRequiredWithReplace() throws Exception {
	String xml = "<a>\r\n" + //
			"	<b>\r\n" + //
			"		</c>";
	Diagnostic d = d(2, 4, 2, 5, XMLSyntaxErrorCode.ETagRequired);
	testDiagnosticsFor(xml, d);
	testCodeActionsFor(xml, d, //
			ca(d, te(2, 4, 2, 5, "b")));
}