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;
3using System.Text;
4using System.Threading.Tasks;
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+json"
35 };
36
40 public string[] FileExtensions => SparqlResultSetFileExtensions;
41
42 private static readonly string[] SparqlResultSetFileExtensions = new string[]
43 {
44 "srj"
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 object Obj = JSON.Parse(s);
82
83 if (!(Obj is Dictionary<string, object> Doc))
84 return Task.FromResult(new ContentResponse(new Exception("Unable to decode JSON.")));
85
86 SparqlResultSet Parsed = new SparqlResultSet(Doc, BaseUri);
87 return Task.FromResult(new ContentResponse(ContentType, Parsed, Data));
88 }
89
97 public bool Encodes(object Object, out Grade Grade, params string[] AcceptedContentTypes)
98 {
99 if (Object is SparqlResultSet &&
100 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
101 {
102 Grade = Grade.Excellent;
103 return true;
104 }
105 else if (Object is ObjectMatrix M && M.HasColumnNames &&
106 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
107 {
108 Grade = Grade.Ok;
109 return true;
110 }
111 else if (Object is bool &&
112 InternetContent.IsAccepted(SparqlResultSetContentTypes, AcceptedContentTypes))
113 {
114 Grade = Grade.Barely;
115 return true;
116 }
117 else
118 {
119 Grade = Grade.NotAtAll;
120 return false;
121 }
122 }
123
132 public Task<ContentResponse> EncodeAsync(object Object, Encoding Encoding, ICodecProgress Progress, params string[] AcceptedContentTypes)
133 {
134 if (Encoding is null)
135 Encoding = Encoding.UTF8;
136
137 object ResultObj;
138 bool Pretty = false;
139
140 if (Object is SparqlResultSet Result)
141 {
142 ResultObj = Encode(Result);
143 Pretty = Result.Pretty;
144 }
145 else if (Object is ObjectMatrix M)
146 ResultObj = Encode(M);
147 else if (Object is bool b)
148 ResultObj = Encode(b);
149 else
150 return Task.FromResult(new ContentResponse(new ArgumentException("Unable to encode object.", nameof(Object))));
151
152 string Text = JSON.Encode(ResultObj, Pretty);
153 byte[] Bin = Encoding.GetBytes(Text);
154 string ContentType = SparqlResultSetContentTypes[0] + "; charset=" + Encoding.WebName;
155
156 return Task.FromResult(new ContentResponse(ContentType, Object, Bin));
157 }
158
159 private static Dictionary<string, object> Encode(SparqlResultSet Result)
160 {
161 Dictionary<string, object> Head = new Dictionary<string, object>();
162 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
163 {
164 { "head", Head }
165 };
166
167 if (!(Result.Variables is null))
168 Head["vars"] = Result.Variables;
169
170 if (!(Result.Links is null))
171 {
173
174 foreach (Uri Link in Result.Links)
175 Links.Add(Link.ToString());
176
177 Head["link"] = Links.ToArray();
178 }
179
180 if (Result.BooleanResult.HasValue)
181 ResultObj["boolean"] = Result.BooleanResult.Value;
182 else
183 {
184 Dictionary<string, object> Results = new Dictionary<string, object>();
185 ResultObj["results"] = Results;
186
187 if (!(Result.Records is null))
188 {
190
191 foreach (ISparqlResultRecord Record in Result.Records)
192 {
193 Dictionary<string, object> Binding = new Dictionary<string, object>();
194
195 foreach (ISparqlResultItem Item in Record)
196 Binding[Item.Name] = OutputValue(Item.Value);
197
198 Bindings.Add(Binding);
199 }
200
201 Results["bindings"] = Bindings.ToArray();
202 }
203 }
204
205 return ResultObj;
206 }
207
208 private static Dictionary<string, object> Encode(ObjectMatrix Result)
209 {
210 Dictionary<string, object> Head = new Dictionary<string, object>();
211 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
212 {
213 { "head", Head }
214 };
215
216 if (!(Result.ColumnNames is null))
217 Head["vars"] = Result.ColumnNames;
218
219 Dictionary<string, object> Results = new Dictionary<string, object>();
220 ResultObj["results"] = Results;
221
223
224 int x, y;
225 int NrRows = Result.Rows;
226 int NrColumns = Result.Columns;
227
228 for (y = 0; y < NrRows; y++)
229 {
230 Dictionary<string, object> Binding = new Dictionary<string, object>();
231
232 for (x = 0; x < NrColumns; x++)
233 Binding[Result.ColumnNames[x]] = OutputValue(Result.GetElement(x, y)?.AssociatedObjectValue);
234
235 Bindings.Add(Binding);
236 }
237
238 Results["bindings"] = Bindings.ToArray();
239
240 return ResultObj;
241 }
242
243 private static Dictionary<string, object> Encode(bool Result)
244 {
245 Dictionary<string, object> Head = new Dictionary<string, object>();
246 Dictionary<string, object> ResultObj = new Dictionary<string, object>()
247 {
248 { "head", Head },
249 { "boolean", Result }
250 };
251
252 return ResultObj;
253 }
254
255 private static Dictionary<string, object> OutputValue(object Value)
256 {
257 Dictionary<string, object> Result;
258
259 if (Value is ISemanticElement E)
260 {
261 if (E is ISemanticLiteral Literal)
262 {
263 Result = new Dictionary<string, object>()
264 {
265 { "type", "literal" },
266 { "value", Literal.Value }
267 };
268
269 if (!string.IsNullOrEmpty(Literal.StringType))
270 Result["datatype"] = Literal.StringType;
271
272 if (Literal is StringLiteral StringLiteral &&
273 !string.IsNullOrEmpty(StringLiteral.Language))
274 {
275 Result["xml:lang"] = StringLiteral.Language;
276 }
277 else if (Literal is CustomLiteral CustomLiteral &&
278 !string.IsNullOrEmpty(CustomLiteral.Language))
279 {
280 Result["xml:lang"] = CustomLiteral.Language;
281 }
282 }
283 else if (E is UriNode N)
284 {
285 Result = new Dictionary<string, object>()
286 {
287 { "type", "uri" },
288 { "value", N.Uri.ToString() }
289 };
290 }
291 else if (E is BlankNode N2)
292 {
293 Result = new Dictionary<string, object>()
294 {
295 { "type", "bnode" },
296 { "value", N2.NodeId }
297 };
298 }
299 else if (E is ISemanticTriple T)
300 {
301 Dictionary<string, object> Triple = new Dictionary<string, object>()
302 {
303 { "subject", OutputValue(T.Subject) },
304 { "predicate", OutputValue(T.Predicate) },
305 { "object", OutputValue(T.Object) }
306 };
307 Result = new Dictionary<string, object>()
308 {
309 { "type", "triple" },
310 { "value", Triple }
311 };
312 }
313 else
314 {
315 Result = new Dictionary<string, object>()
316 {
317 { "type", "literal" },
318 { "value", Value?.ToString() }
319 };
320 }
321 }
322 else
323 {
324 Result = new Dictionary<string, object>()
325 {
326 { "type", "literal" },
327 { "value", Value?.ToString() }
328 };
329 }
330
331 return Result;
332 }
333
340 public bool TryGetContentType(string FileExtension, out string ContentType)
341 {
342 if (string.Compare(FileExtension, SparqlResultSetFileExtensions[0], true) == 0)
343 {
344 ContentType = SparqlResultSetContentTypes[0];
345 return true;
346 }
347 else
348 {
349 ContentType = null;
350 return false;
351 }
352 }
353
360 public bool TryGetFileExtension(string ContentType, out string FileExtension)
361 {
362 if (Array.IndexOf(SparqlResultSetContentTypes, ContentType) >= 0)
363 {
364 FileExtension = SparqlResultSetFileExtensions[0];
365 return true;
366 }
367 else
368 {
369 FileExtension = null;
370 return false;
371 }
372 }
373 }
374}
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.
Helps with common JSON-related tasks.
Definition: JSON.cs:16
static object Parse(string Json)
Parses a JSON string.
Definition: JSON.cs:45
static string Encode(string s)
Encodes a string for inclusion in JSON.
Definition: JSON.cs:537
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< ContentResponse > DecodeAsync(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair< string, string >[] Fields, Uri BaseUri, ICodecProgress Progress)
Decodes an object
string[] ContentTypes
Supported Internet Content Types.
Task< ContentResponse > EncodeAsync(object Object, Encoding Encoding, ICodecProgress Progress, 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.
A chunked list is a linked list of chunks of objects of type T .
Definition: ChunkedList.cs:54
void Add(T Item)
Adds an item to the collection.
Definition: ChunkedList.cs:272
T[] ToArray()
Returns an array containing all elements of the collection.
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.
Grade
Grade enumeration
Definition: Grade.cs:7