aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs')
-rw-r--r--OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs500
1 files changed, 500 insertions, 0 deletions
diff --git a/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs
new file mode 100644
index 0000000..34894ba
--- /dev/null
+++ b/OpenSim/Region/OptionalModules/Scripting/JsonStore/JsonStore.cs
@@ -0,0 +1,500 @@
1/*
2 * Copyright (c) Contributors
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSim Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27using Mono.Addins;
28
29using System;
30using System.Reflection;
31using System.Threading;
32using System.Text;
33using System.Net;
34using System.Net.Sockets;
35using log4net;
36using Nini.Config;
37using OpenMetaverse;
38using OpenMetaverse.StructuredData;
39using OpenSim.Framework;
40using OpenSim.Region.Framework.Interfaces;
41using OpenSim.Region.Framework.Scenes;
42using System.Collections.Generic;
43using System.Text.RegularExpressions;
44
45namespace OpenSim.Region.OptionalModules.Scripting.JsonStore
46{
47 public class JsonStore
48 {
49 private static readonly ILog m_log =
50 LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
51
52 private OSD m_ValueStore;
53
54 protected class TakeValueCallbackClass
55 {
56 public string Path { get; set; }
57 public bool UseJson { get; set; }
58 public TakeValueCallback Callback { get; set; }
59
60 public TakeValueCallbackClass(string spath, bool usejson, TakeValueCallback cback)
61 {
62 Path = spath;
63 UseJson = usejson;
64 Callback = cback;
65 }
66 }
67
68 protected List<TakeValueCallbackClass> m_TakeStore;
69 protected List<TakeValueCallbackClass> m_ReadStore;
70
71
72 // -----------------------------------------------------------------
73 /// <summary>
74 ///
75 /// </summary>
76 // -----------------------------------------------------------------
77 public JsonStore() : this("") {}
78
79 public JsonStore(string value)
80 {
81 m_TakeStore = new List<TakeValueCallbackClass>();
82 m_ReadStore = new List<TakeValueCallbackClass>();
83
84 if (String.IsNullOrEmpty(value))
85 m_ValueStore = new OSDMap();
86 else
87 m_ValueStore = OSDParser.DeserializeJson(value);
88 }
89
90 // -----------------------------------------------------------------
91 /// <summary>
92 ///
93 /// </summary>
94 // -----------------------------------------------------------------
95 public bool TestPath(string expr, bool useJson)
96 {
97 Stack<string> path = ParsePathExpression(expr);
98 OSD result = ProcessPathExpression(m_ValueStore,path);
99
100 if (result == null)
101 return false;
102
103 if (useJson || result.Type == OSDType.String)
104 return true;
105
106 return false;
107 }
108
109 // -----------------------------------------------------------------
110 /// <summary>
111 ///
112 /// </summary>
113 // -----------------------------------------------------------------
114 public bool GetValue(string expr, out string value, bool useJson)
115 {
116 Stack<string> path = ParsePathExpression(expr);
117 OSD result = ProcessPathExpression(m_ValueStore,path);
118 return ConvertOutputValue(result,out value,useJson);
119 }
120
121
122 // -----------------------------------------------------------------
123 /// <summary>
124 ///
125 /// </summary>
126 // -----------------------------------------------------------------
127 public bool RemoveValue(string expr)
128 {
129 return SetValueFromExpression(expr,null);
130 }
131
132 // -----------------------------------------------------------------
133 /// <summary>
134 ///
135 /// </summary>
136 // -----------------------------------------------------------------
137 public bool SetValue(string expr, string value, bool useJson)
138 {
139 OSD ovalue = useJson ? OSDParser.DeserializeJson(value) : new OSDString(value);
140 return SetValueFromExpression(expr,ovalue);
141 }
142
143 // -----------------------------------------------------------------
144 /// <summary>
145 ///
146 /// </summary>
147 // -----------------------------------------------------------------
148 public bool TakeValue(string expr, bool useJson, TakeValueCallback cback)
149 {
150 Stack<string> path = ParsePathExpression(expr);
151 string pexpr = PathExpressionToKey(path);
152
153 OSD result = ProcessPathExpression(m_ValueStore,path);
154 if (result == null)
155 {
156 m_TakeStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
157 return false;
158 }
159
160 string value = String.Empty;
161 if (! ConvertOutputValue(result,out value,useJson))
162 {
163 // the structure does not match the request so i guess we'll wait
164 m_TakeStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
165 return false;
166 }
167
168 SetValueFromExpression(expr,null);
169 cback(value);
170
171 return true;
172 }
173
174 // -----------------------------------------------------------------
175 /// <summary>
176 ///
177 /// </summary>
178 // -----------------------------------------------------------------
179 public bool ReadValue(string expr, bool useJson, TakeValueCallback cback)
180 {
181 Stack<string> path = ParsePathExpression(expr);
182 string pexpr = PathExpressionToKey(path);
183
184 OSD result = ProcessPathExpression(m_ValueStore,path);
185 if (result == null)
186 {
187 m_ReadStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
188 return false;
189 }
190
191 string value = String.Empty;
192 if (! ConvertOutputValue(result,out value,useJson))
193 {
194 // the structure does not match the request so i guess we'll wait
195 m_ReadStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
196 return false;
197 }
198
199 cback(value);
200
201 return true;
202 }
203
204 // -----------------------------------------------------------------
205 /// <summary>
206 ///
207 /// </summary>
208 // -----------------------------------------------------------------
209 protected bool SetValueFromExpression(string expr, OSD ovalue)
210 {
211 Stack<string> path = ParsePathExpression(expr);
212 if (path.Count == 0)
213 {
214 m_ValueStore = ovalue;
215 return true;
216 }
217
218 string pkey = path.Pop();
219 string pexpr = PathExpressionToKey(path);
220 if (pexpr != "")
221 pexpr += ".";
222
223 OSD result = ProcessPathExpression(m_ValueStore,path);
224 if (result == null)
225 return false;
226
227 Regex aPattern = new Regex("\\[([0-9]+|\\+)\\]");
228 MatchCollection amatches = aPattern.Matches(pkey,0);
229
230 if (amatches.Count > 0)
231 {
232 if (result.Type != OSDType.Array)
233 return false;
234
235 OSDArray amap = result as OSDArray;
236
237 Match match = amatches[0];
238 GroupCollection groups = match.Groups;
239 string akey = groups[1].Value;
240
241 if (akey == "+")
242 {
243 string npkey = String.Format("[{0}]",amap.Count);
244
245 amap.Add(ovalue);
246 InvokeNextCallback(pexpr + npkey);
247 return true;
248 }
249
250 int aval = Convert.ToInt32(akey);
251 if (0 <= aval && aval < amap.Count)
252 {
253 if (ovalue == null)
254 amap.RemoveAt(aval);
255 else
256 {
257 amap[aval] = ovalue;
258 InvokeNextCallback(pexpr + pkey);
259 }
260 return true;
261 }
262
263 return false;
264 }
265
266 Regex hPattern = new Regex("{([^}]+)}");
267 MatchCollection hmatches = hPattern.Matches(pkey,0);
268
269 if (hmatches.Count > 0)
270 {
271 Match match = hmatches[0];
272 GroupCollection groups = match.Groups;
273 string hkey = groups[1].Value;
274
275 if (result is OSDMap)
276 {
277 OSDMap hmap = result as OSDMap;
278 if (ovalue != null)
279 {
280 hmap[hkey] = ovalue;
281 InvokeNextCallback(pexpr + pkey);
282 }
283 else if (hmap.ContainsKey(hkey))
284 hmap.Remove(hkey);
285
286 return true;
287 }
288
289 return false;
290 }
291
292 // Shouldn't get here if the path was checked correctly
293 m_log.WarnFormat("[JsonStore] invalid path expression");
294 return false;
295 }
296
297 // -----------------------------------------------------------------
298 /// <summary>
299 ///
300 /// </summary>
301 // -----------------------------------------------------------------
302 protected bool InvokeNextCallback(string pexpr)
303 {
304 // Process all of the reads that match the expression first
305 List<TakeValueCallbackClass> reads =
306 m_ReadStore.FindAll(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); });
307
308 foreach (TakeValueCallbackClass readcb in reads)
309 {
310 m_ReadStore.Remove(readcb);
311 ReadValue(readcb.Path,readcb.UseJson,readcb.Callback);
312 }
313
314 // Process one take next
315 TakeValueCallbackClass takecb =
316 m_TakeStore.Find(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); });
317
318 if (takecb != null)
319 {
320 m_TakeStore.Remove(takecb);
321 TakeValue(takecb.Path,takecb.UseJson,takecb.Callback);
322
323 return true;
324 }
325
326 return false;
327 }
328
329 // -----------------------------------------------------------------
330 /// <summary>
331 /// Parse the path expression and put the components into a stack. We
332 /// use a stack because we process the path in inverse order later
333 /// </summary>
334 // -----------------------------------------------------------------
335 protected static Stack<string> ParsePathExpression(string path)
336 {
337 Stack<string> m_path = new Stack<string>();
338
339 // add front and rear separators
340 path = "." + path + ".";
341
342 // add separators for quoted paths
343 Regex pass1 = new Regex("{[^}]+}");
344 path = pass1.Replace(path,".$0.",-1,0);
345
346 // add separators for array references
347 Regex pass2 = new Regex("(\\[[0-9]+\\]|\\[\\+\\])");
348 path = pass2.Replace(path,".$0.",-1,0);
349
350 // add quotes to bare identifier
351 Regex pass3 = new Regex("\\.([a-zA-Z]+)");
352 path = pass3.Replace(path,".{$1}",-1,0);
353
354 // remove extra separators
355 Regex pass4 = new Regex("\\.+");
356 path = pass4.Replace(path,".",-1,0);
357
358 Regex validate = new Regex("^\\.(({[^}]+}|\\[[0-9]+\\]|\\[\\+\\])\\.)+$");
359 if (validate.IsMatch(path))
360 {
361 Regex parser = new Regex("\\.({[^}]+}|\\[[0-9]+\\]|\\[\\+\\]+)");
362 MatchCollection matches = parser.Matches(path,0);
363 foreach (Match match in matches)
364 m_path.Push(match.Groups[1].Value);
365 }
366
367 return m_path;
368 }
369
370 // -----------------------------------------------------------------
371 /// <summary>
372 ///
373 /// </summary>
374 /// <param>path is a stack where the top level of the path is at the bottom of the stack</param>
375 // -----------------------------------------------------------------
376 protected static OSD ProcessPathExpression(OSD map, Stack<string> path)
377 {
378 if (path.Count == 0)
379 return map;
380
381 string pkey = path.Pop();
382
383 OSD rmap = ProcessPathExpression(map,path);
384 if (rmap == null)
385 return null;
386
387 // ---------- Check for an array index ----------
388 Regex aPattern = new Regex("\\[([0-9]+)\\]");
389 MatchCollection amatches = aPattern.Matches(pkey,0);
390
391 if (amatches.Count > 0)
392 {
393 if (rmap.Type != OSDType.Array)
394 {
395 m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}",OSDType.Array,rmap.Type,pkey);
396 return null;
397 }
398
399 OSDArray amap = rmap as OSDArray;
400
401 Match match = amatches[0];
402 GroupCollection groups = match.Groups;
403 string akey = groups[1].Value;
404 int aval = Convert.ToInt32(akey);
405
406 if (aval < amap.Count)
407 return (OSD) amap[aval];
408
409 return null;
410 }
411
412 // ---------- Check for a hash index ----------
413 Regex hPattern = new Regex("{([^}]+)}");
414 MatchCollection hmatches = hPattern.Matches(pkey,0);
415
416 if (hmatches.Count > 0)
417 {
418 if (rmap.Type != OSDType.Map)
419 {
420 m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}",OSDType.Map,rmap.Type,pkey);
421 return null;
422 }
423
424 OSDMap hmap = rmap as OSDMap;
425
426 Match match = hmatches[0];
427 GroupCollection groups = match.Groups;
428 string hkey = groups[1].Value;
429
430 if (hmap.ContainsKey(hkey))
431 return (OSD) hmap[hkey];
432
433 return null;
434 }
435
436 // Shouldn't get here if the path was checked correctly
437 m_log.WarnFormat("[JsonStore] Path type (unknown) does not match the structure");
438 return null;
439 }
440
441 // -----------------------------------------------------------------
442 /// <summary>
443 ///
444 /// </summary>
445 // -----------------------------------------------------------------
446 protected static bool ConvertOutputValue(OSD result, out string value, bool useJson)
447 {
448 value = String.Empty;
449
450 // If we couldn't process the path
451 if (result == null)
452 return false;
453
454 if (useJson)
455 {
456 // The path pointed to an intermediate hash structure
457 if (result.Type == OSDType.Map)
458 {
459 value = OSDParser.SerializeJsonString(result as OSDMap);
460 return true;
461 }
462
463 // The path pointed to an intermediate hash structure
464 if (result.Type == OSDType.Array)
465 {
466 value = OSDParser.SerializeJsonString(result as OSDArray);
467 return true;
468 }
469
470 value = "'" + result.AsString() + "'";
471 return true;
472 }
473
474 if (result.Type == OSDType.String)
475 {
476 value = result.AsString();
477 return true;
478 }
479
480 return false;
481 }
482
483 // -----------------------------------------------------------------
484 /// <summary>
485 ///
486 /// </summary>
487 // -----------------------------------------------------------------
488 protected static string PathExpressionToKey(Stack<string> path)
489 {
490 if (path.Count == 0)
491 return "";
492
493 string pkey = "";
494 foreach (string k in path)
495 pkey = (pkey == "") ? k : (k + "." + pkey);
496
497 return pkey;
498 }
499 }
500}