JsonStore.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. */
  27. using Mono.Addins;
  28. using System;
  29. using System.Reflection;
  30. using System.Threading;
  31. using System.Text;
  32. using System.Net;
  33. using System.Net.Sockets;
  34. using log4net;
  35. using Nini.Config;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.Framework.Interfaces;
  40. using OpenSim.Region.Framework.Scenes;
  41. using System.Collections.Generic;
  42. using System.Text.RegularExpressions;
  43. namespace OpenSim.Region.OptionalModules.Scripting.JsonStore
  44. {
  45. public class JsonStore
  46. {
  47. private static readonly ILog m_log =
  48. LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  49. private OSD m_ValueStore;
  50. protected class TakeValueCallbackClass
  51. {
  52. public string Path { get; set; }
  53. public bool UseJson { get; set; }
  54. public TakeValueCallback Callback { get; set; }
  55. public TakeValueCallbackClass(string spath, bool usejson, TakeValueCallback cback)
  56. {
  57. Path = spath;
  58. UseJson = usejson;
  59. Callback = cback;
  60. }
  61. }
  62. protected List<TakeValueCallbackClass> m_TakeStore;
  63. protected List<TakeValueCallbackClass> m_ReadStore;
  64. // -----------------------------------------------------------------
  65. /// <summary>
  66. ///
  67. /// </summary>
  68. // -----------------------------------------------------------------
  69. public JsonStore() : this("") {}
  70. public JsonStore(string value)
  71. {
  72. m_TakeStore = new List<TakeValueCallbackClass>();
  73. m_ReadStore = new List<TakeValueCallbackClass>();
  74. if (String.IsNullOrEmpty(value))
  75. m_ValueStore = new OSDMap();
  76. else
  77. m_ValueStore = OSDParser.DeserializeJson(value);
  78. }
  79. // -----------------------------------------------------------------
  80. /// <summary>
  81. ///
  82. /// </summary>
  83. // -----------------------------------------------------------------
  84. public bool TestPath(string expr, bool useJson)
  85. {
  86. Stack<string> path = ParsePathExpression(expr);
  87. OSD result = ProcessPathExpression(m_ValueStore,path);
  88. if (result == null)
  89. return false;
  90. if (useJson || result.Type == OSDType.String)
  91. return true;
  92. return false;
  93. }
  94. // -----------------------------------------------------------------
  95. /// <summary>
  96. ///
  97. /// </summary>
  98. // -----------------------------------------------------------------
  99. public bool GetValue(string expr, out string value, bool useJson)
  100. {
  101. Stack<string> path = ParsePathExpression(expr);
  102. OSD result = ProcessPathExpression(m_ValueStore,path);
  103. return ConvertOutputValue(result,out value,useJson);
  104. }
  105. // -----------------------------------------------------------------
  106. /// <summary>
  107. ///
  108. /// </summary>
  109. // -----------------------------------------------------------------
  110. public bool RemoveValue(string expr)
  111. {
  112. return SetValueFromExpression(expr,null);
  113. }
  114. // -----------------------------------------------------------------
  115. /// <summary>
  116. ///
  117. /// </summary>
  118. // -----------------------------------------------------------------
  119. public bool SetValue(string expr, string value, bool useJson)
  120. {
  121. OSD ovalue = useJson ? OSDParser.DeserializeJson(value) : new OSDString(value);
  122. return SetValueFromExpression(expr,ovalue);
  123. }
  124. // -----------------------------------------------------------------
  125. /// <summary>
  126. ///
  127. /// </summary>
  128. // -----------------------------------------------------------------
  129. public bool TakeValue(string expr, bool useJson, TakeValueCallback cback)
  130. {
  131. Stack<string> path = ParsePathExpression(expr);
  132. string pexpr = PathExpressionToKey(path);
  133. OSD result = ProcessPathExpression(m_ValueStore,path);
  134. if (result == null)
  135. {
  136. m_TakeStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
  137. return false;
  138. }
  139. string value = String.Empty;
  140. if (! ConvertOutputValue(result,out value,useJson))
  141. {
  142. // the structure does not match the request so i guess we'll wait
  143. m_TakeStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
  144. return false;
  145. }
  146. SetValueFromExpression(expr,null);
  147. cback(value);
  148. return true;
  149. }
  150. // -----------------------------------------------------------------
  151. /// <summary>
  152. ///
  153. /// </summary>
  154. // -----------------------------------------------------------------
  155. public bool ReadValue(string expr, bool useJson, TakeValueCallback cback)
  156. {
  157. Stack<string> path = ParsePathExpression(expr);
  158. string pexpr = PathExpressionToKey(path);
  159. OSD result = ProcessPathExpression(m_ValueStore,path);
  160. if (result == null)
  161. {
  162. m_ReadStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
  163. return false;
  164. }
  165. string value = String.Empty;
  166. if (! ConvertOutputValue(result,out value,useJson))
  167. {
  168. // the structure does not match the request so i guess we'll wait
  169. m_ReadStore.Add(new TakeValueCallbackClass(pexpr,useJson,cback));
  170. return false;
  171. }
  172. cback(value);
  173. return true;
  174. }
  175. // -----------------------------------------------------------------
  176. /// <summary>
  177. ///
  178. /// </summary>
  179. // -----------------------------------------------------------------
  180. protected bool SetValueFromExpression(string expr, OSD ovalue)
  181. {
  182. Stack<string> path = ParsePathExpression(expr);
  183. if (path.Count == 0)
  184. {
  185. m_ValueStore = ovalue;
  186. return true;
  187. }
  188. string pkey = path.Pop();
  189. string pexpr = PathExpressionToKey(path);
  190. if (pexpr != "")
  191. pexpr += ".";
  192. OSD result = ProcessPathExpression(m_ValueStore,path);
  193. if (result == null)
  194. return false;
  195. Regex aPattern = new Regex("\\[([0-9]+|\\+)\\]");
  196. MatchCollection amatches = aPattern.Matches(pkey,0);
  197. if (amatches.Count > 0)
  198. {
  199. if (result.Type != OSDType.Array)
  200. return false;
  201. OSDArray amap = result as OSDArray;
  202. Match match = amatches[0];
  203. GroupCollection groups = match.Groups;
  204. string akey = groups[1].Value;
  205. if (akey == "+")
  206. {
  207. string npkey = String.Format("[{0}]",amap.Count);
  208. amap.Add(ovalue);
  209. InvokeNextCallback(pexpr + npkey);
  210. return true;
  211. }
  212. int aval = Convert.ToInt32(akey);
  213. if (0 <= aval && aval < amap.Count)
  214. {
  215. if (ovalue == null)
  216. amap.RemoveAt(aval);
  217. else
  218. {
  219. amap[aval] = ovalue;
  220. InvokeNextCallback(pexpr + pkey);
  221. }
  222. return true;
  223. }
  224. return false;
  225. }
  226. Regex hPattern = new Regex("{([^}]+)}");
  227. MatchCollection hmatches = hPattern.Matches(pkey,0);
  228. if (hmatches.Count > 0)
  229. {
  230. Match match = hmatches[0];
  231. GroupCollection groups = match.Groups;
  232. string hkey = groups[1].Value;
  233. if (result is OSDMap)
  234. {
  235. OSDMap hmap = result as OSDMap;
  236. if (ovalue != null)
  237. {
  238. hmap[hkey] = ovalue;
  239. InvokeNextCallback(pexpr + pkey);
  240. }
  241. else if (hmap.ContainsKey(hkey))
  242. hmap.Remove(hkey);
  243. return true;
  244. }
  245. return false;
  246. }
  247. // Shouldn't get here if the path was checked correctly
  248. m_log.WarnFormat("[JsonStore] invalid path expression");
  249. return false;
  250. }
  251. // -----------------------------------------------------------------
  252. /// <summary>
  253. ///
  254. /// </summary>
  255. // -----------------------------------------------------------------
  256. protected bool InvokeNextCallback(string pexpr)
  257. {
  258. // Process all of the reads that match the expression first
  259. List<TakeValueCallbackClass> reads =
  260. m_ReadStore.FindAll(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); });
  261. foreach (TakeValueCallbackClass readcb in reads)
  262. {
  263. m_ReadStore.Remove(readcb);
  264. ReadValue(readcb.Path,readcb.UseJson,readcb.Callback);
  265. }
  266. // Process one take next
  267. TakeValueCallbackClass takecb =
  268. m_TakeStore.Find(delegate(TakeValueCallbackClass tb) { return pexpr.StartsWith(tb.Path); });
  269. if (takecb != null)
  270. {
  271. m_TakeStore.Remove(takecb);
  272. TakeValue(takecb.Path,takecb.UseJson,takecb.Callback);
  273. return true;
  274. }
  275. return false;
  276. }
  277. // -----------------------------------------------------------------
  278. /// <summary>
  279. /// Parse the path expression and put the components into a stack. We
  280. /// use a stack because we process the path in inverse order later
  281. /// </summary>
  282. // -----------------------------------------------------------------
  283. protected static Stack<string> ParsePathExpression(string path)
  284. {
  285. Stack<string> m_path = new Stack<string>();
  286. // add front and rear separators
  287. path = "." + path + ".";
  288. // add separators for quoted paths
  289. Regex pass1 = new Regex("{[^}]+}");
  290. path = pass1.Replace(path,".$0.",-1,0);
  291. // add separators for array references
  292. Regex pass2 = new Regex("(\\[[0-9]+\\]|\\[\\+\\])");
  293. path = pass2.Replace(path,".$0.",-1,0);
  294. // add quotes to bare identifier
  295. Regex pass3 = new Regex("\\.([a-zA-Z]+)");
  296. path = pass3.Replace(path,".{$1}",-1,0);
  297. // remove extra separators
  298. Regex pass4 = new Regex("\\.+");
  299. path = pass4.Replace(path,".",-1,0);
  300. Regex validate = new Regex("^\\.(({[^}]+}|\\[[0-9]+\\]|\\[\\+\\])\\.)+$");
  301. if (validate.IsMatch(path))
  302. {
  303. Regex parser = new Regex("\\.({[^}]+}|\\[[0-9]+\\]|\\[\\+\\]+)");
  304. MatchCollection matches = parser.Matches(path,0);
  305. foreach (Match match in matches)
  306. m_path.Push(match.Groups[1].Value);
  307. }
  308. return m_path;
  309. }
  310. // -----------------------------------------------------------------
  311. /// <summary>
  312. ///
  313. /// </summary>
  314. /// <param>path is a stack where the top level of the path is at the bottom of the stack</param>
  315. // -----------------------------------------------------------------
  316. protected static OSD ProcessPathExpression(OSD map, Stack<string> path)
  317. {
  318. if (path.Count == 0)
  319. return map;
  320. string pkey = path.Pop();
  321. OSD rmap = ProcessPathExpression(map,path);
  322. if (rmap == null)
  323. return null;
  324. // ---------- Check for an array index ----------
  325. Regex aPattern = new Regex("\\[([0-9]+)\\]");
  326. MatchCollection amatches = aPattern.Matches(pkey,0);
  327. if (amatches.Count > 0)
  328. {
  329. if (rmap.Type != OSDType.Array)
  330. {
  331. m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}",OSDType.Array,rmap.Type,pkey);
  332. return null;
  333. }
  334. OSDArray amap = rmap as OSDArray;
  335. Match match = amatches[0];
  336. GroupCollection groups = match.Groups;
  337. string akey = groups[1].Value;
  338. int aval = Convert.ToInt32(akey);
  339. if (aval < amap.Count)
  340. return (OSD) amap[aval];
  341. return null;
  342. }
  343. // ---------- Check for a hash index ----------
  344. Regex hPattern = new Regex("{([^}]+)}");
  345. MatchCollection hmatches = hPattern.Matches(pkey,0);
  346. if (hmatches.Count > 0)
  347. {
  348. if (rmap.Type != OSDType.Map)
  349. {
  350. m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}",OSDType.Map,rmap.Type,pkey);
  351. return null;
  352. }
  353. OSDMap hmap = rmap as OSDMap;
  354. Match match = hmatches[0];
  355. GroupCollection groups = match.Groups;
  356. string hkey = groups[1].Value;
  357. if (hmap.ContainsKey(hkey))
  358. return (OSD) hmap[hkey];
  359. return null;
  360. }
  361. // Shouldn't get here if the path was checked correctly
  362. m_log.WarnFormat("[JsonStore] Path type (unknown) does not match the structure");
  363. return null;
  364. }
  365. // -----------------------------------------------------------------
  366. /// <summary>
  367. ///
  368. /// </summary>
  369. // -----------------------------------------------------------------
  370. protected static bool ConvertOutputValue(OSD result, out string value, bool useJson)
  371. {
  372. value = String.Empty;
  373. // If we couldn't process the path
  374. if (result == null)
  375. return false;
  376. if (useJson)
  377. {
  378. // The path pointed to an intermediate hash structure
  379. if (result.Type == OSDType.Map)
  380. {
  381. value = OSDParser.SerializeJsonString(result as OSDMap);
  382. return true;
  383. }
  384. // The path pointed to an intermediate hash structure
  385. if (result.Type == OSDType.Array)
  386. {
  387. value = OSDParser.SerializeJsonString(result as OSDArray);
  388. return true;
  389. }
  390. value = "'" + result.AsString() + "'";
  391. return true;
  392. }
  393. if (result.Type == OSDType.String)
  394. {
  395. value = result.AsString();
  396. return true;
  397. }
  398. return false;
  399. }
  400. // -----------------------------------------------------------------
  401. /// <summary>
  402. ///
  403. /// </summary>
  404. // -----------------------------------------------------------------
  405. protected static string PathExpressionToKey(Stack<string> path)
  406. {
  407. if (path.Count == 0)
  408. return "";
  409. string pkey = "";
  410. foreach (string k in path)
  411. pkey = (pkey == "") ? k : (k + "." + pkey);
  412. return pkey;
  413. }
  414. }
  415. }