WebUtil.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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.Collections;
  29. using System.Collections.Generic;
  30. using System.Collections.Specialized;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.Net;
  34. using System.Net.Security;
  35. using System.Reflection;
  36. using System.Text;
  37. using System.Web;
  38. using System.Xml;
  39. using System.Xml.Serialization;
  40. using log4net;
  41. using OpenSim.Framework.Servers.HttpServer;
  42. using OpenMetaverse.StructuredData;
  43. namespace OpenSim.Framework
  44. {
  45. /// <summary>
  46. /// Miscellaneous static methods and extension methods related to the web
  47. /// </summary>
  48. public static class WebUtil
  49. {
  50. private static readonly ILog m_log =
  51. LogManager.GetLogger(
  52. MethodBase.GetCurrentMethod().DeclaringType);
  53. private static int m_requestNumber = 0;
  54. // this is the header field used to communicate the local request id
  55. // used for performance and debugging
  56. public const string OSHeaderRequestID = "opensim-request-id";
  57. // number of milliseconds a call can take before it is considered
  58. // a "long" call for warning & debugging purposes
  59. public const int LongCallTime = 500;
  60. /// <summary>
  61. /// Send LLSD to an HTTP client in application/llsd+json form
  62. /// </summary>
  63. /// <param name="response">HTTP response to send the data in</param>
  64. /// <param name="body">LLSD to send to the client</param>
  65. public static void SendJSONResponse(OSHttpResponse response, OSDMap body)
  66. {
  67. byte[] responseData = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(body));
  68. response.ContentEncoding = Encoding.UTF8;
  69. response.ContentLength = responseData.Length;
  70. response.ContentType = "application/llsd+json";
  71. response.Body.Write(responseData, 0, responseData.Length);
  72. }
  73. /// <summary>
  74. /// Send LLSD to an HTTP client in application/llsd+xml form
  75. /// </summary>
  76. /// <param name="response">HTTP response to send the data in</param>
  77. /// <param name="body">LLSD to send to the client</param>
  78. public static void SendXMLResponse(OSHttpResponse response, OSDMap body)
  79. {
  80. byte[] responseData = OSDParser.SerializeLLSDXmlBytes(body);
  81. response.ContentEncoding = Encoding.UTF8;
  82. response.ContentLength = responseData.Length;
  83. response.ContentType = "application/llsd+xml";
  84. response.Body.Write(responseData, 0, responseData.Length);
  85. }
  86. /// <summary>
  87. /// Make a GET or GET-like request to a web service that returns LLSD
  88. /// or JSON data
  89. /// </summary>
  90. public static OSDMap ServiceRequest(string url, string httpVerb)
  91. {
  92. string errorMessage;
  93. try
  94. {
  95. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  96. request.Method = httpVerb;
  97. using (WebResponse response = request.GetResponse())
  98. {
  99. using (Stream responseStream = response.GetResponseStream())
  100. {
  101. try
  102. {
  103. string responseStr = responseStream.GetStreamString();
  104. OSD responseOSD = OSDParser.Deserialize(responseStr);
  105. if (responseOSD.Type == OSDType.Map)
  106. return (OSDMap)responseOSD;
  107. else
  108. errorMessage = "Response format was invalid.";
  109. }
  110. catch
  111. {
  112. errorMessage = "Failed to parse the response.";
  113. }
  114. }
  115. }
  116. }
  117. catch (Exception ex)
  118. {
  119. m_log.Warn(httpVerb + " on URL " + url + " failed: " + ex.Message);
  120. errorMessage = ex.Message;
  121. }
  122. return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } };
  123. }
  124. /// <summary>
  125. /// PUT JSON-encoded data to a web service that returns LLSD or
  126. /// JSON data
  127. /// </summary>
  128. public static OSDMap PutToService(string url, OSDMap data)
  129. {
  130. return ServiceOSDRequest(url,data,"PUT",10000);
  131. }
  132. public static OSDMap PostToService(string url, OSDMap data)
  133. {
  134. return ServiceOSDRequest(url,data,"POST",10000);
  135. }
  136. public static OSDMap GetFromService(string url)
  137. {
  138. return ServiceOSDRequest(url,null,"GET",10000);
  139. }
  140. public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout)
  141. {
  142. int reqnum = m_requestNumber++;
  143. // m_log.DebugFormat("[WEB UTIL]: <{0}> start osd request for {1}, method {2}",reqnum,url,method);
  144. string errorMessage = "unknown error";
  145. int tickstart = Util.EnvironmentTickCount();
  146. int tickdata = 0;
  147. try
  148. {
  149. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  150. request.Method = method;
  151. request.Timeout = timeout;
  152. request.KeepAlive = false;
  153. request.MaximumAutomaticRedirections = 10;
  154. request.ReadWriteTimeout = timeout / 4;
  155. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  156. // If there is some input, write it into the request
  157. if (data != null)
  158. {
  159. string strBuffer = OSDParser.SerializeJsonString(data);
  160. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer);
  161. request.ContentType = "application/json";
  162. request.ContentLength = buffer.Length; //Count bytes to send
  163. using (Stream requestStream = request.GetRequestStream())
  164. requestStream.Write(buffer, 0, buffer.Length); //Send it
  165. }
  166. // capture how much time was spent writing, this may seem silly
  167. // but with the number concurrent requests, this often blocks
  168. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  169. using (WebResponse response = request.GetResponse())
  170. {
  171. using (Stream responseStream = response.GetResponseStream())
  172. {
  173. string responseStr = null;
  174. responseStr = responseStream.GetStreamString();
  175. // m_log.DebugFormat("[WEB UTIL]: <{0}> response is <{1}>",reqnum,responseStr);
  176. return CanonicalizeResults(responseStr);
  177. }
  178. }
  179. }
  180. catch (WebException we)
  181. {
  182. errorMessage = we.Message;
  183. if (we.Status == WebExceptionStatus.ProtocolError)
  184. {
  185. HttpWebResponse webResponse = (HttpWebResponse)we.Response;
  186. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. errorMessage = ex.Message;
  192. }
  193. finally
  194. {
  195. // This just dumps a warning for any operation that takes more than 100 ms
  196. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  197. if (tickdiff > LongCallTime)
  198. m_log.InfoFormat("[WEB UTIL]: osd request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing",
  199. reqnum,url,method,tickdiff,tickdata);
  200. }
  201. m_log.WarnFormat("[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage);
  202. return ErrorResponseMap(errorMessage);
  203. }
  204. /// <summary>
  205. /// Since there are no consistencies in the way web requests are
  206. /// formed, we need to do a little guessing about the result format.
  207. /// Keys:
  208. /// Success|success == the success fail of the request
  209. /// _RawResult == the raw string that came back
  210. /// _Result == the OSD unpacked string
  211. /// </summary>
  212. private static OSDMap CanonicalizeResults(string response)
  213. {
  214. OSDMap result = new OSDMap();
  215. // Default values
  216. result["Success"] = OSD.FromBoolean(true);
  217. result["success"] = OSD.FromBoolean(true);
  218. result["_RawResult"] = OSD.FromString(response);
  219. result["_Result"] = new OSDMap();
  220. if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase))
  221. return result;
  222. if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase))
  223. {
  224. result["Success"] = OSD.FromBoolean(false);
  225. result["success"] = OSD.FromBoolean(false);
  226. return result;
  227. }
  228. try
  229. {
  230. OSD responseOSD = OSDParser.Deserialize(response);
  231. if (responseOSD.Type == OSDType.Map)
  232. {
  233. result["_Result"] = (OSDMap)responseOSD;
  234. return result;
  235. }
  236. }
  237. catch (Exception e)
  238. {
  239. // don't need to treat this as an error... we're just guessing anyway
  240. m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message);
  241. }
  242. return result;
  243. }
  244. /// <summary>
  245. /// POST URL-encoded form data to a web service that returns LLSD or
  246. /// JSON data
  247. /// </summary>
  248. public static OSDMap PostToService(string url, NameValueCollection data)
  249. {
  250. return ServiceFormRequest(url,data,10000);
  251. }
  252. public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
  253. {
  254. int reqnum = m_requestNumber++;
  255. string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
  256. // m_log.DebugFormat("[WEB UTIL]: <{0}> start form request for {1}, method {2}",reqnum,url,method);
  257. string errorMessage = "unknown error";
  258. int tickstart = Util.EnvironmentTickCount();
  259. int tickdata = 0;
  260. try
  261. {
  262. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  263. request.Method = "POST";
  264. request.Timeout = timeout;
  265. request.KeepAlive = false;
  266. request.MaximumAutomaticRedirections = 10;
  267. request.ReadWriteTimeout = timeout / 4;
  268. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  269. if (data != null)
  270. {
  271. string queryString = BuildQueryString(data);
  272. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
  273. request.ContentLength = buffer.Length;
  274. request.ContentType = "application/x-www-form-urlencoded";
  275. using (Stream requestStream = request.GetRequestStream())
  276. requestStream.Write(buffer, 0, buffer.Length);
  277. }
  278. // capture how much time was spent writing, this may seem silly
  279. // but with the number concurrent requests, this often blocks
  280. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  281. using (WebResponse response = request.GetResponse())
  282. {
  283. using (Stream responseStream = response.GetResponseStream())
  284. {
  285. string responseStr = null;
  286. responseStr = responseStream.GetStreamString();
  287. OSD responseOSD = OSDParser.Deserialize(responseStr);
  288. if (responseOSD.Type == OSDType.Map)
  289. return (OSDMap)responseOSD;
  290. }
  291. }
  292. }
  293. catch (WebException we)
  294. {
  295. errorMessage = we.Message;
  296. if (we.Status == WebExceptionStatus.ProtocolError)
  297. {
  298. HttpWebResponse webResponse = (HttpWebResponse)we.Response;
  299. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  300. }
  301. }
  302. catch (Exception ex)
  303. {
  304. errorMessage = ex.Message;
  305. }
  306. finally
  307. {
  308. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  309. if (tickdiff > LongCallTime)
  310. m_log.InfoFormat("[WEB UTIL]: form request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing",
  311. reqnum,url,method,tickdiff,tickdata);
  312. }
  313. m_log.WarnFormat("[WEB UTIL]: <{0}> form request failed: {1}",reqnum,errorMessage);
  314. return ErrorResponseMap(errorMessage);
  315. }
  316. /// <summary>
  317. /// Create a response map for an error, trying to keep
  318. /// the result formats consistent
  319. /// </summary>
  320. private static OSDMap ErrorResponseMap(string msg)
  321. {
  322. OSDMap result = new OSDMap();
  323. result["Success"] = "False";
  324. result["Message"] = OSD.FromString("Service request failed: " + msg);
  325. return result;
  326. }
  327. #region Uri
  328. /// <summary>
  329. /// Combines a Uri that can contain both a base Uri and relative path
  330. /// with a second relative path fragment
  331. /// </summary>
  332. /// <param name="uri">Starting (base) Uri</param>
  333. /// <param name="fragment">Relative path fragment to append to the end
  334. /// of the Uri</param>
  335. /// <returns>The combined Uri</returns>
  336. /// <remarks>This is similar to the Uri constructor that takes a base
  337. /// Uri and the relative path, except this method can append a relative
  338. /// path fragment on to an existing relative path</remarks>
  339. public static Uri Combine(this Uri uri, string fragment)
  340. {
  341. string fragment1 = uri.Fragment;
  342. string fragment2 = fragment;
  343. if (!fragment1.EndsWith("/"))
  344. fragment1 = fragment1 + '/';
  345. if (fragment2.StartsWith("/"))
  346. fragment2 = fragment2.Substring(1);
  347. return new Uri(uri, fragment1 + fragment2);
  348. }
  349. /// <summary>
  350. /// Combines a Uri that can contain both a base Uri and relative path
  351. /// with a second relative path fragment. If the fragment is absolute,
  352. /// it will be returned without modification
  353. /// </summary>
  354. /// <param name="uri">Starting (base) Uri</param>
  355. /// <param name="fragment">Relative path fragment to append to the end
  356. /// of the Uri, or an absolute Uri to return unmodified</param>
  357. /// <returns>The combined Uri</returns>
  358. public static Uri Combine(this Uri uri, Uri fragment)
  359. {
  360. if (fragment.IsAbsoluteUri)
  361. return fragment;
  362. string fragment1 = uri.Fragment;
  363. string fragment2 = fragment.ToString();
  364. if (!fragment1.EndsWith("/"))
  365. fragment1 = fragment1 + '/';
  366. if (fragment2.StartsWith("/"))
  367. fragment2 = fragment2.Substring(1);
  368. return new Uri(uri, fragment1 + fragment2);
  369. }
  370. /// <summary>
  371. /// Appends a query string to a Uri that may or may not have existing
  372. /// query parameters
  373. /// </summary>
  374. /// <param name="uri">Uri to append the query to</param>
  375. /// <param name="query">Query string to append. Can either start with ?
  376. /// or just containg key/value pairs</param>
  377. /// <returns>String representation of the Uri with the query string
  378. /// appended</returns>
  379. public static string AppendQuery(this Uri uri, string query)
  380. {
  381. if (String.IsNullOrEmpty(query))
  382. return uri.ToString();
  383. if (query[0] == '?' || query[0] == '&')
  384. query = query.Substring(1);
  385. string uriStr = uri.ToString();
  386. if (uriStr.Contains("?"))
  387. return uriStr + '&' + query;
  388. else
  389. return uriStr + '?' + query;
  390. }
  391. #endregion Uri
  392. #region NameValueCollection
  393. /// <summary>
  394. /// Convert a NameValueCollection into a query string. This is the
  395. /// inverse of HttpUtility.ParseQueryString()
  396. /// </summary>
  397. /// <param name="parameters">Collection of key/value pairs to convert</param>
  398. /// <returns>A query string with URL-escaped values</returns>
  399. public static string BuildQueryString(NameValueCollection parameters)
  400. {
  401. List<string> items = new List<string>(parameters.Count);
  402. foreach (string key in parameters.Keys)
  403. {
  404. string[] values = parameters.GetValues(key);
  405. if (values != null)
  406. {
  407. foreach (string value in values)
  408. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  409. }
  410. }
  411. return String.Join("&", items.ToArray());
  412. }
  413. /// <summary>
  414. ///
  415. /// </summary>
  416. /// <param name="collection"></param>
  417. /// <param name="key"></param>
  418. /// <returns></returns>
  419. public static string GetOne(this NameValueCollection collection, string key)
  420. {
  421. string[] values = collection.GetValues(key);
  422. if (values != null && values.Length > 0)
  423. return values[0];
  424. return null;
  425. }
  426. #endregion NameValueCollection
  427. #region Stream
  428. /// <summary>
  429. /// Copies the contents of one stream to another, starting at the
  430. /// current position of each stream
  431. /// </summary>
  432. /// <param name="copyFrom">The stream to copy from, at the position
  433. /// where copying should begin</param>
  434. /// <param name="copyTo">The stream to copy to, at the position where
  435. /// bytes should be written</param>
  436. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  437. /// <returns>The total number of bytes copied</returns>
  438. /// <remarks>
  439. /// Copying begins at the streams' current positions. The positions are
  440. /// NOT reset after copying is complete.
  441. /// </remarks>
  442. public static int CopyTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  443. {
  444. byte[] buffer = new byte[4096];
  445. int readBytes;
  446. int totalCopiedBytes = 0;
  447. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  448. {
  449. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  450. copyTo.Write(buffer, 0, writeBytes);
  451. totalCopiedBytes += writeBytes;
  452. maximumBytesToCopy -= writeBytes;
  453. }
  454. return totalCopiedBytes;
  455. }
  456. /// <summary>
  457. /// Converts an entire stream to a string, regardless of current stream
  458. /// position
  459. /// </summary>
  460. /// <param name="stream">The stream to convert to a string</param>
  461. /// <returns></returns>
  462. /// <remarks>When this method is done, the stream position will be
  463. /// reset to its previous position before this method was called</remarks>
  464. public static string GetStreamString(this Stream stream)
  465. {
  466. string value = null;
  467. if (stream != null && stream.CanRead)
  468. {
  469. long rewindPos = -1;
  470. if (stream.CanSeek)
  471. {
  472. rewindPos = stream.Position;
  473. stream.Seek(0, SeekOrigin.Begin);
  474. }
  475. StreamReader reader = new StreamReader(stream);
  476. value = reader.ReadToEnd();
  477. if (rewindPos >= 0)
  478. stream.Seek(rewindPos, SeekOrigin.Begin);
  479. }
  480. return value;
  481. }
  482. #endregion Stream
  483. public class QBasedComparer : IComparer
  484. {
  485. public int Compare(Object x, Object y)
  486. {
  487. float qx = GetQ(x);
  488. float qy = GetQ(y);
  489. return qy.CompareTo(qx); // descending order
  490. }
  491. private float GetQ(Object o)
  492. {
  493. // Example: image/png;q=0.9
  494. float qvalue = 1F;
  495. if (o is String)
  496. {
  497. string mime = (string)o;
  498. string[] parts = mime.Split(';');
  499. if (parts.Length > 1)
  500. {
  501. string[] kvp = parts[1].Split('=');
  502. if (kvp.Length == 2 && kvp[0] == "q")
  503. float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue);
  504. }
  505. }
  506. return qvalue;
  507. }
  508. }
  509. /// <summary>
  510. /// Takes the value of an Accept header and returns the preferred types
  511. /// ordered by q value (if it exists).
  512. /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
  513. /// Exmaple output: ["jp2", "png", "jpg"]
  514. /// NOTE: This doesn't handle the semantics of *'s...
  515. /// </summary>
  516. /// <param name="accept"></param>
  517. /// <returns></returns>
  518. public static string[] GetPreferredImageTypes(string accept)
  519. {
  520. if (accept == null || accept == string.Empty)
  521. return new string[0];
  522. string[] types = accept.Split(new char[] { ',' });
  523. if (types.Length > 0)
  524. {
  525. List<string> list = new List<string>(types);
  526. list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
  527. ArrayList tlist = new ArrayList(list);
  528. tlist.Sort(new QBasedComparer());
  529. string[] result = new string[tlist.Count];
  530. for (int i = 0; i < tlist.Count; i++)
  531. {
  532. string mime = (string)tlist[i];
  533. string[] parts = mime.Split(new char[] { ';' });
  534. string[] pair = parts[0].Split(new char[] { '/' });
  535. if (pair.Length == 2)
  536. result[i] = pair[1].ToLower();
  537. else // oops, we don't know what this is...
  538. result[i] = pair[0];
  539. }
  540. return result;
  541. }
  542. return new string[0];
  543. }
  544. }
  545. public static class AsynchronousRestObjectRequester
  546. {
  547. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  548. /// <summary>
  549. /// Perform an asynchronous REST request.
  550. /// </summary>
  551. /// <param name="verb">GET or POST</param>
  552. /// <param name="requestUrl"></param>
  553. /// <param name="obj"></param>
  554. /// <param name="action"></param>
  555. /// <returns></returns>
  556. ///
  557. /// <exception cref="System.Net.WebException">Thrown if we encounter a
  558. /// network issue while posting the request. You'll want to make
  559. /// sure you deal with this as they're not uncommon</exception>
  560. //
  561. public static void MakeRequest<TRequest, TResponse>(string verb,
  562. string requestUrl, TRequest obj, Action<TResponse> action)
  563. {
  564. // m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
  565. Type type = typeof(TRequest);
  566. WebRequest request = WebRequest.Create(requestUrl);
  567. WebResponse response = null;
  568. TResponse deserial = default(TResponse);
  569. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  570. request.Method = verb;
  571. if (verb == "POST")
  572. {
  573. request.ContentType = "text/xml";
  574. MemoryStream buffer = new MemoryStream();
  575. XmlWriterSettings settings = new XmlWriterSettings();
  576. settings.Encoding = Encoding.UTF8;
  577. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  578. {
  579. XmlSerializer serializer = new XmlSerializer(type);
  580. serializer.Serialize(writer, obj);
  581. writer.Flush();
  582. }
  583. int length = (int)buffer.Length;
  584. request.ContentLength = length;
  585. request.BeginGetRequestStream(delegate(IAsyncResult res)
  586. {
  587. Stream requestStream = request.EndGetRequestStream(res);
  588. requestStream.Write(buffer.ToArray(), 0, length);
  589. requestStream.Close();
  590. request.BeginGetResponse(delegate(IAsyncResult ar)
  591. {
  592. response = request.EndGetResponse(ar);
  593. Stream respStream = null;
  594. try
  595. {
  596. respStream = response.GetResponseStream();
  597. deserial = (TResponse)deserializer.Deserialize(
  598. respStream);
  599. }
  600. catch (System.InvalidOperationException)
  601. {
  602. }
  603. finally
  604. {
  605. // Let's not close this
  606. //buffer.Close();
  607. respStream.Close();
  608. response.Close();
  609. }
  610. action(deserial);
  611. }, null);
  612. }, null);
  613. return;
  614. }
  615. request.BeginGetResponse(delegate(IAsyncResult res2)
  616. {
  617. try
  618. {
  619. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  620. // documented in MSDN
  621. response = request.EndGetResponse(res2);
  622. Stream respStream = null;
  623. try
  624. {
  625. respStream = response.GetResponseStream();
  626. deserial = (TResponse)deserializer.Deserialize(respStream);
  627. }
  628. catch (System.InvalidOperationException)
  629. {
  630. }
  631. finally
  632. {
  633. respStream.Close();
  634. response.Close();
  635. }
  636. }
  637. catch (WebException e)
  638. {
  639. if (e.Status == WebExceptionStatus.ProtocolError)
  640. {
  641. if (e.Response is HttpWebResponse)
  642. {
  643. HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
  644. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  645. {
  646. // We don't appear to be handling any other status codes, so log these feailures to that
  647. // people don't spend unnecessary hours hunting phantom bugs.
  648. m_log.DebugFormat(
  649. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  650. verb, requestUrl, httpResponse.StatusCode);
  651. }
  652. }
  653. }
  654. else
  655. {
  656. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
  657. }
  658. }
  659. catch (Exception e)
  660. {
  661. m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
  662. }
  663. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  664. try
  665. {
  666. action(deserial);
  667. }
  668. catch (Exception e)
  669. {
  670. m_log.ErrorFormat(
  671. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
  672. }
  673. }, null);
  674. }
  675. }
  676. public static class SynchronousRestFormsRequester
  677. {
  678. private static readonly ILog m_log =
  679. LogManager.GetLogger(
  680. MethodBase.GetCurrentMethod().DeclaringType);
  681. /// <summary>
  682. /// Perform a synchronous REST request.
  683. /// </summary>
  684. /// <param name="verb"></param>
  685. /// <param name="requestUrl"></param>
  686. /// <param name="obj"> </param>
  687. /// <returns></returns>
  688. ///
  689. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  690. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  691. public static string MakeRequest(string verb, string requestUrl, string obj)
  692. {
  693. WebRequest request = WebRequest.Create(requestUrl);
  694. request.Method = verb;
  695. string respstring = String.Empty;
  696. using (MemoryStream buffer = new MemoryStream())
  697. {
  698. if ((verb == "POST") || (verb == "PUT"))
  699. {
  700. request.ContentType = "text/www-form-urlencoded";
  701. int length = 0;
  702. using (StreamWriter writer = new StreamWriter(buffer))
  703. {
  704. writer.Write(obj);
  705. writer.Flush();
  706. }
  707. length = (int)obj.Length;
  708. request.ContentLength = length;
  709. Stream requestStream = null;
  710. try
  711. {
  712. requestStream = request.GetRequestStream();
  713. requestStream.Write(buffer.ToArray(), 0, length);
  714. }
  715. catch (Exception e)
  716. {
  717. m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl);
  718. }
  719. finally
  720. {
  721. if (requestStream != null)
  722. requestStream.Close();
  723. }
  724. }
  725. try
  726. {
  727. using (WebResponse resp = request.GetResponse())
  728. {
  729. if (resp.ContentLength != 0)
  730. {
  731. Stream respStream = null;
  732. try
  733. {
  734. respStream = resp.GetResponseStream();
  735. using (StreamReader reader = new StreamReader(respStream))
  736. {
  737. respstring = reader.ReadToEnd();
  738. }
  739. }
  740. catch (Exception e)
  741. {
  742. m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString());
  743. }
  744. finally
  745. {
  746. if (respStream != null)
  747. respStream.Close();
  748. }
  749. }
  750. }
  751. }
  752. catch (System.InvalidOperationException)
  753. {
  754. // This is what happens when there is invalid XML
  755. m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request");
  756. }
  757. }
  758. return respstring;
  759. }
  760. }
  761. public class SynchronousRestObjectPoster
  762. {
  763. [Obsolete]
  764. public static TResponse BeginPostObject<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
  765. {
  766. return SynchronousRestObjectRequester.MakeRequest<TRequest, TResponse>(verb, requestUrl, obj);
  767. }
  768. }
  769. public class SynchronousRestObjectRequester
  770. {
  771. /// <summary>
  772. /// Perform a synchronous REST request.
  773. /// </summary>
  774. /// <param name="verb"></param>
  775. /// <param name="requestUrl"></param>
  776. /// <param name="obj"> </param>
  777. /// <returns></returns>
  778. ///
  779. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  780. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  781. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
  782. {
  783. Type type = typeof(TRequest);
  784. TResponse deserial = default(TResponse);
  785. WebRequest request = WebRequest.Create(requestUrl);
  786. request.Method = verb;
  787. if ((verb == "POST") || (verb == "PUT"))
  788. {
  789. request.ContentType = "text/xml";
  790. MemoryStream buffer = new MemoryStream();
  791. XmlWriterSettings settings = new XmlWriterSettings();
  792. settings.Encoding = Encoding.UTF8;
  793. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  794. {
  795. XmlSerializer serializer = new XmlSerializer(type);
  796. serializer.Serialize(writer, obj);
  797. writer.Flush();
  798. }
  799. int length = (int)buffer.Length;
  800. request.ContentLength = length;
  801. Stream requestStream = null;
  802. try
  803. {
  804. requestStream = request.GetRequestStream();
  805. requestStream.Write(buffer.ToArray(), 0, length);
  806. }
  807. catch (Exception)
  808. {
  809. return deserial;
  810. }
  811. finally
  812. {
  813. if (requestStream != null)
  814. requestStream.Close();
  815. }
  816. }
  817. try
  818. {
  819. using (WebResponse resp = request.GetResponse())
  820. {
  821. if (resp.ContentLength > 0)
  822. {
  823. Stream respStream = resp.GetResponseStream();
  824. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  825. deserial = (TResponse)deserializer.Deserialize(respStream);
  826. respStream.Close();
  827. }
  828. }
  829. }
  830. catch (System.InvalidOperationException)
  831. {
  832. // This is what happens when there is invalid XML
  833. }
  834. return deserial;
  835. }
  836. }
  837. }