RestClient.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Web;
  9. using log4net;
  10. namespace OpenSim.Framework.Communications
  11. {
  12. /// <summary>
  13. /// Implementation of a generic REST client
  14. /// </summary>
  15. /// <remarks>
  16. /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
  17. /// class is designed to execute both synchroneously and asynchroneously.
  18. ///
  19. /// Internally the implementation works as a two stage asynchroneous web-client.
  20. /// When the request is initiated, RestClient will query asynchroneously for for a web-response,
  21. /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
  22. /// the second stage of asynchroneous requests will be triggered, in an attempt to read of the response
  23. /// object into a memorystream as a sequence of asynchroneous reads.
  24. ///
  25. /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
  26. /// other threads to execute, while it waits for a response from the web-service. RestClient it self, can be
  27. /// invoked by the caller in either synchroneous mode or asynchroneous mode.
  28. /// </remarks>
  29. public class RestClient
  30. {
  31. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  32. private string realuri;
  33. #region member variables
  34. /// <summary>
  35. /// The base Uri of the web-service e.g. http://www.google.com
  36. /// </summary>
  37. private string _url;
  38. /// <summary>
  39. /// Path elements of the query
  40. /// </summary>
  41. private List<string> _pathElements = new List<string>();
  42. /// <summary>
  43. /// Parameter elements of the query, e.g. min=34
  44. /// </summary>
  45. private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
  46. /// <summary>
  47. /// Request method. E.g. GET, POST, PUT or DELETE
  48. /// </summary>
  49. private string _method;
  50. /// <summary>
  51. /// Temporary buffer used to store bytes temporarily as they come in from the server
  52. /// </summary>
  53. private byte[] _readbuf;
  54. /// <summary>
  55. /// MemoryStream representing the resultiong resource
  56. /// </summary>
  57. private Stream _resource;
  58. /// <summary>
  59. /// WebRequest object, held as a member variable
  60. /// </summary>
  61. private HttpWebRequest _request;
  62. /// <summary>
  63. /// WebResponse object, held as a member variable, so we can close it
  64. /// </summary>
  65. private HttpWebResponse _response;
  66. /// <summary>
  67. /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
  68. /// </summary>
  69. public static ManualResetEvent _allDone = new ManualResetEvent(false);
  70. /// <summary>
  71. /// Default time out period
  72. /// </summary>
  73. private const int DefaultTimeout = 10*1000; // 10 seconds timeout
  74. /// <summary>
  75. /// Default Buffer size of a block requested from the web-server
  76. /// </summary>
  77. private const int BufferSize = 4096; // Read blocks of 4 KB.
  78. /// <summary>
  79. /// if an exception occours during async processing, we need to save it, so it can be
  80. /// rethrown on the primary thread;
  81. /// </summary>
  82. private Exception _asyncException;
  83. #endregion member variables
  84. #region constructors
  85. /// <summary>
  86. /// Instantiate a new RestClient
  87. /// </summary>
  88. /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
  89. public RestClient(string url)
  90. {
  91. _url = url;
  92. _readbuf = new byte[BufferSize];
  93. _resource = new MemoryStream();
  94. _request = null;
  95. _response = null;
  96. _lock = new object();
  97. }
  98. private object _lock;
  99. #endregion constructors
  100. /// <summary>
  101. /// Add a path element to the query, e.g. assets
  102. /// </summary>
  103. /// <param name="element">path entry</param>
  104. public void AddResourcePath(string element)
  105. {
  106. if (isSlashed(element))
  107. _pathElements.Add(element.Substring(0, element.Length - 1));
  108. else
  109. _pathElements.Add(element);
  110. }
  111. /// <summary>
  112. /// Add a query parameter to the Url
  113. /// </summary>
  114. /// <param name="name">Name of the parameter, e.g. min</param>
  115. /// <param name="value">Value of the parameter, e.g. 42</param>
  116. public void AddQueryParameter(string name, string value)
  117. {
  118. _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
  119. }
  120. /// <summary>
  121. /// Add a query parameter to the Url
  122. /// </summary>
  123. /// <param name="name">Name of the parameter, e.g. min</param>
  124. public void AddQueryParameter(string name)
  125. {
  126. _parameterElements.Add(HttpUtility.UrlEncode(name), null);
  127. }
  128. /// <summary>
  129. /// Web-Request method, e.g. GET, PUT, POST, DELETE
  130. /// </summary>
  131. public string RequestMethod
  132. {
  133. get { return _method; }
  134. set { _method = value; }
  135. }
  136. /// <summary>
  137. /// True if string contains a trailing slash '/'
  138. /// </summary>
  139. /// <param name="s">string to be examined</param>
  140. /// <returns>true if slash is present</returns>
  141. private static bool isSlashed(string s)
  142. {
  143. return s.Substring(s.Length - 1, 1) == "/";
  144. }
  145. /// <summary>
  146. /// Build a Uri based on the initial Url, path elements and parameters
  147. /// </summary>
  148. /// <returns>fully constructed Uri</returns>
  149. private Uri buildUri()
  150. {
  151. StringBuilder sb = new StringBuilder();
  152. sb.Append(_url);
  153. foreach (string e in _pathElements)
  154. {
  155. sb.Append("/");
  156. sb.Append(e);
  157. }
  158. bool firstElement = true;
  159. foreach (KeyValuePair<string, string> kv in _parameterElements)
  160. {
  161. if (firstElement)
  162. {
  163. sb.Append("?");
  164. firstElement = false;
  165. }
  166. else
  167. sb.Append("&");
  168. sb.Append(kv.Key);
  169. if (!string.IsNullOrEmpty(kv.Value))
  170. {
  171. sb.Append("=");
  172. sb.Append(kv.Value);
  173. }
  174. }
  175. realuri = sb.ToString();
  176. //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
  177. return new Uri(sb.ToString());
  178. }
  179. #region Async communications with server
  180. /// <summary>
  181. /// Async method, invoked when a block of data has been received from the service
  182. /// </summary>
  183. /// <param name="ar"></param>
  184. private void StreamIsReadyDelegate(IAsyncResult ar)
  185. {
  186. try
  187. {
  188. Stream s = (Stream) ar.AsyncState;
  189. int read = s.EndRead(ar);
  190. if (read > 0)
  191. {
  192. _resource.Write(_readbuf, 0, read);
  193. IAsyncResult asynchronousResult =
  194. s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
  195. // TODO! Implement timeout, without killing the server
  196. //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
  197. }
  198. else
  199. {
  200. s.Close();
  201. _allDone.Set();
  202. }
  203. }
  204. catch (Exception e)
  205. {
  206. _allDone.Set();
  207. _asyncException = e;
  208. }
  209. }
  210. #endregion Async communications with server
  211. /// <summary>
  212. /// Perform synchroneous request
  213. /// </summary>
  214. public Stream Request()
  215. {
  216. lock (_lock)
  217. {
  218. _request = (HttpWebRequest) WebRequest.Create(buildUri());
  219. _request.KeepAlive = false;
  220. _request.ContentType = "application/xml";
  221. _request.Timeout = 200000;
  222. _asyncException = null;
  223. // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
  224. _response = (HttpWebResponse) _request.GetResponse();
  225. Stream src = _response.GetResponseStream();
  226. int length = src.Read(_readbuf, 0, BufferSize);
  227. while (length > 0)
  228. {
  229. _resource.Write(_readbuf, 0, length);
  230. length = src.Read(_readbuf, 0, BufferSize);
  231. }
  232. // TODO! Implement timeout, without killing the server
  233. // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
  234. //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
  235. // _allDone.WaitOne();
  236. if (_response != null)
  237. _response.Close();
  238. if (_asyncException != null)
  239. throw _asyncException;
  240. if (_resource != null)
  241. {
  242. _resource.Flush();
  243. _resource.Seek(0, SeekOrigin.Begin);
  244. }
  245. return _resource;
  246. }
  247. }
  248. public Stream Request(Stream src)
  249. {
  250. _request = (HttpWebRequest) WebRequest.Create(buildUri());
  251. _request.KeepAlive = false;
  252. _request.ContentType = "application/xml";
  253. _request.Timeout = 900000;
  254. _request.Method = RequestMethod;
  255. _asyncException = null;
  256. _request.ContentLength = src.Length;
  257. m_log.InfoFormat("[REST]: Request Length {0}", _request.ContentLength);
  258. m_log.InfoFormat("[REST]: Sending Web Request {0}", buildUri());
  259. src.Seek(0, SeekOrigin.Begin);
  260. m_log.Info("[REST]: Seek is ok");
  261. Stream dst = _request.GetRequestStream();
  262. m_log.Info("[REST]: GetRequestStream is ok");
  263. byte[] buf = new byte[1024];
  264. int length = src.Read(buf, 0, 1024);
  265. m_log.Info("[REST]: First Read is ok");
  266. while (length > 0)
  267. {
  268. dst.Write(buf, 0, length);
  269. length = src.Read(buf, 0, 1024);
  270. }
  271. _response = (HttpWebResponse) _request.GetResponse();
  272. // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
  273. // TODO! Implement timeout, without killing the server
  274. // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
  275. //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
  276. return null;
  277. }
  278. #region Async Invocation
  279. public IAsyncResult BeginRequest(AsyncCallback callback, object state)
  280. {
  281. /// <summary>
  282. /// In case, we are invoked asynchroneously this object will keep track of the state
  283. /// </summary>
  284. AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
  285. ThreadPool.QueueUserWorkItem(RequestHelper, ar);
  286. return ar;
  287. }
  288. public Stream EndRequest(IAsyncResult asyncResult)
  289. {
  290. AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
  291. // Wait for operation to complete, then return result or
  292. // throw exception
  293. return ar.EndInvoke();
  294. }
  295. private void RequestHelper(Object asyncResult)
  296. {
  297. // We know that it's really an AsyncResult<DateTime> object
  298. AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
  299. try
  300. {
  301. // Perform the operation; if sucessful set the result
  302. Stream s = Request();
  303. ar.SetAsCompleted(s, false);
  304. }
  305. catch (Exception e)
  306. {
  307. // If operation fails, set the exception
  308. ar.HandleException(e, false);
  309. }
  310. }
  311. #endregion Async Invocation
  312. }
  313. }