AsynchronousRestObjectRequester.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. request.BeginGetResponse(delegate(IAsyncResult ar)
  82. {
  83. response = request.EndGetResponse(ar);
  84. try
  85. {
  86. deserial = (TResponse) deserializer.Deserialize(
  87. response.GetResponseStream());
  88. }
  89. catch (System.InvalidOperationException)
  90. {
  91. }
  92. action(deserial);
  93. }, null);
  94. }, null);
  95. return;
  96. }
  97. request.BeginGetResponse(delegate(IAsyncResult res2)
  98. {
  99. try
  100. {
  101. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  102. // documented in MSDN
  103. response = request.EndGetResponse(res2);
  104. try
  105. {
  106. deserial = (TResponse)deserializer.Deserialize(response.GetResponseStream());
  107. }
  108. catch (System.InvalidOperationException)
  109. {
  110. }
  111. }
  112. catch (WebException e)
  113. {
  114. if (e.Status == WebExceptionStatus.ProtocolError)
  115. {
  116. if (e.Response is HttpWebResponse)
  117. {
  118. HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
  119. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  120. {
  121. // We don't appear to be handling any other status codes, so log these feailures to that
  122. // people don't spend unnecessary hours hunting phantom bugs.
  123. m_log.DebugFormat(
  124. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  125. verb, requestUrl, httpResponse.StatusCode);
  126. }
  127. }
  128. }
  129. else
  130. {
  131. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
  132. }
  133. }
  134. catch (Exception e)
  135. {
  136. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
  137. }
  138. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  139. try
  140. {
  141. action(deserial);
  142. }
  143. catch (Exception e)
  144. {
  145. m_log.ErrorFormat(
  146. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
  147. }
  148. }, null);
  149. }
  150. }
  151. }