1
0

ServerUtils.cs 11 KB

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