ServerUtils.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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.IO;
  29. using System.Reflection;
  30. using System.Xml;
  31. using System.Xml.Serialization;
  32. using System.Text;
  33. using System.Collections.Generic;
  34. using log4net;
  35. using OpenSim.Framework;
  36. using OpenMetaverse;
  37. using OpenMetaverse.StructuredData;
  38. namespace OpenSim.Server.Base
  39. {
  40. public static class ServerUtils
  41. {
  42. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  43. public static byte[] SerializeResult(XmlSerializer xs, object data)
  44. {
  45. MemoryStream ms = new MemoryStream();
  46. XmlTextWriter xw = new XmlTextWriter(ms, Util.UTF8);
  47. xw.Formatting = Formatting.Indented;
  48. xs.Serialize(xw, data);
  49. xw.Flush();
  50. ms.Seek(0, SeekOrigin.Begin);
  51. byte[] ret = ms.GetBuffer();
  52. Array.Resize(ref ret, (int)ms.Length);
  53. return ret;
  54. }
  55. /// <summary>
  56. /// Load a plugin from a dll with the given class or interface
  57. /// </summary>
  58. /// <param name="dllName"></param>
  59. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  60. /// <returns></returns>
  61. public static T LoadPlugin<T>(string dllName, Object[] args) where T:class
  62. {
  63. // This is good to debug configuration problems
  64. //if (dllName == string.Empty)
  65. // Util.PrintCallStack();
  66. string[] parts = dllName.Split(new char[] {':'});
  67. dllName = parts[0];
  68. string className = String.Empty;
  69. if (parts.Length > 1)
  70. className = parts[1];
  71. return LoadPlugin<T>(dllName, className, args);
  72. }
  73. /// <summary>
  74. /// Load a plugin from a dll with the given class or interface
  75. /// </summary>
  76. /// <param name="dllName"></param>
  77. /// <param name="className"></param>
  78. /// <param name="args">The arguments which control which constructor is invoked on the plugin</param>
  79. /// <returns></returns>
  80. public static T LoadPlugin<T>(string dllName, string className, Object[] args) where T:class
  81. {
  82. string interfaceName = typeof(T).ToString();
  83. try
  84. {
  85. Assembly pluginAssembly = Assembly.LoadFrom(dllName);
  86. foreach (Type pluginType in pluginAssembly.GetTypes())
  87. {
  88. if (pluginType.IsPublic)
  89. {
  90. if (className != String.Empty
  91. && pluginType.ToString() != pluginType.Namespace + "." + className)
  92. continue;
  93. Type typeInterface = pluginType.GetInterface(interfaceName, true);
  94. if (typeInterface != null)
  95. {
  96. T plug = null;
  97. try
  98. {
  99. plug = (T)Activator.CreateInstance(pluginType,
  100. args);
  101. }
  102. catch (Exception e)
  103. {
  104. if (!(e is System.MissingMethodException))
  105. {
  106. m_log.ErrorFormat("Error loading plugin {0} from {1}. Exception: {2}",
  107. interfaceName, dllName, e.InnerException == null ? e.Message : e.InnerException.Message);
  108. }
  109. return null;
  110. }
  111. return plug;
  112. }
  113. }
  114. }
  115. return null;
  116. }
  117. catch (ReflectionTypeLoadException rtle)
  118. {
  119. m_log.Error(string.Format("Error loading plugin from {0}:\n{1}", dllName,
  120. String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
  121. rtle);
  122. return null;
  123. }
  124. catch (Exception e)
  125. {
  126. m_log.Error(string.Format("Error loading plugin from {0}", dllName), e);
  127. return null;
  128. }
  129. }
  130. public static Dictionary<string, object> ParseQueryString(string query)
  131. {
  132. Dictionary<string, object> result = new Dictionary<string, object>();
  133. string[] terms = query.Split(new char[] {'&'});
  134. if (terms.Length == 0)
  135. return result;
  136. foreach (string t in terms)
  137. {
  138. string[] elems = t.Split(new char[] {'='});
  139. if (elems.Length == 0)
  140. continue;
  141. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  142. string value = String.Empty;
  143. if (elems.Length > 1)
  144. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  145. if (name.EndsWith("[]"))
  146. {
  147. string cleanName = name.Substring(0, name.Length - 2);
  148. if (result.ContainsKey(cleanName))
  149. {
  150. if (!(result[cleanName] is List<string>))
  151. continue;
  152. List<string> l = (List<string>)result[cleanName];
  153. l.Add(value);
  154. }
  155. else
  156. {
  157. List<string> newList = new List<string>();
  158. newList.Add(value);
  159. result[cleanName] = newList;
  160. }
  161. }
  162. else
  163. {
  164. if (!result.ContainsKey(name))
  165. result[name] = value;
  166. }
  167. }
  168. return result;
  169. }
  170. public static string BuildQueryString(Dictionary<string, object> data)
  171. {
  172. string qstring = String.Empty;
  173. string part;
  174. foreach (KeyValuePair<string, object> kvp in data)
  175. {
  176. if (kvp.Value is List<string>)
  177. {
  178. List<string> l = (List<String>)kvp.Value;
  179. foreach (string s in l)
  180. {
  181. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  182. "[]=" + System.Web.HttpUtility.UrlEncode(s);
  183. if (qstring != String.Empty)
  184. qstring += "&";
  185. qstring += part;
  186. }
  187. }
  188. else
  189. {
  190. if (kvp.Value.ToString() != String.Empty)
  191. {
  192. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  193. "=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
  194. }
  195. else
  196. {
  197. part = System.Web.HttpUtility.UrlEncode(kvp.Key);
  198. }
  199. if (qstring != String.Empty)
  200. qstring += "&";
  201. qstring += part;
  202. }
  203. }
  204. return qstring;
  205. }
  206. public static string BuildXmlResponse(Dictionary<string, object> data)
  207. {
  208. XmlDocument doc = new XmlDocument();
  209. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  210. "", "");
  211. doc.AppendChild(xmlnode);
  212. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  213. "");
  214. doc.AppendChild(rootElement);
  215. BuildXmlData(rootElement, data);
  216. return doc.InnerXml;
  217. }
  218. private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
  219. {
  220. foreach (KeyValuePair<string, object> kvp in data)
  221. {
  222. if (kvp.Value == null)
  223. continue;
  224. XmlElement elem = parent.OwnerDocument.CreateElement("",
  225. XmlConvert.EncodeLocalName(kvp.Key), "");
  226. if (kvp.Value is Dictionary<string, object>)
  227. {
  228. XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
  229. "type", "");
  230. type.Value = "List";
  231. elem.Attributes.Append(type);
  232. BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
  233. }
  234. else
  235. {
  236. elem.AppendChild(parent.OwnerDocument.CreateTextNode(
  237. kvp.Value.ToString()));
  238. }
  239. parent.AppendChild(elem);
  240. }
  241. }
  242. public static Dictionary<string, object> ParseXmlResponse(string data)
  243. {
  244. //m_log.DebugFormat("[XXX]: received xml string: {0}", data);
  245. Dictionary<string, object> ret = new Dictionary<string, object>();
  246. XmlDocument doc = new XmlDocument();
  247. doc.LoadXml(data);
  248. XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
  249. if (rootL.Count != 1)
  250. return ret;
  251. XmlNode rootNode = rootL[0];
  252. ret = ParseElement(rootNode);
  253. return ret;
  254. }
  255. private static Dictionary<string, object> ParseElement(XmlNode element)
  256. {
  257. Dictionary<string, object> ret = new Dictionary<string, object>();
  258. XmlNodeList partL = element.ChildNodes;
  259. foreach (XmlNode part in partL)
  260. {
  261. XmlNode type = part.Attributes.GetNamedItem("type");
  262. if (type == null || type.Value != "List")
  263. {
  264. ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
  265. }
  266. else
  267. {
  268. ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
  269. }
  270. }
  271. return ret;
  272. }
  273. public static bool ParseStringToOSDMap(string input, out OSDMap map)
  274. {
  275. try
  276. {
  277. map = null;
  278. OSD tmpbuff = null;
  279. try
  280. {
  281. tmpbuff = OSDParser.DeserializeJson(input);
  282. }
  283. catch
  284. {
  285. m_log.DebugFormat("[ServerUtils]: Parse Caught Error Deserializei {0} ", input);
  286. return false;
  287. }
  288. if (tmpbuff.Type == OSDType.Map)
  289. {
  290. map = (OSDMap)tmpbuff;
  291. return true;
  292. }
  293. else
  294. return false;
  295. }
  296. catch (NullReferenceException e)
  297. {
  298. m_log.ErrorFormat("[ServerUtils]: exception on ParseStringToJson {0}", e.Message);
  299. map = null;
  300. return false;
  301. }
  302. }
  303. }
  304. }