Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
SparqlResultSetXmlCodec.cs
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Threading.Tasks;
5using System.Xml;
10
12{
18 {
23 {
24 }
25
29 public string[] ContentTypes => SparqlResultSetContentTypes;
30
31 private static readonly string[] SparqlResultSetContentTypes = new string[]
32 {
33 "application/sparql-results+xml"
34 };
35
39 public string[] FileExtensions => SparqlResultSetFileExtensions;
40
41 private static readonly string[] SparqlResultSetFileExtensions = new string[]
42 {
43 "srx"
44 };
45
52 public bool Decodes(string ContentType, out Grade Grade)
53 {
54 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
55 {
56 Grade = Grade.Excellent;
57 return true;
58 }
59 else
60 {
61 Grade = Grade.NotAtAll;
62 return false;
63 }
64 }
65
75 public Task<object> DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair<string, string>[] Fields, Uri BaseUri)
76 {
77 string s = CommonTypes.GetString(Data, Encoding ?? Encoding.UTF8);
78 SparqlResultSet Parsed = new SparqlResultSet(s, BaseUri);
79 return Task.FromResult<object>(Parsed);
80 }
81
89 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
90 {
91 if (Object is SparqlResultSet &&
92 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
93 {
94 Grade = Grade.Excellent;
95 return true;
96 }
97 else if (Object is ObjectMatrix M && M.HasColumnNames &&
98 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
99 {
100 Grade = Grade.Ok;
101 return true;
102 }
103 else if (Object is bool &&
104 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
105 {
106 Grade = Grade.Barely;
107 return true;
108 }
109 else
110 {
111 Grade = Grade.NotAtAll;
112 return false;
113 }
114 }
115
123 public Task<KeyValuePair<byte[], string>> EncodeAsync(object Object, Encoding Encoding, params string[] AcceptedContentTypes)
124 {
125 if (Encoding is null)
126 Encoding = Encoding.UTF8;
127
128 StringBuilder sb = new StringBuilder();
129 sb.Append("<?xml version=\"1.0\" encoding=\"");
130 sb.Append(Encoding.WebName);
131 sb.AppendLine("\"?>");
132
133 XmlWriterSettings Settings = new XmlWriterSettings()
134 {
135 ConformanceLevel = ConformanceLevel.Document,
136 Encoding = Encoding,
137 Indent = false,
138 NamespaceHandling = NamespaceHandling.OmitDuplicates,
139 NewLineHandling = NewLineHandling.None,
140 NewLineOnAttributes = false,
141 OmitXmlDeclaration = true,
142 WriteEndDocumentOnClose = true
143 };
144
145 if (Object is SparqlResultSet Result && Result.Pretty)
146 {
147 Settings.Indent = true;
148 Settings.IndentChars = "\t";
149 }
150
151 using (XmlWriter w = XmlWriter.Create(sb, Settings))
152 {
153 if (Object is SparqlResultSet Result2)
154 this.EncodeAsync(Result2, w);
155 else if (Object is ObjectMatrix M)
156 this.EncodeAsync(M, w);
157 else if (Object is bool b)
158 this.EncodeAsync(b, w);
159 else
160 throw new ArgumentException("Unable to encode object.", nameof(Object));
161
162 w.Flush();
163
164 string Text = sb.ToString();
165
166 byte[] Bin = Encoding.GetBytes(Text);
167 string ContentType = SparqlResultSetContentTypes[0] + "; charset=" + Encoding.WebName;
168
169 return Task.FromResult(new KeyValuePair<byte[], string>(Bin, ContentType));
170 }
171 }
172
173 private void EncodeAsync(SparqlResultSet Result, XmlWriter w)
174 {
176
177 w.WriteStartElement("head");
178
179 if (!(Result.Variables is null))
180 {
181 foreach (string Name in Result.Variables)
182 {
183 w.WriteStartElement("variable");
184 w.WriteAttributeString("name", Name);
185 w.WriteEndElement();
186 }
187 }
188
189 if (!(Result.Links is null))
190 {
191 foreach (Uri Link in Result.Links)
192 {
193 w.WriteStartElement("link");
194 w.WriteAttributeString("href", Link.ToString());
195 w.WriteEndElement();
196 }
197 }
198
199 w.WriteEndElement();
200
201 if (Result.BooleanResult.HasValue)
202 w.WriteElementString("boolean", CommonTypes.Encode(Result.BooleanResult.Value));
203 else
204 {
205 w.WriteStartElement("results");
206
207 if (!(Result.Records is null))
208 {
209 foreach (ISparqlResultRecord Record in Result.Records)
210 {
211 w.WriteStartElement("result");
212
213 foreach (ISparqlResultItem Item in Record)
214 {
215 w.WriteStartElement("binding");
216 w.WriteAttributeString("name", Item.Name);
217
218 OutputValue(w, Item.Value);
219
220 w.WriteEndElement();
221 }
222
223 w.WriteEndElement();
224 }
225 }
226
227 w.WriteEndElement();
228 }
229
230 w.WriteEndElement();
231 }
232
233 private void EncodeAsync(ObjectMatrix Result, XmlWriter w)
234 {
236
237 w.WriteStartElement("head");
238
239 if (!(Result.ColumnNames is null))
240 {
241 foreach (string Name in Result.ColumnNames)
242 {
243 w.WriteStartElement("variable");
244 w.WriteAttributeString("name", Name);
245 w.WriteEndAttribute();
246 }
247 }
248
249 w.WriteEndElement();
250 w.WriteStartElement("results");
251
252 int x, y;
253 int NrRows = Result.Rows;
254 int NrColumns = Result.Columns;
255
256 for (y = 0; y < NrRows; y++)
257 {
258 w.WriteStartElement("result");
259
260 for (x = 0; x < NrColumns; x++)
261 {
262 w.WriteStartElement("binding");
263 w.WriteAttributeString("name", Result.ColumnNames[x]);
264
265 OutputValue(w, Result.GetElement(x, y)?.AssociatedObjectValue);
266
267 w.WriteEndElement();
268 }
269
270 w.WriteEndElement();
271 }
272
273 w.WriteEndElement();
274 w.WriteEndElement();
275 }
276
277 private void EncodeAsync(bool Result, XmlWriter w)
278 {
280 w.WriteElementString("head", string.Empty);
281 w.WriteElementString("boolean", CommonTypes.Encode(Result));
282 w.WriteEndElement();
283 }
284
285 private static void OutputValue(XmlWriter w, object Value)
286 {
287 if (Value is ISemanticElement E)
288 {
289 if (E is ISemanticLiteral Literal)
290 {
291 w.WriteStartElement("literal");
292
293 if (!string.IsNullOrEmpty(Literal.StringType))
294 w.WriteAttributeString("datatype", Literal.StringType);
295
296 if (Literal is StringLiteral StringLiteral &&
297 !string.IsNullOrEmpty(StringLiteral.Language))
298 {
299 w.WriteAttributeString("xml:lang", StringLiteral.Language);
300 }
301 else if (Literal is CustomLiteral CustomLiteral &&
302 !string.IsNullOrEmpty(CustomLiteral.Language))
303 {
304 w.WriteAttributeString("xml:lang", CustomLiteral.Language);
305 }
306
307 w.WriteValue(Literal.Value);
308 w.WriteEndElement();
309 }
310 else if (E is UriNode N)
311 w.WriteElementString("uri", N.Uri.ToString());
312 else if (E is BlankNode N2)
313 w.WriteElementString("bnode", N2.NodeId);
314 else if (E is ISemanticTriple T)
315 {
316 w.WriteStartElement("triple");
317
318 w.WriteStartElement("subject");
319 OutputValue(w, T.Subject);
320 w.WriteEndElement();
321
322 w.WriteStartElement("predicate");
323 OutputValue(w, T.Predicate);
324 w.WriteEndElement();
325
326 w.WriteStartElement("object");
327 OutputValue(w, T.Object);
328 w.WriteEndElement();
329
330 w.WriteEndElement();
331 }
332 else
333 w.WriteElementString("literal", Value?.ToString() ?? string.Empty);
334 }
335 else
336 w.WriteElementString("literal", Value?.ToString() ?? string.Empty);
337 }
338
345 public bool TryGetContentType(string FileExtension, out string ContentType)
346 {
347 if (string.Compare(FileExtension, SparqlResultSetFileExtensions[0], true) == 0)
348 {
349 ContentType = SparqlResultSetContentTypes[0];
350 return true;
351 }
352 else
353 {
354 ContentType = null;
355 return false;
356 }
357 }
358
365 public bool TryGetFileExtension(string ContentType, out string FileExtension)
366 {
367 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
368 {
369 FileExtension = SparqlResultSetFileExtensions[0];
370 return true;
371 }
372 else
373 {
374 FileExtension = null;
375 return false;
376 }
377 }
378 }
379}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
static string Encode(bool x)
Encodes a Boolean for use in XML and other formats.
Definition: CommonTypes.cs:594
static string GetString(byte[] Data, Encoding DefaultEncoding)
Gets a string from its binary representation, taking any Byte Order Mark (BOM) into account.
Static class managing encoding and decoding of internet content.
static bool IsAccepted(string ContentType, params string[] AcceptedContentTypes)
Checks if a given content type is acceptable.
Represents a blank node
Definition: BlankNode.cs:7
Contains the results of a SPARQL query. https://www.w3.org/TR/2023/WD-sparql12-results-xml-20230516/ ...
bool? BooleanResult
Any Boolean result returned.
const string Namespace
http://www.w3.org/2005/sparql-results#
bool Pretty
If pretty output is desired.
string[] Variables
Names of variables in result set.
ISparqlResultRecord[] Records
Records in result set.
Uri[] Links
Links to additional metadata about result set.
Encoder and Decoder of semantic information from SPARQL queries using XML. https://www....
string[] FileExtensions
Supported file extensions.
string[] ContentTypes
Supported Internet Content Types.
bool TryGetFileExtension(string ContentType, out string FileExtension)
Tries to get the file extension of content of a given content type.
bool Decodes(string ContentType, out Grade Grade)
If the decoder decodes content of a given Internet Content Type.
bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
If the encoder encodes a specific object.
Task< object > DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair< string, string >[] Fields, Uri BaseUri)
Decodes an object
SparqlResultSetXmlCodec()
Encoder and Decoder of semantic information from SPARQL queries using XML.
bool TryGetContentType(string FileExtension, out string ContentType)
Tries to get the content type of content of a given file extension.
Task< KeyValuePair< byte[], string > > EncodeAsync(object Object, Encoding Encoding, params string[] AcceptedContentTypes)
Encodes an object
IElement GetElement(int Index)
Gets an element of the vector.
bool HasColumnNames
If the matrix has column names defined.
string[] ColumnNames
Contains optional column names.
Basic interface for Internet Content decoders. A class implementing this interface and having a defau...
Basic interface for Internet Content encoders. A class implementing this interface and having a defau...
Interface for semantic nodes.
Interface for semantic literals.
Interface for semantic triples.
Interface for items in a record from the results of a SPARQL query.
string Name
Name of item in record.
ISemanticElement Value
Value of item in record.
Interface for result records of a SPARQL query.
delegate string ToString(IElement Element)
Delegate for callback methods that convert an element value to a string.
Grade
Grade enumeration
Definition: Grade.cs:7