ExternalRepresentationUtils.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  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 OpenSimulator 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 System;
  28. using System.Collections.Generic;
  29. using System.IO;
  30. using System.Reflection;
  31. using System.Xml;
  32. using log4net;
  33. using OpenMetaverse;
  34. using OpenSim.Services.Interfaces;
  35. namespace OpenSim.Framework.Serialization.External
  36. {
  37. /// <summary>
  38. /// Utilities for manipulating external representations of data structures in OpenSim
  39. /// </summary>
  40. public class ExternalRepresentationUtils
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. /// <summary>
  44. /// Populate a node with data read from xml using a dictinoary of processors
  45. /// </summary>
  46. /// <param name="nodeToFill"></param>
  47. /// <param name="processors">/param>
  48. /// <param name="xtr"></param>
  49. /// <returns>true on successful, false if there were any processing failures</returns>
  50. public static bool ExecuteReadProcessors<NodeType>(
  51. NodeType nodeToFill, Dictionary<string, Action<NodeType, XmlReader>> processors, XmlReader xtr)
  52. {
  53. return ExecuteReadProcessors(
  54. nodeToFill,
  55. processors,
  56. xtr,
  57. (o, name, e)
  58. => m_log.DebugFormat(
  59. "[ExternalRepresentationUtils]: Exception while parsing element {0}, continuing. Exception {1}{2}",
  60. name, e.Message, e.StackTrace));
  61. }
  62. /// <summary>
  63. /// Populate a node with data read from xml using a dictinoary of processors
  64. /// </summary>
  65. /// <param name="nodeToFill"></param>
  66. /// <param name="processors"></param>
  67. /// <param name="xtr"></param>
  68. /// <param name="parseExceptionAction">
  69. /// Action to take if there is a parsing problem. This will usually just be to log the exception
  70. /// </param>
  71. /// <returns>true on successful, false if there were any processing failures</returns>
  72. public static bool ExecuteReadProcessors<NodeType>(
  73. NodeType nodeToFill,
  74. Dictionary<string, Action<NodeType, XmlReader>> processors,
  75. XmlReader xtr,
  76. Action<NodeType, string, Exception> parseExceptionAction)
  77. {
  78. bool errors = false;
  79. string nodeName = string.Empty;
  80. while (xtr.NodeType != XmlNodeType.EndElement)
  81. {
  82. nodeName = xtr.Name;
  83. // m_log.DebugFormat("[ExternalRepresentationUtils]: Processing: {0}", nodeName);
  84. Action<NodeType, XmlReader> p = null;
  85. if (processors.TryGetValue(xtr.Name, out p))
  86. {
  87. // m_log.DebugFormat("[ExternalRepresentationUtils]: Found {0} processor, nodeName);
  88. try
  89. {
  90. p(nodeToFill, xtr);
  91. }
  92. catch (Exception e)
  93. {
  94. errors = true;
  95. parseExceptionAction(nodeToFill, nodeName, e);
  96. if (xtr.NodeType == XmlNodeType.EndElement)
  97. xtr.Read();
  98. }
  99. }
  100. else
  101. {
  102. // m_log.DebugFormat("[LandDataSerializer]: caught unknown element {0}", nodeName);
  103. xtr.ReadOuterXml(); // ignore
  104. }
  105. }
  106. return errors;
  107. }
  108. /// <summary>
  109. /// Takes a XML representation of a SceneObjectPart and returns another XML representation
  110. /// with creator data added to it.
  111. /// </summary>
  112. /// <param name="xml">The SceneObjectPart represented in XML2</param>
  113. /// <param name="homeURL">The URL of the user agents service (home) for the creator</param>
  114. /// <param name="userService">The service for retrieving user account information</param>
  115. /// <param name="scopeID">The scope of the user account information (Grid ID)</param>
  116. /// <returns>The SceneObjectPart represented in XML2</returns>
  117. [Obsolete("This method is deprecated. Use RewriteSOP instead.")]
  118. public static string RewriteSOP_Old(string xml, string homeURL, IUserAccountService userService, UUID scopeID)
  119. {
  120. if (xml == string.Empty || homeURL == string.Empty || userService == null)
  121. return xml;
  122. XmlDocument doc = new XmlDocument();
  123. doc.LoadXml(xml);
  124. XmlNodeList sops = doc.GetElementsByTagName("SceneObjectPart");
  125. foreach (XmlNode sop in sops)
  126. {
  127. UserAccount creator = null;
  128. bool hasCreatorData = false;
  129. XmlNodeList nodes = sop.ChildNodes;
  130. foreach (XmlNode node in nodes)
  131. {
  132. if (node.Name == "CreatorID")
  133. {
  134. UUID uuid = UUID.Zero;
  135. UUID.TryParse(node.InnerText, out uuid);
  136. creator = userService.GetUserAccount(scopeID, uuid);
  137. }
  138. if (node.Name == "CreatorData" && node.InnerText != null && node.InnerText != string.Empty)
  139. hasCreatorData = true;
  140. //if (node.Name == "OwnerID")
  141. //{
  142. // UserAccount owner = GetUser(node.InnerText);
  143. // if (owner != null)
  144. // node.InnerText = m_ProfileServiceURL + "/" + node.InnerText + "/" + owner.FirstName + " " + owner.LastName;
  145. //}
  146. }
  147. if (!hasCreatorData && creator != null)
  148. {
  149. XmlElement creatorData = doc.CreateElement("CreatorData");
  150. creatorData.InnerText = CalcCreatorData(homeURL, creator.FirstName + " " + creator.LastName);
  151. sop.AppendChild(creatorData);
  152. }
  153. }
  154. using (StringWriter wr = new StringWriter())
  155. {
  156. doc.Save(wr);
  157. return wr.ToString();
  158. }
  159. }
  160. /// <summary>
  161. /// Takes a XML representation of a SceneObjectPart and returns another XML representation
  162. /// with creator data added to it.
  163. /// </summary>
  164. /// <param name="xml">The SceneObjectPart represented in XML2</param>
  165. /// <param name="sceneName">An identifier for the component that's calling this function</param>
  166. /// <param name="homeURL">The URL of the user agents service (home) for the creator</param>
  167. /// <param name="userService">The service for retrieving user account information</param>
  168. /// <param name="scopeID">The scope of the user account information (Grid ID)</param>
  169. /// <returns>The SceneObjectPart represented in XML2</returns>
  170. public static string RewriteSOP(string xmlData, string sceneName, string homeURL, IUserAccountService userService, UUID scopeID)
  171. {
  172. // Console.WriteLine("Input XML [{0}]", xmlData);
  173. if (xmlData == string.Empty || homeURL == string.Empty || userService == null)
  174. return xmlData;
  175. using (StringWriter sw = new StringWriter())
  176. using (XmlTextWriter writer = new XmlTextWriter(sw))
  177. using (XmlTextReader wrappedReader = new XmlTextReader(xmlData, XmlNodeType.Element, null))
  178. using (XmlReader reader = XmlReader.Create(wrappedReader, new XmlReaderSettings() { IgnoreWhitespace = true, ConformanceLevel = ConformanceLevel.Fragment }))
  179. {
  180. TransformXml(reader, writer, sceneName, homeURL, userService, scopeID);
  181. // Console.WriteLine("Output: [{0}]", sw.ToString());
  182. return sw.ToString();
  183. }
  184. }
  185. protected static void TransformXml(XmlReader reader, XmlWriter writer, string sceneName, string homeURI, IUserAccountService userAccountService, UUID scopeID)
  186. {
  187. // m_log.DebugFormat("[HG ASSET MAPPER]: Transforming XML");
  188. int sopDepth = -1;
  189. UserAccount creator = null;
  190. bool hasCreatorData = false;
  191. while (reader.Read())
  192. {
  193. // Console.WriteLine("Depth: {0}, name {1}", reader.Depth, reader.Name);
  194. switch (reader.NodeType)
  195. {
  196. case XmlNodeType.Attribute:
  197. // Console.WriteLine("FOUND ATTRIBUTE {0}", reader.Name);
  198. writer.WriteAttributeString(reader.Name, reader.Value);
  199. break;
  200. case XmlNodeType.CDATA:
  201. writer.WriteCData(reader.Value);
  202. break;
  203. case XmlNodeType.Comment:
  204. writer.WriteComment(reader.Value);
  205. break;
  206. case XmlNodeType.DocumentType:
  207. writer.WriteDocType(reader.Name, reader.Value, null, null);
  208. break;
  209. case XmlNodeType.Element:
  210. // m_log.DebugFormat("Depth {0} at element {1}", reader.Depth, reader.Name);
  211. writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI);
  212. if (reader.HasAttributes)
  213. {
  214. while (reader.MoveToNextAttribute())
  215. writer.WriteAttributeString(reader.Name, reader.Value);
  216. reader.MoveToElement();
  217. }
  218. if (reader.LocalName == "SceneObjectPart")
  219. {
  220. if (sopDepth < 0)
  221. {
  222. sopDepth = reader.Depth;
  223. // m_log.DebugFormat("[HG ASSET MAPPER]: Set sopDepth to {0}", sopDepth);
  224. }
  225. }
  226. else
  227. {
  228. if (sopDepth >= 0 && reader.Depth == sopDepth + 1)
  229. {
  230. if (reader.Name == "CreatorID")
  231. {
  232. reader.Read();
  233. if (reader.NodeType == XmlNodeType.Element && reader.Name == "Guid" || reader.Name == "UUID")
  234. {
  235. reader.Read();
  236. if (reader.NodeType == XmlNodeType.Text)
  237. {
  238. UUID uuid = UUID.Zero;
  239. UUID.TryParse(reader.Value, out uuid);
  240. creator = userAccountService.GetUserAccount(scopeID, uuid);
  241. writer.WriteElementString("UUID", reader.Value);
  242. reader.Read();
  243. }
  244. else
  245. {
  246. // If we unexpected run across mixed content in this node, still carry on
  247. // transforming the subtree (this replicates earlier behaviour).
  248. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  249. }
  250. }
  251. else
  252. {
  253. // If we unexpected run across mixed content in this node, still carry on
  254. // transforming the subtree (this replicates earlier behaviour).
  255. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  256. }
  257. }
  258. else if (reader.Name == "CreatorData")
  259. {
  260. reader.Read();
  261. if (reader.NodeType == XmlNodeType.Text)
  262. {
  263. hasCreatorData = true;
  264. writer.WriteString(reader.Value);
  265. }
  266. else
  267. {
  268. // If we unexpected run across mixed content in this node, still carry on
  269. // transforming the subtree (this replicates earlier behaviour).
  270. TransformXml(reader, writer, sceneName, homeURI, userAccountService, scopeID);
  271. }
  272. }
  273. }
  274. }
  275. if (reader.IsEmptyElement)
  276. {
  277. // m_log.DebugFormat("[HG ASSET MAPPER]: Writing end for empty element {0}", reader.Name);
  278. writer.WriteEndElement();
  279. }
  280. break;
  281. case XmlNodeType.EndElement:
  282. // m_log.DebugFormat("Depth {0} at EndElement", reader.Depth);
  283. if (sopDepth == reader.Depth)
  284. {
  285. if (!hasCreatorData && creator != null)
  286. writer.WriteElementString(reader.Prefix, "CreatorData", reader.NamespaceURI, string.Format("{0};{1} {2}", homeURI, creator.FirstName, creator.LastName));
  287. // m_log.DebugFormat("[HG ASSET MAPPER]: Reset sopDepth");
  288. sopDepth = -1;
  289. creator = null;
  290. hasCreatorData = false;
  291. }
  292. writer.WriteEndElement();
  293. break;
  294. case XmlNodeType.EntityReference:
  295. writer.WriteEntityRef(reader.Name);
  296. break;
  297. case XmlNodeType.ProcessingInstruction:
  298. writer.WriteProcessingInstruction(reader.Name, reader.Value);
  299. break;
  300. case XmlNodeType.Text:
  301. writer.WriteString(reader.Value);
  302. break;
  303. case XmlNodeType.XmlDeclaration:
  304. // For various reasons, not all serializations have xml declarations (or consistent ones)
  305. // and as it's embedded inside a byte stream we don't need it anyway, so ignore.
  306. break;
  307. default:
  308. m_log.WarnFormat(
  309. "[HG ASSET MAPPER]: Unrecognized node {0} in asset XML transform in {1}",
  310. reader.NodeType, sceneName);
  311. break;
  312. }
  313. }
  314. }
  315. public static string CalcCreatorData(string homeURL, string name)
  316. {
  317. return homeURL + ";" + name;
  318. }
  319. internal static string CalcCreatorData(string homeURL, UUID uuid, string name)
  320. {
  321. return homeURL + "/" + uuid + ";" + name;
  322. }
  323. }
  324. }