RestClient.cs 16 KB

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