下面列出了怎么用org.eclipse.lsp4j.jsonrpc.CancelChecker的API类实例代码及写法,或者点击链接到github查看源代码。
private void findSymbolInformations(DOMNode node, String container, List<SymbolInformation> symbols,
boolean ignoreNode, AtomicLong limit, CancelChecker cancelChecker) throws BadLocationException {
if (!isNodeSymbol(node)) {
return;
}
String name = "";
if (!ignoreNode) {
name = nodeToName(node);
DOMDocument xmlDocument = node.getOwnerDocument();
Range range = getSymbolRange(node);
Location location = new Location(xmlDocument.getDocumentURI(), range);
SymbolInformation symbol = new SymbolInformation(name, getSymbolKind(node), location, container);
checkLimit(limit);
symbols.add(symbol);
}
final String containerName = name;
node.getChildren().forEach(child -> {
try {
findSymbolInformations(child, containerName, symbols, false, limit, cancelChecker);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "XMLSymbolsProvider was given a BadLocation by the provided 'node' variable",
e);
}
});
}
public List<DocumentHighlight> findDocumentHighlights(DOMDocument xmlDocument, Position position,
CancelChecker cancelChecker) {
int offset = -1;
try {
offset = xmlDocument.offsetAt(position);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "In XMLHighlighting the client provided Position is at a BadLocation", e);
return Collections.emptyList();
}
DOMNode node = xmlDocument.findNodeAt(offset);
if (node == null) {
return Collections.emptyList();
}
List<DocumentHighlight> highlights = new ArrayList<>();
fillWithDefaultHighlights(node, position, offset, highlights, cancelChecker);
fillWithCustomHighlights(node, position, offset, highlights, cancelChecker);
return highlights;
}
public List<Diagnostic> doDiagnostics(DOMDocument xmlDocument, CancelChecker monitor, XMLValidationSettings validationSettings) {
List<Diagnostic> diagnostics = new ArrayList<Diagnostic>();
if(validationSettings == null || validationSettings.isEnabled()) {
try {
//Doesn't do anything ATM
doBasicDiagnostics(xmlDocument, diagnostics, monitor);
} catch (BadLocationException e) {
LOGGER.log(Level.WARNING, "BadLocationException thrown doing doBasicDiagnostics() in XMLDiagnostics.", e);;
}
doExtensionsDiagnostics(xmlDocument, diagnostics, monitor);
}
return diagnostics;
}
@Override
public void findReference(DOMDocument document, Position position, ReferenceContext context,
List<Location> locations, CancelChecker cancelChecker) {
if (!match(document)) {
return;
}
try {
int offset = document.offsetAt(position);
DOMNode node = document.findNodeAt(offset);
if (node != null) {
findReferences(node, position, offset, context, locations, cancelChecker);
}
} catch (BadLocationException e) {
}
}
public List<? extends LocationLink> findDefinition(DOMDocument document, Position position,
CancelChecker cancelChecker) {
IDefinitionRequest request = null;
try {
request = new DefinitionRequest(document, position, extensionsRegistry);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "Failed creating TypeDefinitionRequest", e);
return Collections.emptyList();
}
// Custom definition
List<LocationLink> locations = new ArrayList<>();
for (IDefinitionParticipant participant : extensionsRegistry.getDefinitionParticipants()) {
participant.findDefinition(request, locations, cancelChecker);
}
// Start end tag definition
findStartEndTagDefinition(request, locations);
return locations;
}
@Override
protected void doFindDefinition(IDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
DOMNode node = request.getNode();
int offset = request.getOffset();
// DTD definition is applicable only for <!ELEMENT and <!ATTLIST
if (!(node.isDTDElementDecl() || node.isDTDAttListDecl())) {
return;
}
// Get the parameter which defines the name which references an <!ELEMENT
// - <!ATTLIST elt -> we search the 'elt' in <!ELEMENT elt
// - <!ELEMENT elt (child1 -> we search the 'child1' in <!ELEMENT child1
DTDDeclParameter originName = ((DTDDeclNode) node).getReferencedElementNameAt(offset);
if (originName != null) {
DTDUtils.searchDTDTargetElementDecl(originName, true, targetElementName -> {
LocationLink location = XMLPositionUtility.createLocationLink((DOMRange) originName,
(DOMRange) targetElementName);
locations.add(location);
});
}
}
public static void doDiagnostics(DOMDocument document, XMLEntityResolver entityResolver,
List<Diagnostic> diagnostics, CancelChecker monitor) {
try {
XMLDTDLoader loader = new XMLDTDLoader();
loader.setProperty("http://apache.org/xml/properties/internal/error-reporter",
new LSPErrorReporterForXML(document, diagnostics));
if (entityResolver != null) {
loader.setEntityResolver(entityResolver);
}
String content = document.getText();
String uri = document.getDocumentURI();
InputStream inputStream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
XMLInputSource source = new XMLInputSource(null, uri, uri, inputStream, null);
loader.loadGrammar(source);
} catch (Exception e) {
}
}
@Override
protected void doFindDefinition(IDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
DOMNode node = request.getNode();
if (!node.isText()) {
return;
}
// Definition is done in a text node, check if it's a entity reference
DOMDocument document = request.getXMLDocument();
int offset = request.getOffset();
EntityReferenceRange entityRange = XMLPositionUtility.selectEntityReference(offset, document);
if (entityRange != null) {
String entityName = entityRange.getName();
Range range = entityRange.getRange();
searchInLocalEntities(entityName, range, document, locations, cancelChecker);
searchInExternalEntities(entityName, range, document, locations, request, cancelChecker);
}
}
/**
* Search the given entity name in the local entities.
*
* @param document the DOM document.
* @param entityName the entity name.
* @param entityRange the entity range.
* @param locations the location links
* @param cancelChecker the cancel checker.
*/
private static void searchInLocalEntities(String entityName, Range entityRange, DOMDocument document,
List<LocationLink> locations, CancelChecker cancelChecker) {
DOMDocumentType docType = document.getDoctype();
if (docType == null) {
return;
}
cancelChecker.checkCanceled();
// Loop for entities declared in the DOCTYPE of the document
NamedNodeMap entities = docType.getEntities();
for (int i = 0; i < entities.getLength(); i++) {
cancelChecker.checkCanceled();
DTDEntityDecl entity = (DTDEntityDecl) entities.item(i);
fillEntityLocation(entity, entityName, entityRange, locations);
}
}
@Override
protected void doFindDefinition(IDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
// - xs:element/@type -> xs:complexType/@name
// - xs:extension/@base -> xs:complexType/@name
// - xs:element/@ref -> xs:complexType/@name
DOMNode node = request.getNode();
if (!node.isAttribute()) {
return;
}
DOMAttr attr = (DOMAttr) node;
BindingType bindingType = XSDUtils.getBindingType(attr);
if (bindingType != BindingType.NONE) {
XSDUtils.searchXSTargetAttributes(attr, bindingType, true, true, (targetNamespacePrefix, targetAttr) -> {
LocationLink location = XMLPositionUtility.createLocationLink(attr.getNodeAttrValue(),
targetAttr.getNodeAttrValue());
locations.add(location);
});
}
}
@Override
protected void doFindTypeDefinition(ITypeDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
ContentModelManager contentModelManager = request.getComponent(ContentModelManager.class);
DOMNode node = request.getNode();
if (node == null) {
return;
}
DOMElement element = null;
if (node.isElement()) {
element = (DOMElement) node;
} else if (node.isAttribute()) {
element = ((DOMAttr) node).getOwnerElement();
}
if (element != null) {
Collection<CMDocument> cmDocuments = contentModelManager.findCMDocument(element);
for (CMDocument cmDocument : cmDocuments) {
LocationLink location = cmDocument.findTypeLocation(node);
if (location != null) {
locations.add(location);
}
}
}
}
private void validate(DOMDocument xmlDocument) throws CancellationException {
CancelChecker cancelChecker = xmlDocument.getCancelChecker();
cancelChecker.checkCanceled();
getXMLLanguageService().publishDiagnostics(xmlDocument,
params -> xmlLanguageServer.getLanguageClient().publishDiagnostics(params),
(doc) -> triggerValidationFor(doc), sharedSettings.getValidationSettings(), cancelChecker);
}
private static <R, M> CompletableFuture<R> computeModelAsync(CompletableFuture<M> loadModel,
BiFunction<CancelChecker, M, R> code) {
CompletableFuture<CancelChecker> start = new CompletableFuture<>();
CompletableFuture<R> result = start.thenCombineAsync(loadModel, code);
CancelChecker cancelIndicator = () -> {
if (result.isCancelled())
throw new CancellationException();
};
start.complete(cancelIndicator);
return result;
}
private void fillWithCustomHighlights(DOMNode node, Position position, int offset,
List<DocumentHighlight> highlights, CancelChecker cancelChecker) {
// Consume highlighting participant
for (IHighlightingParticipant highlightingParticipant : extensionsRegistry.getHighlightingParticipants()) {
highlightingParticipant.findDocumentHighlights(node, position, offset,highlights, cancelChecker);
}
}
public List<? extends CodeLens> getCodelens(DOMDocument xmlDocument, XMLCodeLensSettings settings, CancelChecker cancelChecker) {
ICodeLensRequest request = new CodeLensRequest(xmlDocument, settings);
List<CodeLens> lenses = new ArrayList<>();
for (ICodeLensParticipant participant : extensionsRegistry.getCodeLensParticipants()) {
participant.doCodeLens(request, lenses, cancelChecker);
}
return lenses;
}
/**
* Do basic validation to check the no XML valid.
*
* @param xmlDocument
* @param diagnostics
* @param monitor
* @throws BadLocationException
*/
private void doBasicDiagnostics(DOMDocument xmlDocument, List<Diagnostic> diagnostics, CancelChecker monitor)
throws BadLocationException {
/*
* Scanner scanner = XMLScanner.createScanner(document.getText()); TokenType
* token = scanner.scan(); while (token != TokenType.EOS) {
* monitor.checkCanceled(); // TODO check tokens... token = scanner.scan(); }
*/
}
public List<? extends Location> findReferences(DOMDocument document, Position position, ReferenceContext context,
CancelChecker cancelChecker) {
List<Location> locations = new ArrayList<>();
for (IReferenceParticipant participant : extensionsRegistry.getReferenceParticipants()) {
participant.findReference(document, position, context, locations, cancelChecker);
}
return locations;
}
@Override
public final void findDefinition(IDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
DOMDocument document = request.getXMLDocument();
if (!match(document)) {
return;
}
doFindDefinition(request, locations, cancelChecker);
}
@Override
public final void findTypeDefinition(ITypeDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
DOMDocument document = request.getXMLDocument();
if (!match(document)) {
return;
}
doFindTypeDefinition(request, locations, cancelChecker);
}
public AutoCloseTagResponse doAutoClose(DOMDocument xmlDocument, Position position, CancelChecker cancelChecker) {
try {
int offset = xmlDocument.offsetAt(position);
String text = xmlDocument.getText();
if (offset > 0) {
char c = text.charAt(offset - 1);
if (c == '>' || c == '/') {
return doTagComplete(xmlDocument, position, cancelChecker);
}
}
return null;
} catch (BadLocationException e) {
return null;
}
}
public List<? extends LocationLink> findTypeDefinition(DOMDocument document, Position position,
CancelChecker cancelChecker) {
ITypeDefinitionRequest request = null;
try {
request = new TypeDefinitionRequest(document, position, extensionsRegistry);
} catch (BadLocationException e) {
LOGGER.log(Level.SEVERE, "Failed creating TypeDefinitionRequest", e);
return Collections.emptyList();
}
List<LocationLink> locations = new ArrayList<>();
for (ITypeDefinitionParticipant participant : extensionsRegistry.getTypeDefinitionParticipants()) {
participant.findTypeDefinition(request, locations, cancelChecker);
}
return locations;
}
@Override
protected void findReferences(DOMNode node, Position position, int offset, ReferenceContext context,
List<Location> locations, CancelChecker cancelChecker) {
// DTD reference works only when references is done on an <!ELEMENT name
if (!node.isDTDElementDecl()) {
return;
}
DTDElementDecl elementDecl = (DTDElementDecl) node;
if (!elementDecl.isInNameParameter(offset)) {
return;
}
DTDUtils.searchDTDOriginElementDecls(elementDecl,
(origin, target) -> locations.add(XMLPositionUtility.createLocation(origin)), cancelChecker);
}
@Override
public void doDiagnostics(DOMDocument xmlDocument, List<Diagnostic> diagnostics, CancelChecker monitor) {
if (!xmlDocument.isDTD()) {
// Don't use the DTD validator, if it's a DTD
return;
}
// Get entity resolver (XML catalog resolver, XML schema from the file
// associations settings., ...)
XMLEntityResolver entityResolver = xmlDocument.getResolverExtensionManager();
// Process validation
DTDValidator.doDiagnostics(xmlDocument, entityResolver, diagnostics, monitor);
}
/**
* Search the given entity name in the external entities.
*
* @param document the DOM document.
* @param entityName the entity name.
* @param entityRange the entity range.
* @param locations the location links
* @param request the definition request.
* @param cancelChecker the cancel checker.
*/
private static void searchInExternalEntities(String entityName, Range entityRange, DOMDocument document,
List<LocationLink> locations, IDefinitionRequest request, CancelChecker cancelChecker) {
ContentModelManager contentModelManager = request.getComponent(ContentModelManager.class);
Collection<CMDocument> cmDocuments = contentModelManager.findCMDocument(document, null, false);
for (CMDocument cmDocument : cmDocuments) {
List<Entity> entities = cmDocument.getEntities();
for (Entity entity : entities) {
fillEntityLocation((DTDEntityDecl) entity, entityName, entityRange, locations);
}
}
}
/**
* Search origin attributes from the given target node..
*
* @param targetNode the referenced node
* @param collector the collector to collect reference between an origin and
* target attribute.
*/
public static void searchXSOriginAttributes(DOMNode targetNode, BiConsumer<DOMAttr, DOMAttr> collector,
CancelChecker cancelChecker) {
// get referenced attribute nodes from the given referenced node
List<DOMAttr> targetAttrs = getTargetAttrs(targetNode);
if (targetAttrs.isEmpty()) {
// None referenced nodes, stop the search of references
return;
}
// Here referencedNodes is filled with a list of attributes
// xs:complexType/@name,
// xs:simpleType/@name, xs:element/@name, xs:group/@name
DOMDocument document = targetNode.getOwnerDocument();
DOMElement documentElement = document.getDocumentElement();
// <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
// xmlns:tns="http://camel.apache.org/schema/spring"
// targetNamespace="http://camel.apache.org/schema/spring" version="1.0">
String targetNamespace = documentElement.getAttribute("targetNamespace"); // ->
// http://camel.apache.org/schema/spring
String targetNamespacePrefix = documentElement.getPrefix(targetNamespace); // -> tns
// Collect references for each references nodes
NodeList nodes = documentElement.getChildNodes();
searchXSOriginAttributes(nodes, targetAttrs, targetNamespacePrefix, collector, cancelChecker);
}
private static void searchXSOriginAttributes(NodeList nodes, List<DOMAttr> targetAttrs,
String targetNamespacePrefix, BiConsumer<DOMAttr, DOMAttr> collector, CancelChecker cancelChecker) {
for (int i = 0; i < nodes.getLength(); i++) {
if (cancelChecker != null) {
cancelChecker.checkCanceled();
}
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
DOMElement originElement = (DOMElement) node;
NamedNodeMap originAttributes = originElement.getAttributes();
if (originAttributes != null) {
for (int j = 0; j < originAttributes.getLength(); j++) {
DOMAttr originAttr = (DOMAttr) originAttributes.item(j);
BindingType originBnding = XSDUtils.getBindingType(originAttr);
if (originBnding != BindingType.NONE) {
String originName = getOriginName(originAttr.getValue(), targetNamespacePrefix);
for (DOMAttr targetAttr : targetAttrs) {
Element targetElement = targetAttr.getOwnerElement();
if (isBounded(originAttr.getOwnerElement(), originBnding, targetElement)) {
// node is a xs:complexType, xs:simpleType element, xsl:element, xs:group which
// matches the binding type of the originAttr
if (targetAttr != null && (Objects.equal(originName, targetAttr.getValue()))) {
collector.accept(originAttr, targetAttr);
}
}
}
}
}
}
}
if (node.hasChildNodes()) {
searchXSOriginAttributes(node.getChildNodes(), targetAttrs, targetNamespacePrefix, collector,
cancelChecker);
}
}
}
@Override
protected void findReferences(DOMNode node, Position position, int offset, ReferenceContext context,
List<Location> locations, CancelChecker cancelChecker) {
DOMAttr attr = node.findAttrAt(offset);
if (attr != null) {
node = attr;
}
XSDUtils.searchXSOriginAttributes(node,
(origin, target) -> locations.add(XMLPositionUtility.createLocation(origin.getNodeAttrValue())),
cancelChecker);
}
@Override
public void doDiagnostics(DOMDocument xmlDocument, List<Diagnostic> diagnostics, CancelChecker monitor) {
if (!DOMUtils.isXSD(xmlDocument)) {
// Don't use the XSD validator, if the XML document is not a XML Schema.
return;
}
// Get entity resolver (XML catalog resolver, XML schema from the file
// associations settings., ...)
XMLEntityResolver entityResolver = xmlDocument.getResolverExtensionManager();
// Process validation
XSDValidator.doDiagnostics(xmlDocument, entityResolver, diagnostics, monitor);
}
@Override
protected void doFindDefinition(IDefinitionRequest request, List<LocationLink> locations,
CancelChecker cancelChecker) {
DOMNode origin = request.getNode();
XMLReferencesManager.getInstance().collect(origin, target -> {
LocationLink location = XMLPositionUtility.createLocationLink(origin, target);
locations.add(location);
});
}
@Override
public void doDiagnostics(DOMDocument xmlDocument, List<Diagnostic> diagnostics, CancelChecker monitor) {
if (xmlDocument.isDTD() || DOMUtils.isXSD(xmlDocument)) {
// Don't validate DTD / XML Schema with XML validator
return;
}
// Get entity resolver (XML catalog resolver, XML schema from the file
// associations settings., ...)
XMLEntityResolver entityResolver = xmlDocument.getResolverExtensionManager();
// Process validation
XMLValidator.doDiagnostics(xmlDocument, entityResolver, diagnostics,
contentModelPlugin.getContentModelSettings(),
contentModelPlugin.getContentModelManager().getGrammarPool(), monitor);
}