Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
SparqlResultSetJsonCodec.cs
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Threading.Tasks;
9
11{
17 {
22 {
23 }
24
28 public string[] ContentTypes => SparqlResultSetContentTypes;
29
30 private static readonly string[] SparqlResultSetContentTypes = new string[]
31 {
32 "application/sparql-results+json"
33 };
34
38 public string[] FileExtensions => SparqlResultSetFileExtensions;
39
40 private static readonly string[] SparqlResultSetFileExtensions = new string[]
41 {
42 "srj"
43 };
44
51 public bool Decodes(string ContentType, out Grade Grade)
52 {
53 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
54 {
55 Grade = Grade.Excellent;
56 return true;
57 }
58 else
59 {
60 Grade = Grade.NotAtAll;
61 return false;
62 }
63 }
64
74 public Task<object> DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair<string, string>[] Fields, Uri BaseUri)
75 {
76 string s = CommonTypes.GetString(Data, Encoding ?? Encoding.UTF8);
77 object Obj = JSON.Parse(s);
78
79 if (!(Obj is Dictionary<string, object> Doc))
80 throw new Exception("Unable to decode JSON.");
81
82 SparqlResultSet Parsed = new SparqlResultSet(Doc, BaseUri);
83 return Task.FromResult<object>(Parsed);
84 }
85
93 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
94 {
95 if (Object is SparqlResultSet &&
96 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
97 {
98 Grade = Grade.Excellent;
99 return true;
100 }
101 else if (Object is ObjectMatrix M && M.HasColumnNames &&
102 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
103 {
104 Grade = Grade.Ok;
105 return true;
106 }
107 else if (Object is bool &&
108 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
109 {
110 Grade = Grade.Barely;
111 return true;
112 }
113 else
114 {
115 Grade = Grade.NotAtAll;
116 return false;
117 }
118 }
119
127 public Task<KeyValuePair<byte[], string>> EncodeAsync(object Object, Encoding Encoding, params string[] AcceptedContentTypes)
128 {
129 if (Encoding is null)
130 Encoding = Encoding.UTF8;
131
132 object ResultObj;
133 bool Pretty = false;
134
135 if (Object is SparqlResultSet Result)
136 {
137 ResultObj = this.EncodeAsync(Result);
138 Pretty = Result.Pretty;
139 }
140 else if (Object is ObjectMatrix M)
141 ResultObj = this.EncodeAsync(M);
142 else if (Object is bool b)
143 ResultObj = this.EncodeAsync(b);
144 else
145 throw new ArgumentException("Unable to encode object.", nameof(Object));
146
147 string Text = JSON.Encode(ResultObj, Pretty);
148 byte[] Bin = Encoding.GetBytes(Text);
149 string ContentType = SparqlResultSetContentTypes[0] + "; charset=" + Encoding.WebName;
150
151 return Task.FromResult(new KeyValuePair<byte[], string>(Bin, ContentType));
152 }
153
154 private Dictionary<string, object> EncodeAsync(SparqlResultSet Result)
155 {
156 Dictionary<string, object> Head = new Dictionary<string, object>();
157 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
158 {
159 { "head", Head }
160 };
161
162 if (!(Result.Variables is null))
163 Head["vars"] = Result.Variables;
164
165 if (!(Result.Links is null))
166 {
167 List<string> Links = new List<string>();
168
169 foreach (Uri Link in Result.Links)
170 Links.Add(Link.ToString());
171
172 Head["link"] = Links.ToArray();
173 }
174
175 if (Result.BooleanResult.HasValue)
176 ResultObj["boolean"] = Result.BooleanResult.Value;
177 else
178 {
179 Dictionary<string, object> Results = new Dictionary<string, object>();
180 ResultObj["results"] = Results;
181
182 if (!(Result.Records is null))
183 {
184 List<Dictionary<string, object>> Bindings = new List<Dictionary<string, object>>();
185
186 foreach (ISparqlResultRecord Record in Result.Records)
187 {
188 Dictionary<string, object> Binding = new Dictionary<string, object>();
189
190 foreach (ISparqlResultItem Item in Record)
191 Binding[Item.Name] = OutputValue(Item.Value);
192
193 Bindings.Add(Binding);
194 }
195
196 Results["bindings"] = Bindings.ToArray();
197 }
198 }
199
200 return ResultObj;
201 }
202
203 private Dictionary<string, object> EncodeAsync(ObjectMatrix Result)
204 {
205 Dictionary<string, object> Head = new Dictionary<string, object>();
206 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
207 {
208 { "head", Head }
209 };
210
211 if (!(Result.ColumnNames is null))
212 Head["vars"] = Result.ColumnNames;
213
214 Dictionary<string, object> Results = new Dictionary<string, object>();
215 ResultObj["results"] = Results;
216
217 List<Dictionary<string, object>> Bindings = new List<Dictionary<string, object>>();
218
219 int x, y;
220 int NrRows = Result.Rows;
221 int NrColumns = Result.Columns;
222
223 for (y = 0; y < NrRows; y++)
224 {
225 Dictionary<string, object> Binding = new Dictionary<string, object>();
226
227 for (x = 0; x < NrColumns; x++)
228 Binding[Result.ColumnNames[x]] = OutputValue(Result.GetElement(x, y)?.AssociatedObjectValue);
229
230 Bindings.Add(Binding);
231 }
232
233 Results["bindings"] = Bindings.ToArray();
234
235 return ResultObj;
236 }
237
238 private Dictionary<string, object> EncodeAsync(bool Result)
239 {
240 Dictionary<string, object> Head = new Dictionary<string, object>();
241 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
242 {
243 { "head", Head },
244 { "boolean", Result }
245 };
246
247 return ResultObj;
248 }
249
250 private static Dictionary<string, object> OutputValue(object Value)
251 {
252 Dictionary<string, object> Result;
253
254 if (Value is ISemanticElement E)
255 {
256 if (E is ISemanticLiteral Literal)
257 {
258 Result = new Dictionary<string, object>()
259 {
260 { "type", "literal" },
261 { "value", Literal.Value }
262 };
263
264 if (!string.IsNullOrEmpty(Literal.StringType))
265 Result["datatype"] = Literal.StringType;
266
267 if (Literal is StringLiteral StringLiteral &&
268 !string.IsNullOrEmpty(StringLiteral.Language))
269 {
270 Result["xml:lang"] = StringLiteral.Language;
271 }
272 else if (Literal is CustomLiteral CustomLiteral &&
273 !string.IsNullOrEmpty(CustomLiteral.Language))
274 {
275 Result["xml:lang"] = CustomLiteral.Language;
276 }
277 }
278 else if (E is UriNode N)
279 {
280 Result = new Dictionary<string, object>()
281 {
282 { "type", "uri" },
283 { "value", N.Uri.ToString() }
284 };
285 }
286 else if (E is BlankNode N2)
287 {
288 Result = new Dictionary<string, object>()
289 {
290 { "type", "bnode" },
291 { "value", N2.NodeId }
292 };
293 }
294 else if (E is ISemanticTriple T)
295 {
296 Dictionary<string, object> Triple = new Dictionary<string, object>()
297 {
298 { "subject", OutputValue(T.Subject) },
299 { "predicate", OutputValue(T.Predicate) },
300 { "object", OutputValue(T.Object) }
301 };
302 Result = new Dictionary<string, object>()
303 {
304 { "type", "triple" },
305 { "value", Triple }
306 };
307 }
308 else
309 {
310 Result = new Dictionary<string, object>()
311 {
312 { "type", "literal" },
313 { "value", Value?.ToString() }
314 };
315 }
316 }
317 else
318 {
319 Result = new Dictionary<string, object>()
320 {
321 { "type", "literal" },
322 { "value", Value?.ToString() }
323 };
324 }
325
326 return Result;
327 }
328
335 public bool TryGetContentType(string FileExtension, out string ContentType)
336 {
337 if (string.Compare(FileExtension, SparqlResultSetFileExtensions[0], true) == 0)
338 {
339 ContentType = SparqlResultSetContentTypes[0];
340 return true;
341 }
342 else
343 {
344 ContentType = null;
345 return false;
346 }
347 }
348
355 public bool TryGetFileExtension(string ContentType, out string FileExtension)
356 {
357 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
358 {
359 FileExtension = SparqlResultSetFileExtensions[0];
360 return true;
361 }
362 else
363 {
364 FileExtension = null;
365 return false;
366 }
367 }
368 }
369}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
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.
Helps with common JSON-related tasks.
Definition: JSON.cs:14
static object Parse(string Json)
Parses a JSON string.
Definition: JSON.cs:43
static string Encode(string s)
Encodes a string for inclusion in JSON.
Definition: JSON.cs:507
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.
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 JSON. https://www....
Task< object > DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair< string, string >[] Fields, Uri BaseUri)
Decodes an object
string[] ContentTypes
Supported Internet Content Types.
Task< KeyValuePair< byte[], string > > EncodeAsync(object Object, Encoding Encoding, params string[] AcceptedContentTypes)
Encodes an object
SparqlResultSetJsonCodec()
Encoder and Decoder of semantic information from SPARQL queries using JSON.
bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
If the encoder encodes a specific object.
bool Decodes(string ContentType, out Grade Grade)
If the decoder decodes content of a given Internet Content Type.
bool TryGetContentType(string FileExtension, out string ContentType)
Tries to get the content type of content of a given file extension.
bool TryGetFileExtension(string ContentType, out string FileExtension)
Tries to get the file extension of content of a given content type.
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.
Grade
Grade enumeration
Definition: Grade.cs:7