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;
3using System.Text;
4using System.Threading.Tasks;
5using System.Xml;
11
13{
19 {
24 {
25 }
26
30 public string[] ContentTypes => SparqlResultSetContentTypes;
31
32 private static readonly string[] SparqlResultSetContentTypes = new string[]
33 {
34 "application/sparql-results+xml"
35 };
36
40 public string[] FileExtensions => SparqlResultSetFileExtensions;
41
42 private static readonly string[] SparqlResultSetFileExtensions = new string[]
43 {
44 "srx"
45 };
46
53 public bool Decodes(string ContentType, out Grade Grade)
54 {
55 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
56 {
57 Grade = Grade.Excellent;
58 return true;
59 }
60 else
61 {
62 Grade = Grade.NotAtAll;
63 return false;
64 }
65 }
66
77 public Task<ContentResponse> DecodeAsync(string ContentType, byte[] Data, Encoding Encoding,
78 KeyValuePair<string, string>[] Fields, Uri BaseUri, ICodecProgress Progress)
79 {
80 string s = Strings.GetString(Data, Encoding ?? Encoding.UTF8);
81 SparqlResultSet Parsed = new SparqlResultSet(s, BaseUri);
82 return Task.FromResult(new ContentResponse(ContentType, Parsed, Data));
83 }
84
92 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
93 {
94 if (Object is SparqlResultSet &&
95 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
96 {
97 Grade = Grade.Excellent;
98 return true;
99 }
100 else if (Object is ObjectMatrix M && M.HasColumnNames &&
101 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
102 {
103 Grade = Grade.Ok;
104 return true;
105 }
106 else if (Object is bool &&
107 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
108 {
109 Grade = Grade.Barely;
110 return true;
111 }
112 else
113 {
114 Grade = Grade.NotAtAll;
115 return false;
116 }
117 }
118
127 public Task<ContentResponse> EncodeAsync(object Object, Encoding Encoding, ICodecProgress Progress, params string[] AcceptedContentTypes)
128 {
129 if (Encoding is null)
130 Encoding = Encoding.UTF8;
131
132 StringBuilder sb = new StringBuilder();
133 sb.Append("<?xml version=\"1.0\" encoding=\"");
134 sb.Append(Encoding.WebName);
135 sb.AppendLine("\"?>");
136
137 XmlWriterSettings Settings = new XmlWriterSettings()
138 {
139 ConformanceLevel = ConformanceLevel.Document,
140 Encoding = Encoding,
141 Indent = false,
142 NamespaceHandling = NamespaceHandling.OmitDuplicates,
143 NewLineHandling = NewLineHandling.None,
144 NewLineOnAttributes = false,
145 OmitXmlDeclaration = true,
146 WriteEndDocumentOnClose = true
147 };
148
149 if (Object is SparqlResultSet Result && Result.Pretty)
150 {
151 Settings.Indent = true;
152 Settings.IndentChars = "\t";
153 }
154
155 using (XmlWriter w = XmlWriter.Create(sb, Settings))
156 {
157 if (Object is SparqlResultSet Result2)
158 Encode(Result2, w);
159 else if (Object is ObjectMatrix M)
160 Encode(M, w);
161 else if (Object is bool b)
162 Encode(b, w);
163 else
164 return Task.FromResult(new ContentResponse(new ArgumentException("Unable to encode object.", nameof(Object))));
165
166 w.Flush();
167
168 string Text = sb.ToString();
169
170 byte[] Bin = Encoding.GetBytes(Text);
171 string ContentType = SparqlResultSetContentTypes[0] + "; charset=" + Encoding.WebName;
172
173 return Task.FromResult(new ContentResponse(ContentType, Object, Bin));
174 }
175 }
176
177 private static void Encode(SparqlResultSet Result, XmlWriter w)
178 {
180
181 w.WriteStartElement("head");
182
183 if (!(Result.Variables is null))
184 {
185 foreach (string Name in Result.Variables)
186 {
187 w.WriteStartElement("variable");
188 w.WriteAttributeString("name", Name);
189 w.WriteEndElement();
190 }
191 }
192
193 if (!(Result.Links is null))
194 {
195 foreach (Uri Link in Result.Links)
196 {
197 w.WriteStartElement("link");
198 w.WriteAttributeString("href", Link.ToString());
199 w.WriteEndElement();
200 }
201 }
202
203 w.WriteEndElement();
204
205 if (Result.BooleanResult.HasValue)
206 w.WriteElementString("boolean", CommonTypes.Encode(Result.BooleanResult.Value));
207 else
208 {
209 w.WriteStartElement("results");
210
211 if (!(Result.Records is null))
212 {
213 foreach (ISparqlResultRecord Record in Result.Records)
214 {
215 w.WriteStartElement("result");
216
217 foreach (ISparqlResultItem Item in Record)
218 {
219 w.WriteStartElement("binding");
220 w.WriteAttributeString("name", Item.Name);
221
222 OutputValue(w, Item.Value);
223
224 w.WriteEndElement();
225 }
226
227 w.WriteEndElement();
228 }
229 }
230
231 w.WriteEndElement();
232 }
233
234 w.WriteEndElement();
235 }
236
237 private static void Encode(ObjectMatrix Result, XmlWriter w)
238 {
240
241 w.WriteStartElement("head");
242
243 if (!(Result.ColumnNames is null))
244 {
245 foreach (string Name in Result.ColumnNames)
246 {
247 w.WriteStartElement("variable");
248 w.WriteAttributeString("name", Name);
249 w.WriteEndAttribute();
250 }
251 }
252
253 w.WriteEndElement();
254 w.WriteStartElement("results");
255
256 int x, y;
257 int NrRows = Result.Rows;
258 int NrColumns = Result.Columns;
259
260 for (y = 0; y < NrRows; y++)
261 {
262 w.WriteStartElement("result");
263
264 for (x = 0; x < NrColumns; x++)
265 {
266 w.WriteStartElement("binding");
267 w.WriteAttributeString("name", Result.ColumnNames[x]);
268
269 OutputValue(w, Result.GetElement(x, y)?.AssociatedObjectValue);
270
271 w.WriteEndElement();
272 }
273
274 w.WriteEndElement();
275 }
276
277 w.WriteEndElement();
278 w.WriteEndElement();
279 }
280
281 private static void Encode(bool Result, XmlWriter w)
282 {
284 w.WriteElementString("head", string.Empty);
285 w.WriteElementString("boolean", CommonTypes.Encode(Result));
286 w.WriteEndElement();
287 }
288
289 private static void OutputValue(XmlWriter w, object Value)
290 {
291 if (Value is ISemanticElement E)
292 {
293 if (E is ISemanticLiteral Literal)
294 {
295 w.WriteStartElement("literal");
296
297 if (!string.IsNullOrEmpty(Literal.StringType))
298 w.WriteAttributeString("datatype", Literal.StringType);
299
300 if (Literal is StringLiteral StringLiteral &&
301 !string.IsNullOrEmpty(StringLiteral.Language))
302 {
303 w.WriteAttributeString("xml", "lang", null, StringLiteral.Language);
304 }
305 else if (Literal is CustomLiteral CustomLiteral &&
306 !string.IsNullOrEmpty(CustomLiteral.Language))
307 {
308 w.WriteAttributeString("xml", "lang", null, CustomLiteral.Language);
309 }
310
311 w.WriteValue(Literal.Value);
312 w.WriteEndElement();
313 }
314 else if (E is UriNode N)
315 w.WriteElementString("uri", N.Uri.ToString());
316 else if (E is BlankNode N2)
317 w.WriteElementString("bnode", N2.NodeId);
318 else if (E is ISemanticTriple T)
319 {
320 w.WriteStartElement("triple");
321
322 w.WriteStartElement("subject");
323 OutputValue(w, T.Subject);
324 w.WriteEndElement();
325
326 w.WriteStartElement("predicate");
327 OutputValue(w, T.Predicate);
328 w.WriteEndElement();
329
330 w.WriteStartElement("object");
331 OutputValue(w, T.Object);
332 w.WriteEndElement();
333
334 w.WriteEndElement();
335 }
336 else
337 w.WriteElementString("literal", Value?.ToString() ?? string.Empty);
338 }
339 else
340 w.WriteElementString("literal", Value?.ToString() ?? string.Empty);
341 }
342
349 public bool TryGetContentType(string FileExtension, out string ContentType)
350 {
351 if (string.Compare(FileExtension, SparqlResultSetFileExtensions[0], true) == 0)
352 {
353 ContentType = SparqlResultSetContentTypes[0];
354 return true;
355 }
356 else
357 {
358 ContentType = null;
359 return false;
360 }
361 }
362
369 public bool TryGetFileExtension(string ContentType, out string FileExtension)
370 {
371 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
372 {
373 FileExtension = SparqlResultSetFileExtensions[0];
374 return true;
375 }
376 else
377 {
378 FileExtension = null;
379 return false;
380 }
381 }
382 }
383}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:15
static string Encode(bool x)
Encodes a Boolean for use in XML and other formats.
Definition: CommonTypes.cs:596
Contains information about a response to a content request.
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.
Task< ContentResponse > DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair< string, string >[] Fields, Uri BaseUri, ICodecProgress Progress)
Decodes an object
Task< ContentResponse > EncodeAsync(object Object, Encoding Encoding, ICodecProgress Progress, params string[] AcceptedContentTypes)
Encodes an object
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.
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.
Static class managing binary representations of strings.
Definition: Strings.cs:10
static string GetString(byte[] Data, int Offset, int Count, Encoding DefaultEncoding)
Gets a string from its binary representation, taking any Byte Order Mark (BOM) into account.
Definition: Strings.cs:148
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.
Interface for reporting progress about an encoding or decoding.
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