aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Framework
diff options
context:
space:
mode:
Diffstat (limited to 'OpenSim/Framework')
-rw-r--r--OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs192
-rw-r--r--OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs131
-rw-r--r--OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs137
-rw-r--r--OpenSim/Framework/WebUtil.cs346
4 files changed, 344 insertions, 462 deletions
diff --git a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs
deleted file mode 100644
index 03c12dd..0000000
--- a/OpenSim/Framework/Servers/HttpServer/AsynchronousRestObjectRequester.cs
+++ /dev/null
@@ -1,192 +0,0 @@
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
28using System;
29using System.IO;
30using System.Net;
31using System.Reflection;
32using System.Text;
33using System.Xml;
34using System.Xml.Serialization;
35using log4net;
36
37namespace OpenSim.Framework.Servers.HttpServer
38{
39 public class AsynchronousRestObjectRequester
40 {
41 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
42
43 /// <summary>
44 /// Perform an asynchronous REST request.
45 /// </summary>
46 /// <param name="verb">GET or POST</param>
47 /// <param name="requestUrl"></param>
48 /// <param name="obj"></param>
49 /// <param name="action"></param>
50 /// <returns></returns>
51 ///
52 /// <exception cref="System.Net.WebException">Thrown if we encounter a
53 /// network issue while posting the request. You'll want to make
54 /// sure you deal with this as they're not uncommon</exception>
55 //
56 public static void MakeRequest<TRequest, TResponse>(string verb,
57 string requestUrl, TRequest obj, Action<TResponse> action)
58 {
59// m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
60
61 Type type = typeof (TRequest);
62
63 WebRequest request = WebRequest.Create(requestUrl);
64 WebResponse response = null;
65 TResponse deserial = default(TResponse);
66 XmlSerializer deserializer = new XmlSerializer(typeof (TResponse));
67
68 request.Method = verb;
69
70 if (verb == "POST")
71 {
72 request.ContentType = "text/xml";
73
74 MemoryStream buffer = new MemoryStream();
75
76 XmlWriterSettings settings = new XmlWriterSettings();
77 settings.Encoding = Encoding.UTF8;
78
79 using (XmlWriter writer = XmlWriter.Create(buffer, settings))
80 {
81 XmlSerializer serializer = new XmlSerializer(type);
82 serializer.Serialize(writer, obj);
83 writer.Flush();
84 }
85
86 int length = (int) buffer.Length;
87 request.ContentLength = length;
88
89 request.BeginGetRequestStream(delegate(IAsyncResult res)
90 {
91 Stream requestStream = request.EndGetRequestStream(res);
92
93 requestStream.Write(buffer.ToArray(), 0, length);
94 requestStream.Close();
95
96 request.BeginGetResponse(delegate(IAsyncResult ar)
97 {
98 response = request.EndGetResponse(ar);
99 Stream respStream = null;
100 try
101 {
102 respStream = response.GetResponseStream();
103 deserial = (TResponse)deserializer.Deserialize(
104 respStream);
105 }
106 catch (System.InvalidOperationException)
107 {
108 }
109 finally
110 {
111 // Let's not close this
112 //buffer.Close();
113 respStream.Close();
114 response.Close();
115 }
116
117 action(deserial);
118
119 }, null);
120 }, null);
121
122
123 return;
124 }
125
126 request.BeginGetResponse(delegate(IAsyncResult res2)
127 {
128 try
129 {
130 // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
131 // documented in MSDN
132 response = request.EndGetResponse(res2);
133
134 Stream respStream = null;
135 try
136 {
137 respStream = response.GetResponseStream();
138 deserial = (TResponse)deserializer.Deserialize(respStream);
139 }
140 catch (System.InvalidOperationException)
141 {
142 }
143 finally
144 {
145 respStream.Close();
146 response.Close();
147 }
148 }
149 catch (WebException e)
150 {
151 if (e.Status == WebExceptionStatus.ProtocolError)
152 {
153 if (e.Response is HttpWebResponse)
154 {
155 HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
156
157 if (httpResponse.StatusCode != HttpStatusCode.NotFound)
158 {
159 // We don't appear to be handling any other status codes, so log these feailures to that
160 // people don't spend unnecessary hours hunting phantom bugs.
161 m_log.DebugFormat(
162 "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
163 verb, requestUrl, httpResponse.StatusCode);
164 }
165 }
166 }
167 else
168 {
169 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
170 }
171 }
172 catch (Exception e)
173 {
174 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
175 }
176
177 // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
178
179 try
180 {
181 action(deserial);
182 }
183 catch (Exception e)
184 {
185 m_log.ErrorFormat(
186 "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
187 }
188
189 }, null);
190 }
191 }
192}
diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs
deleted file mode 100644
index d5646d0..0000000
--- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestFormsRequester.cs
+++ /dev/null
@@ -1,131 +0,0 @@
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
28using System;
29using System.IO;
30using System.Net;
31using System.Reflection;
32using System.Text;
33using System.Xml;
34using System.Xml.Serialization;
35
36using log4net;
37
38namespace OpenSim.Framework.Servers.HttpServer
39{
40 public class SynchronousRestFormsRequester
41 {
42 private static readonly ILog m_log =
43 LogManager.GetLogger(
44 MethodBase.GetCurrentMethod().DeclaringType);
45
46 /// <summary>
47 /// Perform a synchronous REST request.
48 /// </summary>
49 /// <param name="verb"></param>
50 /// <param name="requestUrl"></param>
51 /// <param name="obj"> </param>
52 /// <returns></returns>
53 ///
54 /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
55 /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
56 public static string MakeRequest(string verb, string requestUrl, string obj)
57 {
58 WebRequest request = WebRequest.Create(requestUrl);
59 request.Method = verb;
60 string respstring = String.Empty;
61
62 using (MemoryStream buffer = new MemoryStream())
63 {
64 if ((verb == "POST") || (verb == "PUT"))
65 {
66 request.ContentType = "text/www-form-urlencoded";
67
68 int length = 0;
69 using (StreamWriter writer = new StreamWriter(buffer))
70 {
71 writer.Write(obj);
72 writer.Flush();
73 }
74
75 length = (int)obj.Length;
76 request.ContentLength = length;
77
78 Stream requestStream = null;
79 try
80 {
81 requestStream = request.GetRequestStream();
82 requestStream.Write(buffer.ToArray(), 0, length);
83 }
84 catch (Exception e)
85 {
86 m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: with {1} " + e.ToString(), requestUrl,obj);
87 }
88 finally
89 {
90 if (requestStream != null)
91 requestStream.Close();
92 }
93 }
94
95 try
96 {
97 using (WebResponse resp = request.GetResponse())
98 {
99 if (resp.ContentLength != 0)
100 {
101 Stream respStream = null;
102 try
103 {
104 respStream = resp.GetResponseStream();
105 using (StreamReader reader = new StreamReader(respStream))
106 {
107 respstring = reader.ReadToEnd();
108 }
109 }
110 catch (Exception e)
111 {
112 m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString());
113 }
114 finally
115 {
116 if (respStream != null)
117 respStream.Close();
118 }
119 }
120 }
121 }
122 catch (System.InvalidOperationException)
123 {
124 // This is what happens when there is invalid XML
125 m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request");
126 }
127 }
128 return respstring;
129 }
130 }
131}
diff --git a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs b/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs
deleted file mode 100644
index 077a1e8..0000000
--- a/OpenSim/Framework/Servers/HttpServer/SynchronousRestObjectRequester.cs
+++ /dev/null
@@ -1,137 +0,0 @@
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
28using System;
29using System.IO;
30using System.Net;
31using System.Text;
32using System.Xml;
33using System.Xml.Serialization;
34
35namespace OpenSim.Framework.Servers.HttpServer
36{
37 public class SynchronousRestObjectPoster
38 {
39 [Obsolete]
40 public static TResponse BeginPostObject<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
41 {
42 return SynchronousRestObjectRequester.MakeRequest<TRequest, TResponse>(verb, requestUrl, obj);
43 }
44 }
45
46 public class SynchronousRestObjectRequester
47 {
48 /// <summary>
49 /// Perform a synchronous REST request.
50 /// </summary>
51 /// <param name="verb"></param>
52 /// <param name="requestUrl"></param>
53 /// <param name="obj"> </param>
54 /// <returns></returns>
55 ///
56 /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
57 /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
58 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
59 {
60 return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 100);
61 }
62 /// <summary>
63 /// Perform a synchronous REST request.
64 /// </summary>
65 /// <param name="verb"></param>
66 /// <param name="requestUrl"></param>
67 /// <param name="obj"> </param>
68 /// <param name="timeout"> </param>
69 /// <returns></returns>
70 ///
71 /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
72 /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
73 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout)
74 {
75 Type type = typeof (TRequest);
76 TResponse deserial = default(TResponse);
77
78 WebRequest request = WebRequest.Create(requestUrl);
79 request.Method = verb;
80 request.Timeout = pTimeout * 1000;
81
82 if ((verb == "POST") || (verb == "PUT"))
83 {
84 request.ContentType = "text/xml";
85
86 MemoryStream buffer = new MemoryStream();
87
88 XmlWriterSettings settings = new XmlWriterSettings();
89 settings.Encoding = Encoding.UTF8;
90
91 using (XmlWriter writer = XmlWriter.Create(buffer, settings))
92 {
93 XmlSerializer serializer = new XmlSerializer(type);
94 serializer.Serialize(writer, obj);
95 writer.Flush();
96 }
97
98 int length = (int) buffer.Length;
99 request.ContentLength = length;
100 Stream requestStream = null;
101 try
102 {
103 requestStream = request.GetRequestStream();
104 requestStream.Write(buffer.ToArray(), 0, length);
105 }
106 catch (Exception)
107 {
108 return deserial;
109 }
110 finally
111 {
112 if (requestStream != null)
113 requestStream.Close();
114 }
115 }
116
117 try
118 {
119 using (WebResponse resp = request.GetResponse())
120 {
121 if (resp.ContentLength != 0)
122 {
123 Stream respStream = resp.GetResponseStream();
124 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
125 deserial = (TResponse)deserializer.Deserialize(respStream);
126 respStream.Close();
127 }
128 }
129 }
130 catch (System.InvalidOperationException)
131 {
132 // This is what happens when there is invalid XML
133 }
134 return deserial;
135 }
136 }
137}
diff --git a/OpenSim/Framework/WebUtil.cs b/OpenSim/Framework/WebUtil.cs
index f59c8f8..d04a3df 100644
--- a/OpenSim/Framework/WebUtil.cs
+++ b/OpenSim/Framework/WebUtil.cs
@@ -36,6 +36,9 @@ using System.Net.Security;
36using System.Reflection; 36using System.Reflection;
37using System.Text; 37using System.Text;
38using System.Web; 38using System.Web;
39using System.Xml;
40using System.Xml.Serialization;
41
39using log4net; 42using log4net;
40using OpenSim.Framework.Servers.HttpServer; 43using OpenSim.Framework.Servers.HttpServer;
41using OpenMetaverse.StructuredData; 44using OpenMetaverse.StructuredData;
@@ -224,8 +227,8 @@ namespace OpenSim.Framework
224 m_log.InfoFormat("[WEB UTIL]: osd request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing", 227 m_log.InfoFormat("[WEB UTIL]: osd request <{0}> (URI:{1}, METHOD:{2}) took {3}ms overall, {4}ms writing",
225 reqnum,url,method,tickdiff,tickdata); 228 reqnum,url,method,tickdiff,tickdata);
226 } 229 }
227 230
228 m_log.WarnFormat("[WEB UTIL] <{0}> osd request failed: {1}",reqnum,errorMessage); 231 m_log.WarnFormat("[WEB UTIL]: <{0}> osd request for {1}, method {2} FAILED: {3}", reqnum, url, method, errorMessage);
229 return ErrorResponseMap(errorMessage); 232 return ErrorResponseMap(errorMessage);
230 } 233 }
231 234
@@ -630,4 +633,343 @@ namespace OpenSim.Framework
630 633
631 634
632 } 635 }
636
637 public static class AsynchronousRestObjectRequester
638 {
639 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
640
641 /// <summary>
642 /// Perform an asynchronous REST request.
643 /// </summary>
644 /// <param name="verb">GET or POST</param>
645 /// <param name="requestUrl"></param>
646 /// <param name="obj"></param>
647 /// <param name="action"></param>
648 /// <returns></returns>
649 ///
650 /// <exception cref="System.Net.WebException">Thrown if we encounter a
651 /// network issue while posting the request. You'll want to make
652 /// sure you deal with this as they're not uncommon</exception>
653 //
654 public static void MakeRequest<TRequest, TResponse>(string verb,
655 string requestUrl, TRequest obj, Action<TResponse> action)
656 {
657 // m_log.DebugFormat("[ASYNC REQUEST]: Starting {0} {1}", verb, requestUrl);
658
659 Type type = typeof(TRequest);
660
661 WebRequest request = WebRequest.Create(requestUrl);
662 WebResponse response = null;
663 TResponse deserial = default(TResponse);
664 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
665
666 request.Method = verb;
667
668 if (verb == "POST")
669 {
670 request.ContentType = "text/xml";
671
672 MemoryStream buffer = new MemoryStream();
673
674 XmlWriterSettings settings = new XmlWriterSettings();
675 settings.Encoding = Encoding.UTF8;
676
677 using (XmlWriter writer = XmlWriter.Create(buffer, settings))
678 {
679 XmlSerializer serializer = new XmlSerializer(type);
680 serializer.Serialize(writer, obj);
681 writer.Flush();
682 }
683
684 int length = (int)buffer.Length;
685 request.ContentLength = length;
686
687 request.BeginGetRequestStream(delegate(IAsyncResult res)
688 {
689 Stream requestStream = request.EndGetRequestStream(res);
690
691 requestStream.Write(buffer.ToArray(), 0, length);
692 requestStream.Close();
693
694 request.BeginGetResponse(delegate(IAsyncResult ar)
695 {
696 response = request.EndGetResponse(ar);
697 Stream respStream = null;
698 try
699 {
700 respStream = response.GetResponseStream();
701 deserial = (TResponse)deserializer.Deserialize(
702 respStream);
703 }
704 catch (System.InvalidOperationException)
705 {
706 }
707 finally
708 {
709 // Let's not close this
710 //buffer.Close();
711 respStream.Close();
712 response.Close();
713 }
714
715 action(deserial);
716
717 }, null);
718 }, null);
719
720
721 return;
722 }
723
724 request.BeginGetResponse(delegate(IAsyncResult res2)
725 {
726 try
727 {
728 // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
729 // documented in MSDN
730 response = request.EndGetResponse(res2);
731
732 Stream respStream = null;
733 try
734 {
735 respStream = response.GetResponseStream();
736 deserial = (TResponse)deserializer.Deserialize(respStream);
737 }
738 catch (System.InvalidOperationException)
739 {
740 }
741 finally
742 {
743 respStream.Close();
744 response.Close();
745 }
746 }
747 catch (WebException e)
748 {
749 if (e.Status == WebExceptionStatus.ProtocolError)
750 {
751 if (e.Response is HttpWebResponse)
752 {
753 HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
754
755 if (httpResponse.StatusCode != HttpStatusCode.NotFound)
756 {
757 // We don't appear to be handling any other status codes, so log these feailures to that
758 // people don't spend unnecessary hours hunting phantom bugs.
759 m_log.DebugFormat(
760 "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
761 verb, requestUrl, httpResponse.StatusCode);
762 }
763 }
764 }
765 else
766 {
767 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}", verb, requestUrl, e.Status, e.Message);
768 }
769 }
770 catch (Exception e)
771 {
772 m_log.ErrorFormat("[ASYNC REQUEST]: Request {0} {1} failed with exception {2}", verb, requestUrl, e);
773 }
774
775 // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
776
777 try
778 {
779 action(deserial);
780 }
781 catch (Exception e)
782 {
783 m_log.ErrorFormat(
784 "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}", verb, requestUrl, e);
785 }
786
787 }, null);
788 }
789 }
790
791 public static class SynchronousRestFormsRequester
792 {
793 private static readonly ILog m_log =
794 LogManager.GetLogger(
795 MethodBase.GetCurrentMethod().DeclaringType);
796
797 /// <summary>
798 /// Perform a synchronous REST request.
799 /// </summary>
800 /// <param name="verb"></param>
801 /// <param name="requestUrl"></param>
802 /// <param name="obj"> </param>
803 /// <returns></returns>
804 ///
805 /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
806 /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
807 public static string MakeRequest(string verb, string requestUrl, string obj)
808 {
809 WebRequest request = WebRequest.Create(requestUrl);
810 request.Method = verb;
811 string respstring = String.Empty;
812
813 using (MemoryStream buffer = new MemoryStream())
814 {
815 if ((verb == "POST") || (verb == "PUT"))
816 {
817 request.ContentType = "text/www-form-urlencoded";
818
819 int length = 0;
820 using (StreamWriter writer = new StreamWriter(buffer))
821 {
822 writer.Write(obj);
823 writer.Flush();
824 }
825
826 length = (int)obj.Length;
827 request.ContentLength = length;
828
829 Stream requestStream = null;
830 try
831 {
832 requestStream = request.GetRequestStream();
833 requestStream.Write(buffer.ToArray(), 0, length);
834 }
835 catch (Exception e)
836 {
837 m_log.DebugFormat("[FORMS]: exception occured on sending request to {0}: " + e.ToString(), requestUrl);
838 }
839 finally
840 {
841 if (requestStream != null)
842 requestStream.Close();
843 }
844 }
845
846 try
847 {
848 using (WebResponse resp = request.GetResponse())
849 {
850 if (resp.ContentLength != 0)
851 {
852 Stream respStream = null;
853 try
854 {
855 respStream = resp.GetResponseStream();
856 using (StreamReader reader = new StreamReader(respStream))
857 {
858 respstring = reader.ReadToEnd();
859 }
860 }
861 catch (Exception e)
862 {
863 m_log.DebugFormat("[FORMS]: exception occured on receiving reply " + e.ToString());
864 }
865 finally
866 {
867 if (respStream != null)
868 respStream.Close();
869 }
870 }
871 }
872 }
873 catch (System.InvalidOperationException)
874 {
875 // This is what happens when there is invalid XML
876 m_log.DebugFormat("[FORMS]: InvalidOperationException on receiving request");
877 }
878 }
879 return respstring;
880 }
881 }
882
883 public class SynchronousRestObjectPoster
884 {
885 [Obsolete]
886 public static TResponse BeginPostObject<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
887 {
888 return SynchronousRestObjectRequester.MakeRequest<TRequest, TResponse>(verb, requestUrl, obj);
889 }
890 }
891
892 public class SynchronousRestObjectRequester
893 {
894 /// <summary>
895 /// Perform a synchronous REST request.
896 /// </summary>
897 /// <param name="verb"></param>
898 /// <param name="requestUrl"></param>
899 /// <param name="obj"> </param>
900 /// <returns></returns>
901 ///
902 /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
903 /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
904 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
905 {
906 return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0);
907 }
908
909 public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout)
910 {
911 Type type = typeof(TRequest);
912 TResponse deserial = default(TResponse);
913
914 WebRequest request = WebRequest.Create(requestUrl);
915 request.Method = verb;
916 if (pTimeout != 0)
917 request.Timeout = pTimeout * 1000;
918
919 if ((verb == "POST") || (verb == "PUT"))
920 {
921 request.ContentType = "text/xml";
922
923 MemoryStream buffer = new MemoryStream();
924
925 XmlWriterSettings settings = new XmlWriterSettings();
926 settings.Encoding = Encoding.UTF8;
927
928 using (XmlWriter writer = XmlWriter.Create(buffer, settings))
929 {
930 XmlSerializer serializer = new XmlSerializer(type);
931 serializer.Serialize(writer, obj);
932 writer.Flush();
933 }
934
935 int length = (int)buffer.Length;
936 request.ContentLength = length;
937
938 Stream requestStream = null;
939 try
940 {
941 requestStream = request.GetRequestStream();
942 requestStream.Write(buffer.ToArray(), 0, length);
943 }
944 catch (Exception)
945 {
946 return deserial;
947 }
948 finally
949 {
950 if (requestStream != null)
951 requestStream.Close();
952 }
953 }
954
955 try
956 {
957 using (WebResponse resp = request.GetResponse())
958 {
959 if (resp.ContentLength > 0)
960 {
961 Stream respStream = resp.GetResponseStream();
962 XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
963 deserial = (TResponse)deserializer.Deserialize(respStream);
964 respStream.Close();
965 }
966 }
967 }
968 catch (System.InvalidOperationException)
969 {
970 // This is what happens when there is invalid XML
971 }
972 return deserial;
973 }
974 }
633} 975}