WebUtil.cs 44 KB

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