ServerUtils.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. {
  105. m_log.ErrorFormat("Error loading plugin {0} from {1}. Exception: {2}",
  106. interfaceName, dllName, e.InnerException == null ? e.Message : e.InnerException.Message);
  107. }
  108. return null;
  109. }
  110. return plug;
  111. }
  112. }
  113. }
  114. return null;
  115. }
  116. catch (ReflectionTypeLoadException rtle)
  117. {
  118. m_log.Error(string.Format("Error loading plugin from {0}:\n{1}", dllName,
  119. String.Join("\n", Array.ConvertAll(rtle.LoaderExceptions, e => e.ToString()))),
  120. rtle);
  121. return null;
  122. }
  123. catch (Exception e)
  124. {
  125. m_log.Error(string.Format("Error loading plugin from {0}", dllName), e);
  126. return null;
  127. }
  128. }
  129. public static Dictionary<string, object> ParseQueryString(string query)
  130. {
  131. Dictionary<string, object> result = new Dictionary<string, object>();
  132. string[] terms = query.Split(new char[] {'&'});
  133. if (terms.Length == 0)
  134. return result;
  135. foreach (string t in terms)
  136. {
  137. string[] elems = t.Split(new char[] {'='});
  138. if (elems.Length == 0)
  139. continue;
  140. string name = System.Web.HttpUtility.UrlDecode(elems[0]);
  141. string value = String.Empty;
  142. if (elems.Length > 1)
  143. value = System.Web.HttpUtility.UrlDecode(elems[1]);
  144. if (name.EndsWith("[]"))
  145. {
  146. string cleanName = name.Substring(0, name.Length - 2);
  147. if (result.ContainsKey(cleanName))
  148. {
  149. if (!(result[cleanName] is List<string>))
  150. continue;
  151. List<string> l = (List<string>)result[cleanName];
  152. l.Add(value);
  153. }
  154. else
  155. {
  156. List<string> newList = new List<string>();
  157. newList.Add(value);
  158. result[cleanName] = newList;
  159. }
  160. }
  161. else
  162. {
  163. if (!result.ContainsKey(name))
  164. result[name] = value;
  165. }
  166. }
  167. return result;
  168. }
  169. public static string BuildQueryString(Dictionary<string, object> data)
  170. {
  171. string qstring = String.Empty;
  172. string part;
  173. foreach (KeyValuePair<string, object> kvp in data)
  174. {
  175. if (kvp.Value is List<string>)
  176. {
  177. List<string> l = (List<String>)kvp.Value;
  178. foreach (string s in l)
  179. {
  180. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  181. "[]=" + System.Web.HttpUtility.UrlEncode(s);
  182. if (qstring != String.Empty)
  183. qstring += "&";
  184. qstring += part;
  185. }
  186. }
  187. else
  188. {
  189. if (kvp.Value.ToString() != String.Empty)
  190. {
  191. part = System.Web.HttpUtility.UrlEncode(kvp.Key) +
  192. "=" + System.Web.HttpUtility.UrlEncode(kvp.Value.ToString());
  193. }
  194. else
  195. {
  196. part = System.Web.HttpUtility.UrlEncode(kvp.Key);
  197. }
  198. if (qstring != String.Empty)
  199. qstring += "&";
  200. qstring += part;
  201. }
  202. }
  203. return qstring;
  204. }
  205. public static string BuildXmlResponse(Dictionary<string, object> data)
  206. {
  207. XmlDocument doc = new XmlDocument();
  208. XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
  209. "", "");
  210. doc.AppendChild(xmlnode);
  211. XmlElement rootElement = doc.CreateElement("", "ServerResponse",
  212. "");
  213. doc.AppendChild(rootElement);
  214. BuildXmlData(rootElement, data);
  215. return doc.InnerXml;
  216. }
  217. private static void BuildXmlData(XmlElement parent, Dictionary<string, object> data)
  218. {
  219. foreach (KeyValuePair<string, object> kvp in data)
  220. {
  221. if (kvp.Value == null)
  222. continue;
  223. XmlElement elem = parent.OwnerDocument.CreateElement("",
  224. XmlConvert.EncodeLocalName(kvp.Key), "");
  225. if (kvp.Value is Dictionary<string, object>)
  226. {
  227. XmlAttribute type = parent.OwnerDocument.CreateAttribute("",
  228. "type", "");
  229. type.Value = "List";
  230. elem.Attributes.Append(type);
  231. BuildXmlData(elem, (Dictionary<string, object>)kvp.Value);
  232. }
  233. else
  234. {
  235. elem.AppendChild(parent.OwnerDocument.CreateTextNode(
  236. kvp.Value.ToString()));
  237. }
  238. parent.AppendChild(elem);
  239. }
  240. }
  241. public static Dictionary<string, object> ParseXmlResponse(string data)
  242. {
  243. //m_log.DebugFormat("[XXX]: received xml string: {0}", data);
  244. Dictionary<string, object> ret = new Dictionary<string, object>();
  245. XmlDocument doc = new XmlDocument();
  246. doc.LoadXml(data);
  247. XmlNodeList rootL = doc.GetElementsByTagName("ServerResponse");
  248. if (rootL.Count != 1)
  249. return ret;
  250. XmlNode rootNode = rootL[0];
  251. ret = ParseElement(rootNode);
  252. return ret;
  253. }
  254. private static Dictionary<string, object> ParseElement(XmlNode element)
  255. {
  256. Dictionary<string, object> ret = new Dictionary<string, object>();
  257. XmlNodeList partL = element.ChildNodes;
  258. foreach (XmlNode part in partL)
  259. {
  260. XmlNode type = part.Attributes.GetNamedItem("type");
  261. if (type == null || type.Value != "List")
  262. {
  263. ret[XmlConvert.DecodeName(part.Name)] = part.InnerText;
  264. }
  265. else
  266. {
  267. ret[XmlConvert.DecodeName(part.Name)] = ParseElement(part);
  268. }
  269. }
  270. return ret;
  271. }
  272. }
  273. }