aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim
diff options
context:
space:
mode:
authorAdam Frisby2008-05-01 15:46:46 +0000
committerAdam Frisby2008-05-01 15:46:46 +0000
commit5da028f6ef904857c52f56db6cb91494a1064a12 (patch)
tree6fbc8a4403c603c7aab3a58734b3a714e442aa19 /OpenSim
parent* Cleaned namespaces of entire solution. OpenSim directories now correspond w... (diff)
downloadopensim-SC_OLD-5da028f6ef904857c52f56db6cb91494a1064a12.zip
opensim-SC_OLD-5da028f6ef904857c52f56db6cb91494a1064a12.tar.gz
opensim-SC_OLD-5da028f6ef904857c52f56db6cb91494a1064a12.tar.bz2
opensim-SC_OLD-5da028f6ef904857c52f56db6cb91494a1064a12.tar.xz
* Removing duplicate files that somehow got undeleted from TortoiseSVN. Fixed.
Diffstat (limited to 'OpenSim')
-rw-r--r--OpenSim/Framework/Communications/RestClient/GenericAsyncResult.cs183
-rw-r--r--OpenSim/Framework/Communications/RestClient/RestClient.cs395
2 files changed, 0 insertions, 578 deletions
diff --git a/OpenSim/Framework/Communications/RestClient/GenericAsyncResult.cs b/OpenSim/Framework/Communications/RestClient/GenericAsyncResult.cs
deleted file mode 100644
index 728e25b..0000000
--- a/OpenSim/Framework/Communications/RestClient/GenericAsyncResult.cs
+++ /dev/null
@@ -1,183 +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 OpenSim Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Threading;
30
31namespace OpenSim.Framework.Communications
32{
33 internal class SimpleAsyncResult : IAsyncResult
34 {
35 private readonly AsyncCallback m_callback;
36
37 /// <summary>
38 /// Is process completed?
39 /// </summary>
40 /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
41 private byte m_completed;
42
43 /// <summary>
44 /// Did process complete synchroneously?
45 /// </summary>
46 /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
47 /// booleans and VolatileRead as m_completed
48 /// </remarks>
49 private byte m_completedSynchronously;
50
51 private readonly object m_asyncState;
52 private ManualResetEvent m_waitHandle;
53 private Exception m_exception;
54
55 internal SimpleAsyncResult(AsyncCallback cb, object state)
56 {
57 m_callback = cb;
58 m_asyncState = state;
59 m_completed = 0;
60 m_completedSynchronously = 1;
61 }
62
63 #region IAsyncResult Members
64
65 public object AsyncState
66 {
67 get { return m_asyncState; }
68 }
69
70 public WaitHandle AsyncWaitHandle
71 {
72 get
73 {
74 if (m_waitHandle == null)
75 {
76 bool done = IsCompleted;
77 ManualResetEvent mre = new ManualResetEvent(done);
78 if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
79 {
80 mre.Close();
81 }
82 else
83 {
84 if (!done && IsCompleted)
85 {
86 m_waitHandle.Set();
87 }
88 }
89 }
90 return m_waitHandle;
91 }
92 }
93
94
95 public bool CompletedSynchronously
96 {
97 get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
98 }
99
100
101 public bool IsCompleted
102 {
103 get { return Thread.VolatileRead(ref m_completed) == 1; }
104 }
105
106 #endregion
107
108 #region class Methods
109
110 internal void SetAsCompleted(bool completedSynchronously)
111 {
112 m_completed = 1;
113 if (completedSynchronously)
114 m_completedSynchronously = 1;
115 else
116 m_completedSynchronously = 0;
117
118 SignalCompletion();
119 }
120
121 internal void HandleException(Exception e, bool completedSynchronously)
122 {
123 m_completed = 1;
124 if (completedSynchronously)
125 m_completedSynchronously = 1;
126 else
127 m_completedSynchronously = 0;
128 m_exception = e;
129
130 SignalCompletion();
131 }
132
133 private void SignalCompletion()
134 {
135 if (m_waitHandle != null) m_waitHandle.Set();
136
137 if (m_callback != null) m_callback(this);
138 }
139
140 public void EndInvoke()
141 {
142 // This method assumes that only 1 thread calls EndInvoke
143 if (!IsCompleted)
144 {
145 // If the operation isn't done, wait for it
146 AsyncWaitHandle.WaitOne();
147 AsyncWaitHandle.Close();
148 m_waitHandle = null; // Allow early GC
149 }
150
151 // Operation is done: if an exception occured, throw it
152 if (m_exception != null) throw m_exception;
153 }
154
155 #endregion
156 }
157
158 internal class AsyncResult<T> : SimpleAsyncResult
159 {
160 private T m_result = default(T);
161
162 public AsyncResult(AsyncCallback asyncCallback, Object state) :
163 base(asyncCallback, state)
164 {
165 }
166
167 public void SetAsCompleted(T result, bool completedSynchronously)
168 {
169 // Save the asynchronous operation's result
170 m_result = result;
171
172 // Tell the base class that the operation completed
173 // sucessfully (no exception)
174 base.SetAsCompleted(completedSynchronously);
175 }
176
177 public new T EndInvoke()
178 {
179 base.EndInvoke();
180 return m_result;
181 }
182 }
183}
diff --git a/OpenSim/Framework/Communications/RestClient/RestClient.cs b/OpenSim/Framework/Communications/RestClient/RestClient.cs
deleted file mode 100644
index 6877690..0000000
--- a/OpenSim/Framework/Communications/RestClient/RestClient.cs
+++ /dev/null
@@ -1,395 +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 OpenSim Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using System;
29using System.Collections.Generic;
30using System.IO;
31using System.Net;
32using System.Reflection;
33using System.Text;
34using System.Threading;
35using System.Web;
36using log4net;
37
38namespace OpenSim.Framework.Communications
39{
40 /// <summary>
41 /// Implementation of a generic REST client
42 /// </summary>
43 /// <remarks>
44 /// This class is a generic implementation of a REST (Representational State Transfer) web service. This
45 /// class is designed to execute both synchroneously and asynchroneously.
46 ///
47 /// Internally the implementation works as a two stage asynchroneous web-client.
48 /// When the request is initiated, RestClient will query asynchroneously for for a web-response,
49 /// sleeping until the initial response is returned by the server. Once the initial response is retrieved
50 /// the second stage of asynchroneous requests will be triggered, in an attempt to read of the response
51 /// object into a memorystream as a sequence of asynchroneous reads.
52 ///
53 /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
54 /// other threads to execute, while it waits for a response from the web-service. RestClient it self, can be
55 /// invoked by the caller in either synchroneous mode or asynchroneous mode.
56 /// </remarks>
57 public class RestClient
58 {
59 private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
60
61 private string realuri;
62
63 #region member variables
64
65 /// <summary>
66 /// The base Uri of the web-service e.g. http://www.google.com
67 /// </summary>
68 private string _url;
69
70 /// <summary>
71 /// Path elements of the query
72 /// </summary>
73 private List<string> _pathElements = new List<string>();
74
75 /// <summary>
76 /// Parameter elements of the query, e.g. min=34
77 /// </summary>
78 private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
79
80 /// <summary>
81 /// Request method. E.g. GET, POST, PUT or DELETE
82 /// </summary>
83 private string _method;
84
85 /// <summary>
86 /// Temporary buffer used to store bytes temporarily as they come in from the server
87 /// </summary>
88 private byte[] _readbuf;
89
90 /// <summary>
91 /// MemoryStream representing the resultiong resource
92 /// </summary>
93 private Stream _resource;
94
95 /// <summary>
96 /// WebRequest object, held as a member variable
97 /// </summary>
98 private HttpWebRequest _request;
99
100 /// <summary>
101 /// WebResponse object, held as a member variable, so we can close it
102 /// </summary>
103 private HttpWebResponse _response;
104
105 /// <summary>
106 /// This flag will help block the main synchroneous method, in case we run in synchroneous mode
107 /// </summary>
108 public static ManualResetEvent _allDone = new ManualResetEvent(false);
109
110 /// <summary>
111 /// Default time out period
112 /// </summary>
113 private const int DefaultTimeout = 10*1000; // 10 seconds timeout
114
115 /// <summary>
116 /// Default Buffer size of a block requested from the web-server
117 /// </summary>
118 private const int BufferSize = 4096; // Read blocks of 4 KB.
119
120
121 /// <summary>
122 /// if an exception occours during async processing, we need to save it, so it can be
123 /// rethrown on the primary thread;
124 /// </summary>
125 private Exception _asyncException;
126
127 #endregion member variables
128
129 #region constructors
130
131 /// <summary>
132 /// Instantiate a new RestClient
133 /// </summary>
134 /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
135 public RestClient(string url)
136 {
137 _url = url;
138 _readbuf = new byte[BufferSize];
139 _resource = new MemoryStream();
140 _request = null;
141 _response = null;
142 _lock = new object();
143 }
144
145 private object _lock;
146
147 #endregion constructors
148
149 /// <summary>
150 /// Add a path element to the query, e.g. assets
151 /// </summary>
152 /// <param name="element">path entry</param>
153 public void AddResourcePath(string element)
154 {
155 if (isSlashed(element))
156 _pathElements.Add(element.Substring(0, element.Length - 1));
157 else
158 _pathElements.Add(element);
159 }
160
161 /// <summary>
162 /// Add a query parameter to the Url
163 /// </summary>
164 /// <param name="name">Name of the parameter, e.g. min</param>
165 /// <param name="value">Value of the parameter, e.g. 42</param>
166 public void AddQueryParameter(string name, string value)
167 {
168 _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
169 }
170
171 /// <summary>
172 /// Add a query parameter to the Url
173 /// </summary>
174 /// <param name="name">Name of the parameter, e.g. min</param>
175 public void AddQueryParameter(string name)
176 {
177 _parameterElements.Add(HttpUtility.UrlEncode(name), null);
178 }
179
180 /// <summary>
181 /// Web-Request method, e.g. GET, PUT, POST, DELETE
182 /// </summary>
183 public string RequestMethod
184 {
185 get { return _method; }
186 set { _method = value; }
187 }
188
189 /// <summary>
190 /// True if string contains a trailing slash '/'
191 /// </summary>
192 /// <param name="s">string to be examined</param>
193 /// <returns>true if slash is present</returns>
194 private bool isSlashed(string s)
195 {
196 return s.Substring(s.Length - 1, 1) == "/";
197 }
198
199 /// <summary>
200 /// Build a Uri based on the initial Url, path elements and parameters
201 /// </summary>
202 /// <returns>fully constructed Uri</returns>
203 private Uri buildUri()
204 {
205 StringBuilder sb = new StringBuilder();
206 sb.Append(_url);
207
208 foreach (string e in _pathElements)
209 {
210 sb.Append("/");
211 sb.Append(e);
212 }
213
214 bool firstElement = true;
215 foreach (KeyValuePair<string, string> kv in _parameterElements)
216 {
217 if (firstElement)
218 {
219 sb.Append("?");
220 firstElement = false;
221 }
222 else
223 sb.Append("&");
224
225 sb.Append(kv.Key);
226 if (kv.Value != null && kv.Value.Length != 0)
227 {
228 sb.Append("=");
229 sb.Append(kv.Value);
230 }
231 }
232 realuri = sb.ToString();
233 //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri);
234 return new Uri(sb.ToString());
235 }
236
237 #region Async communications with server
238
239 /// <summary>
240 /// Async method, invoked when a block of data has been received from the service
241 /// </summary>
242 /// <param name="ar"></param>
243 private void StreamIsReadyDelegate(IAsyncResult ar)
244 {
245 try
246 {
247 Stream s = (Stream) ar.AsyncState;
248 int read = s.EndRead(ar);
249
250 if (read > 0)
251 {
252 _resource.Write(_readbuf, 0, read);
253 IAsyncResult asynchronousResult =
254 s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
255
256 // TODO! Implement timeout, without killing the server
257 //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
258 }
259 else
260 {
261 s.Close();
262 _allDone.Set();
263 }
264 }
265 catch (Exception e)
266 {
267 _allDone.Set();
268 _asyncException = e;
269 }
270 }
271
272 #endregion Async communications with server
273
274 /// <summary>
275 /// Perform synchroneous request
276 /// </summary>
277 public Stream Request()
278 {
279 lock (_lock)
280 {
281 _request = (HttpWebRequest) WebRequest.Create(buildUri());
282 _request.KeepAlive = false;
283 _request.ContentType = "application/xml";
284 _request.Timeout = 200000;
285 _asyncException = null;
286
287// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
288 _response = (HttpWebResponse) _request.GetResponse();
289 Stream src = _response.GetResponseStream();
290 int length = src.Read(_readbuf, 0, BufferSize);
291 while (length > 0)
292 {
293 _resource.Write(_readbuf, 0, length);
294 length = src.Read(_readbuf, 0, BufferSize);
295 }
296
297
298 // TODO! Implement timeout, without killing the server
299 // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
300 //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
301
302// _allDone.WaitOne();
303 if (_response != null)
304 _response.Close();
305 if (_asyncException != null)
306 throw _asyncException;
307
308 if (_resource != null)
309 {
310 _resource.Flush();
311 _resource.Seek(0, SeekOrigin.Begin);
312 }
313
314 return _resource;
315 }
316 }
317
318 public Stream Request(Stream src)
319 {
320 _request = (HttpWebRequest) WebRequest.Create(buildUri());
321 _request.KeepAlive = false;
322 _request.ContentType = "application/xml";
323 _request.Timeout = 900000;
324 _request.Method = RequestMethod;
325 _asyncException = null;
326 _request.ContentLength = src.Length;
327
328 m_log.InfoFormat("[REST]: Request Length {0}", _request.ContentLength);
329 m_log.InfoFormat("[REST]: Sending Web Request {0}", buildUri());
330 src.Seek(0, SeekOrigin.Begin);
331 m_log.Info("[REST]: Seek is ok");
332 Stream dst = _request.GetRequestStream();
333 m_log.Info("[REST]: GetRequestStream is ok");
334
335 byte[] buf = new byte[1024];
336 int length = src.Read(buf, 0, 1024);
337 m_log.Info("[REST]: First Read is ok");
338 while (length > 0)
339 {
340 dst.Write(buf, 0, length);
341 length = src.Read(buf, 0, 1024);
342 }
343
344 _response = (HttpWebResponse) _request.GetResponse();
345
346// IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
347
348 // TODO! Implement timeout, without killing the server
349 // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
350 //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
351
352 return null;
353 }
354
355 #region Async Invocation
356
357 public IAsyncResult BeginRequest(AsyncCallback callback, object state)
358 {
359 /// <summary>
360 /// In case, we are invoked asynchroneously this object will keep track of the state
361 /// </summary>
362 AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
363 ThreadPool.QueueUserWorkItem(RequestHelper, ar);
364 return ar;
365 }
366
367 public Stream EndRequest(IAsyncResult asyncResult)
368 {
369 AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
370
371 // Wait for operation to complete, then return result or
372 // throw exception
373 return ar.EndInvoke();
374 }
375
376 private void RequestHelper(Object asyncResult)
377 {
378 // We know that it's really an AsyncResult<DateTime> object
379 AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult;
380 try
381 {
382 // Perform the operation; if sucessful set the result
383 Stream s = Request();
384 ar.SetAsCompleted(s, false);
385 }
386 catch (Exception e)
387 {
388 // If operation fails, set the exception
389 ar.HandleException(e, false);
390 }
391 }
392
393 #endregion Async Invocation
394 }
395}