AsynchronousRestObjectRequester.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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.Net;
  30. using System.Reflection;
  31. using System.Text;
  32. using System.Xml;
  33. using System.Xml.Serialization;
  34. using log4net;
  35. namespace OpenSim.Framework.Servers.HttpServer
  36. {
  37. public class AsynchronousRestObjectRequester
  38. {
  39. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  40. /// <summary>
  41. /// Perform an asynchronous REST request.
  42. /// </summary>
  43. /// <param name="verb">GET or POST</param>
  44. /// <param name="requestUrl"></param>
  45. /// <param name="obj"></param>
  46. /// <param name="action"></param>
  47. /// <returns></returns>
  48. ///
  49. /// <exception cref="System.Net.WebException">Thrown if we encounter a
  50. /// network issue while posting the request. You'll want to make
  51. /// sure you deal with this as they're not uncommon</exception>
  52. //
  53. public static void MakeRequest<TRequest, TResponse>(string verb,
  54. string requestUrl, TRequest obj, Action<TResponse> action)
  55. {
  56. // m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
  57. Type type = typeof (TRequest);
  58. WebRequest request = WebRequest.Create(requestUrl);
  59. WebResponse response = null;
  60. TResponse deserial = default(TResponse);
  61. XmlSerializer deserializer = new XmlSerializer(typeof (TResponse));
  62. request.Method = verb;
  63. if (verb == "POST")
  64. {
  65. request.ContentType = "text/xml";
  66. MemoryStream buffer = new MemoryStream();
  67. XmlWriterSettings settings = new XmlWriterSettings();
  68. settings.Encoding = Encoding.UTF8;
  69. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  70. {
  71. XmlSerializer serializer = new XmlSerializer(type);
  72. serializer.Serialize(writer, obj);
  73. writer.Flush();
  74. }
  75. int length = (int) buffer.Length;
  76. request.ContentLength = length;
  77. request.BeginGetRequestStream(delegate(IAsyncResult res)
  78. {
  79. Stream requestStream = request.EndGetRequestStream(res);
  80. requestStream.Write(buffer.ToArray(), 0, length);
  81. requestStream.Close();
  82. request.BeginGetResponse(delegate(IAsyncResult ar)
  83. {
  84. response = request.EndGetResponse(ar);
  85. Stream respStream = null;
  86. try
  87. {
  88. respStream = response.GetResponseStream();
  89. deserial = (TResponse)deserializer.Deserialize(
  90. respStream);
  91. }
  92. catch (System.InvalidOperationException)
  93. {
  94. }
  95. finally
  96. {
  97. // Let's not close this
  98. //buffer.Close();
  99. respStream.Close();
  100. response.Close();
  101. }
  102. action(deserial);
  103. }, null);
  104. }, null);
  105. return;
  106. }
  107. request.BeginGetResponse(delegate(IAsyncResult res2)
  108. {
  109. try
  110. {
  111. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  112. // documented in MSDN
  113. response = request.EndGetResponse(res2);
  114. Stream respStream = null;
  115. try
  116. {
  117. respStream = response.GetResponseStream();
  118. deserial = (TResponse)deserializer.Deserialize(respStream);
  119. }
  120. catch (System.InvalidOperationException)
  121. {
  122. }
  123. finally
  124. {
  125. respStream.Close();
  126. response.Close();
  127. }
  128. }
  129. catch (WebException e)
  130. {
  131. if (e.Status == WebExceptionStatus.ProtocolError)
  132. {
  133. if (e.Response is HttpWebResponse)
  134. {
  135. HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
  136. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  137. {
  138. // We don't appear to be handling any other status codes, so log these feailures to that
  139. // people don't spend unnecessary hours hunting phantom bugs.
  140. m_log.DebugFormat(
  141. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  142. verb, requestUrl, httpResponse.StatusCode);
  143. }
  144. }
  145. }
  146. else
  147. {
  148. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
  149. }
  150. }
  151. catch (Exception e)
  152. {
  153. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
  154. }
  155. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  156. try
  157. {
  158. action(deserial);
  159. }
  160. catch (Exception e)
  161. {
  162. m_log.ErrorFormat(
  163. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
  164. }
  165. }, null);
  166. }
  167. }
  168. }