fix line endings
parent
32869aec47
commit
461eaf188e
|
@ -1,163 +1,163 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
|
||||||
namespace OpenSim.Framework.RestClient
|
namespace OpenSim.Framework.RestClient
|
||||||
{
|
{
|
||||||
internal class SimpleAsyncResult : IAsyncResult
|
internal class SimpleAsyncResult : IAsyncResult
|
||||||
{
|
{
|
||||||
|
|
||||||
private readonly AsyncCallback m_callback;
|
private readonly AsyncCallback m_callback;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Is process completed?
|
/// Is process completed?
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
|
/// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks>
|
||||||
private byte m_completed;
|
private byte m_completed;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Did process complete synchroneously?
|
/// Did process complete synchroneously?
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
|
/// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about
|
||||||
/// booleans and VolatileRead as m_completed
|
/// booleans and VolatileRead as m_completed
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
private byte m_completedSynchronously;
|
private byte m_completedSynchronously;
|
||||||
|
|
||||||
private readonly object m_asyncState;
|
private readonly object m_asyncState;
|
||||||
private ManualResetEvent m_waitHandle;
|
private ManualResetEvent m_waitHandle;
|
||||||
private Exception m_exception;
|
private Exception m_exception;
|
||||||
|
|
||||||
internal SimpleAsyncResult(AsyncCallback cb, object state)
|
internal SimpleAsyncResult(AsyncCallback cb, object state)
|
||||||
{
|
{
|
||||||
m_callback = cb;
|
m_callback = cb;
|
||||||
m_asyncState = state;
|
m_asyncState = state;
|
||||||
m_completed = 0;
|
m_completed = 0;
|
||||||
m_completedSynchronously = 1;
|
m_completedSynchronously = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#region IAsyncResult Members
|
#region IAsyncResult Members
|
||||||
|
|
||||||
public object AsyncState
|
public object AsyncState
|
||||||
{
|
{
|
||||||
get { return m_asyncState; }
|
get { return m_asyncState; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
public WaitHandle AsyncWaitHandle
|
public WaitHandle AsyncWaitHandle
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
{
|
{
|
||||||
if (m_waitHandle == null)
|
if (m_waitHandle == null)
|
||||||
{
|
{
|
||||||
bool done = IsCompleted;
|
bool done = IsCompleted;
|
||||||
ManualResetEvent mre = new ManualResetEvent(done);
|
ManualResetEvent mre = new ManualResetEvent(done);
|
||||||
if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
|
if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null)
|
||||||
{
|
{
|
||||||
mre.Close();
|
mre.Close();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (!done && IsCompleted)
|
if (!done && IsCompleted)
|
||||||
{
|
{
|
||||||
m_waitHandle.Set();
|
m_waitHandle.Set();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return m_waitHandle;
|
return m_waitHandle;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public bool CompletedSynchronously
|
public bool CompletedSynchronously
|
||||||
{
|
{
|
||||||
get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
|
get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public bool IsCompleted
|
public bool IsCompleted
|
||||||
{
|
{
|
||||||
get { return Thread.VolatileRead(ref m_completed) == 1; }
|
get { return Thread.VolatileRead(ref m_completed) == 1; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
|
|
||||||
#region class Methods
|
#region class Methods
|
||||||
internal void SetAsCompleted(bool completedSynchronously)
|
internal void SetAsCompleted(bool completedSynchronously)
|
||||||
{
|
{
|
||||||
m_completed = 1;
|
m_completed = 1;
|
||||||
if(completedSynchronously)
|
if(completedSynchronously)
|
||||||
m_completedSynchronously = 1;
|
m_completedSynchronously = 1;
|
||||||
else
|
else
|
||||||
m_completedSynchronously = 0;
|
m_completedSynchronously = 0;
|
||||||
|
|
||||||
SignalCompletion();
|
SignalCompletion();
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void HandleException(Exception e, bool completedSynchronously)
|
internal void HandleException(Exception e, bool completedSynchronously)
|
||||||
{
|
{
|
||||||
m_completed = 1;
|
m_completed = 1;
|
||||||
if (completedSynchronously)
|
if (completedSynchronously)
|
||||||
m_completedSynchronously = 1;
|
m_completedSynchronously = 1;
|
||||||
else
|
else
|
||||||
m_completedSynchronously = 0;
|
m_completedSynchronously = 0;
|
||||||
m_exception = e;
|
m_exception = e;
|
||||||
|
|
||||||
SignalCompletion();
|
SignalCompletion();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SignalCompletion()
|
private void SignalCompletion()
|
||||||
{
|
{
|
||||||
if(m_waitHandle != null) m_waitHandle.Set();
|
if(m_waitHandle != null) m_waitHandle.Set();
|
||||||
|
|
||||||
if(m_callback != null) m_callback(this);
|
if(m_callback != null) m_callback(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void EndInvoke()
|
public void EndInvoke()
|
||||||
{
|
{
|
||||||
// This method assumes that only 1 thread calls EndInvoke
|
// This method assumes that only 1 thread calls EndInvoke
|
||||||
if (!IsCompleted)
|
if (!IsCompleted)
|
||||||
{
|
{
|
||||||
// If the operation isn't done, wait for it
|
// If the operation isn't done, wait for it
|
||||||
AsyncWaitHandle.WaitOne();
|
AsyncWaitHandle.WaitOne();
|
||||||
AsyncWaitHandle.Close();
|
AsyncWaitHandle.Close();
|
||||||
m_waitHandle = null; // Allow early GC
|
m_waitHandle = null; // Allow early GC
|
||||||
}
|
}
|
||||||
|
|
||||||
// Operation is done: if an exception occured, throw it
|
// Operation is done: if an exception occured, throw it
|
||||||
if (m_exception != null) throw m_exception;
|
if (m_exception != null) throw m_exception;
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
|
|
||||||
internal class AsyncResult<T> : SimpleAsyncResult
|
internal class AsyncResult<T> : SimpleAsyncResult
|
||||||
{
|
{
|
||||||
private T m_result = default(T);
|
private T m_result = default(T);
|
||||||
|
|
||||||
public AsyncResult(AsyncCallback asyncCallback, Object state) :
|
public AsyncResult(AsyncCallback asyncCallback, Object state) :
|
||||||
base(asyncCallback, state) { }
|
base(asyncCallback, state) { }
|
||||||
|
|
||||||
|
|
||||||
public void SetAsCompleted(T result, bool completedSynchronously)
|
public void SetAsCompleted(T result, bool completedSynchronously)
|
||||||
{
|
{
|
||||||
// Save the asynchronous operation's result
|
// Save the asynchronous operation's result
|
||||||
m_result = result;
|
m_result = result;
|
||||||
|
|
||||||
// Tell the base class that the operation completed
|
// Tell the base class that the operation completed
|
||||||
// sucessfully (no exception)
|
// sucessfully (no exception)
|
||||||
base.SetAsCompleted(completedSynchronously);
|
base.SetAsCompleted(completedSynchronously);
|
||||||
}
|
}
|
||||||
|
|
||||||
new public T EndInvoke()
|
new public T EndInvoke()
|
||||||
{
|
{
|
||||||
base.EndInvoke();
|
base.EndInvoke();
|
||||||
return m_result;
|
return m_result;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,328 +1,328 @@
|
||||||
using System;
|
using System;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Web;
|
using System.Web;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
|
|
||||||
namespace OpenSim.Framework.RestClient
|
namespace OpenSim.Framework.RestClient
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Implementation of a generic REST client
|
/// Implementation of a generic REST client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <remarks>
|
/// <remarks>
|
||||||
/// This class is a generic implementation of a REST (Representational State Transfer) web service. This
|
/// This class is a generic implementation of a REST (Representational State Transfer) web service. This
|
||||||
/// class is designed to execute both synchroneously and asynchroneously.
|
/// class is designed to execute both synchroneously and asynchroneously.
|
||||||
///
|
///
|
||||||
/// Internally the implementation works as a two stage asynchroneous web-client.
|
/// Internally the implementation works as a two stage asynchroneous web-client.
|
||||||
/// When the request is initiated, RestClient will query asynchroneously for for a web-response,
|
/// When the request is initiated, RestClient will query asynchroneously for for a web-response,
|
||||||
/// sleeping until the initial response is returned by the server. Once the initial response is retrieved
|
/// sleeping until the initial response is returned by the server. Once the initial response is retrieved
|
||||||
/// the second stage of asynchroneous requests will be triggered, in an attempt to read of the response
|
/// the second stage of asynchroneous requests will be triggered, in an attempt to read of the response
|
||||||
/// object into a memorystream as a sequence of asynchroneous reads.
|
/// object into a memorystream as a sequence of asynchroneous reads.
|
||||||
///
|
///
|
||||||
/// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
|
/// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing
|
||||||
/// other threads to execute, while it waits for a response from the web-service. RestClient it self, can be
|
/// other threads to execute, while it waits for a response from the web-service. RestClient it self, can be
|
||||||
/// invoked by the caller in either synchroneous mode or asynchroneous mode.
|
/// invoked by the caller in either synchroneous mode or asynchroneous mode.
|
||||||
/// </remarks>
|
/// </remarks>
|
||||||
public class RestClient
|
public class RestClient
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The base Uri of the web-service e.g. http://www.google.com
|
/// The base Uri of the web-service e.g. http://www.google.com
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private string _url;
|
private string _url;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Path elements of the query
|
/// Path elements of the query
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private List<string> _pathElements = new List<string>();
|
private List<string> _pathElements = new List<string>();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Parameter elements of the query, e.g. min=34
|
/// Parameter elements of the query, e.g. min=34
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
|
private Dictionary<string, string> _parameterElements = new Dictionary<string, string>();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Request method. E.g. GET, POST, PUT or DELETE
|
/// Request method. E.g. GET, POST, PUT or DELETE
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private string _method;
|
private string _method;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Temporary buffer used to store bytes temporarily as they come in from the server
|
/// Temporary buffer used to store bytes temporarily as they come in from the server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private byte[] _readbuf;
|
private byte[] _readbuf;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// MemoryStream representing the resultiong resource
|
/// MemoryStream representing the resultiong resource
|
||||||
/// </summary>
|
/// </summary>
|
||||||
MemoryStream _resource;
|
MemoryStream _resource;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// WebRequest object, held as a member variable
|
/// WebRequest object, held as a member variable
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private HttpWebRequest _request;
|
private HttpWebRequest _request;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// WebResponse object, held as a member variable, so we can close it
|
/// WebResponse object, held as a member variable, so we can close it
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private HttpWebResponse _response;
|
private HttpWebResponse _response;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// This flag will help block the main synchroneous method, in case we run in synchroneous mode
|
/// This flag will help block the main synchroneous method, in case we run in synchroneous mode
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static ManualResetEvent _allDone = new ManualResetEvent(false);
|
public static ManualResetEvent _allDone = new ManualResetEvent(false);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Default time out period
|
/// Default time out period
|
||||||
/// </summary>
|
/// </summary>
|
||||||
const int DefaultTimeout = 10 * 1000; // 10 seconds timeout
|
const int DefaultTimeout = 10 * 1000; // 10 seconds timeout
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Default Buffer size of a block requested from the web-server
|
/// Default Buffer size of a block requested from the web-server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
const int BufferSize = 4096; // Read blocks of 4 KB.
|
const int BufferSize = 4096; // Read blocks of 4 KB.
|
||||||
|
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// if an exception occours during async processing, we need to save it, so it can be
|
/// if an exception occours during async processing, we need to save it, so it can be
|
||||||
/// rethrown on the primary thread;
|
/// rethrown on the primary thread;
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private Exception _asyncException;
|
private Exception _asyncException;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Instantiate a new RestClient
|
/// Instantiate a new RestClient
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
|
/// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param>
|
||||||
public RestClient(string url)
|
public RestClient(string url)
|
||||||
{
|
{
|
||||||
_url = url;
|
_url = url;
|
||||||
_readbuf = new byte[BufferSize];
|
_readbuf = new byte[BufferSize];
|
||||||
_resource = new MemoryStream();
|
_resource = new MemoryStream();
|
||||||
_request = null;
|
_request = null;
|
||||||
_response = null;
|
_response = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Add a path element to the query, e.g. assets
|
/// Add a path element to the query, e.g. assets
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="element">path entry</param>
|
/// <param name="element">path entry</param>
|
||||||
public void AddResourcePath(string element)
|
public void AddResourcePath(string element)
|
||||||
{
|
{
|
||||||
if(isSlashed(element))
|
if(isSlashed(element))
|
||||||
_pathElements.Add(element.Substring(0, element.Length-1));
|
_pathElements.Add(element.Substring(0, element.Length-1));
|
||||||
else
|
else
|
||||||
_pathElements.Add(element);
|
_pathElements.Add(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Add a query parameter to the Url
|
/// Add a query parameter to the Url
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="name">Name of the parameter, e.g. min</param>
|
/// <param name="name">Name of the parameter, e.g. min</param>
|
||||||
/// <param name="value">Value of the parameter, e.g. 42</param>
|
/// <param name="value">Value of the parameter, e.g. 42</param>
|
||||||
public void AddQueryParameter(string name, string value)
|
public void AddQueryParameter(string name, string value)
|
||||||
{
|
{
|
||||||
_parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
|
_parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Web-Request method, e.g. GET, PUT, POST, DELETE
|
/// Web-Request method, e.g. GET, PUT, POST, DELETE
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public string RequestMethod
|
public string RequestMethod
|
||||||
{
|
{
|
||||||
get { return _method; }
|
get { return _method; }
|
||||||
set { _method = value; }
|
set { _method = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// True if string contains a trailing slash '/'
|
/// True if string contains a trailing slash '/'
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="s">string to be examined</param>
|
/// <param name="s">string to be examined</param>
|
||||||
/// <returns>true if slash is present</returns>
|
/// <returns>true if slash is present</returns>
|
||||||
private bool isSlashed(string s)
|
private bool isSlashed(string s)
|
||||||
{
|
{
|
||||||
return s.Substring(s.Length - 1, 1) == "/";
|
return s.Substring(s.Length - 1, 1) == "/";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// return a slash or blank. A slash will be returned if the string does not contain one
|
/// return a slash or blank. A slash will be returned if the string does not contain one
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="s">stromg to be examined</param>
|
/// <param name="s">stromg to be examined</param>
|
||||||
/// <returns>slash '/' if not already present</returns>
|
/// <returns>slash '/' if not already present</returns>
|
||||||
private string slash(string s)
|
private string slash(string s)
|
||||||
{
|
{
|
||||||
return isSlashed(s) ? "" : "/";
|
return isSlashed(s) ? "" : "/";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Build a Uri based on the intial Url, path elements and parameters
|
/// Build a Uri based on the intial Url, path elements and parameters
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <returns>fully constructed Uri</returns>
|
/// <returns>fully constructed Uri</returns>
|
||||||
Uri buildUri()
|
Uri buildUri()
|
||||||
{
|
{
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.Append(_url);
|
sb.Append(_url);
|
||||||
|
|
||||||
foreach (string e in _pathElements)
|
foreach (string e in _pathElements)
|
||||||
{
|
{
|
||||||
sb.Append("/");
|
sb.Append("/");
|
||||||
sb.Append(e);
|
sb.Append(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool firstElement = true;
|
bool firstElement = true;
|
||||||
foreach (KeyValuePair<string, string> kv in _parameterElements)
|
foreach (KeyValuePair<string, string> kv in _parameterElements)
|
||||||
{
|
{
|
||||||
if (firstElement)
|
if (firstElement)
|
||||||
{
|
{
|
||||||
sb.Append("?");
|
sb.Append("?");
|
||||||
firstElement = false;
|
firstElement = false;
|
||||||
} else
|
} else
|
||||||
sb.Append("&");
|
sb.Append("&");
|
||||||
|
|
||||||
sb.Append(kv.Key);
|
sb.Append(kv.Key);
|
||||||
if (kv.Value != null && kv.Value.Length != 0)
|
if (kv.Value != null && kv.Value.Length != 0)
|
||||||
{
|
{
|
||||||
sb.Append("=");
|
sb.Append("=");
|
||||||
sb.Append(kv.Value);
|
sb.Append(kv.Value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return new Uri(sb.ToString());
|
return new Uri(sb.ToString());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Async method, invoked when a block of data has been received from the service
|
/// Async method, invoked when a block of data has been received from the service
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ar"></param>
|
/// <param name="ar"></param>
|
||||||
private void StreamIsReadyDelegate(IAsyncResult ar)
|
private void StreamIsReadyDelegate(IAsyncResult ar)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
Stream s = (Stream)ar.AsyncState;
|
Stream s = (Stream)ar.AsyncState;
|
||||||
int read = s.EndRead(ar);
|
int read = s.EndRead(ar);
|
||||||
|
|
||||||
// Read the HTML page and then print it to the console.
|
// Read the HTML page and then print it to the console.
|
||||||
if (read > 0)
|
if (read > 0)
|
||||||
{
|
{
|
||||||
_resource.Write(_readbuf, 0, read);
|
_resource.Write(_readbuf, 0, read);
|
||||||
IAsyncResult asynchronousResult = s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
|
IAsyncResult asynchronousResult = s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
|
||||||
|
|
||||||
// TODO! Implement timeout, without killing the server
|
// TODO! Implement timeout, without killing the server
|
||||||
//ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
//ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
s.Close();
|
s.Close();
|
||||||
_allDone.Set();
|
_allDone.Set();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_allDone.Set();
|
_allDone.Set();
|
||||||
_asyncException = e;
|
_asyncException = e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Async method, invoked when the intial response if received from the server
|
/// Async method, invoked when the intial response if received from the server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="ar"></param>
|
/// <param name="ar"></param>
|
||||||
private void ResponseIsReadyDelegate(IAsyncResult ar)
|
private void ResponseIsReadyDelegate(IAsyncResult ar)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// grab response
|
// grab response
|
||||||
WebRequest wr = (WebRequest)ar.AsyncState;
|
WebRequest wr = (WebRequest)ar.AsyncState;
|
||||||
_response = (HttpWebResponse)wr.EndGetResponse(ar);
|
_response = (HttpWebResponse)wr.EndGetResponse(ar);
|
||||||
|
|
||||||
// get response stream, and setup async reading
|
// get response stream, and setup async reading
|
||||||
Stream s = _response.GetResponseStream();
|
Stream s = _response.GetResponseStream();
|
||||||
IAsyncResult asynchronousResult = s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
|
IAsyncResult asynchronousResult = s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s);
|
||||||
|
|
||||||
// TODO! Implement timeout, without killing the server
|
// TODO! Implement timeout, without killing the server
|
||||||
// wait until completed, or we timed out
|
// wait until completed, or we timed out
|
||||||
// ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
// ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_allDone.Set();
|
_allDone.Set();
|
||||||
_asyncException = e;
|
_asyncException = e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Abort the request if the timer fires.
|
// Abort the request if the timer fires.
|
||||||
private static void TimeoutCallback(object state, bool timedOut)
|
private static void TimeoutCallback(object state, bool timedOut)
|
||||||
{
|
{
|
||||||
if (timedOut)
|
if (timedOut)
|
||||||
{
|
{
|
||||||
HttpWebRequest request = state as HttpWebRequest;
|
HttpWebRequest request = state as HttpWebRequest;
|
||||||
if (request != null)
|
if (request != null)
|
||||||
{
|
{
|
||||||
request.Abort();
|
request.Abort();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Perform synchroneous request
|
/// Perform synchroneous request
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public Stream Request()
|
public Stream Request()
|
||||||
{
|
{
|
||||||
_request = (HttpWebRequest)WebRequest.Create(buildUri());
|
_request = (HttpWebRequest)WebRequest.Create(buildUri());
|
||||||
_request.KeepAlive = false;
|
_request.KeepAlive = false;
|
||||||
_request.ContentType = "text/html";
|
_request.ContentType = "text/html";
|
||||||
_request.Timeout = 200;
|
_request.Timeout = 200;
|
||||||
_asyncException = null;
|
_asyncException = null;
|
||||||
|
|
||||||
IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
|
IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request);
|
||||||
|
|
||||||
// TODO! Implement timeout, without killing the server
|
// TODO! Implement timeout, without killing the server
|
||||||
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
|
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
|
||||||
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
//ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true);
|
||||||
|
|
||||||
_allDone.WaitOne();
|
_allDone.WaitOne();
|
||||||
if(_response != null)
|
if(_response != null)
|
||||||
_response.Close();
|
_response.Close();
|
||||||
if (_asyncException != null)
|
if (_asyncException != null)
|
||||||
throw _asyncException;
|
throw _asyncException;
|
||||||
return _resource;
|
return _resource;
|
||||||
}
|
}
|
||||||
|
|
||||||
#region Async Invocation
|
#region Async Invocation
|
||||||
public IAsyncResult BeginRequest(AsyncCallback callback, object state)
|
public IAsyncResult BeginRequest(AsyncCallback callback, object state)
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// In case, we are invoked asynchroneously this object will keep track of the state
|
/// In case, we are invoked asynchroneously this object will keep track of the state
|
||||||
/// </summary>
|
/// </summary>
|
||||||
AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
|
AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state);
|
||||||
ThreadPool.QueueUserWorkItem(RequestHelper, ar);
|
ThreadPool.QueueUserWorkItem(RequestHelper, ar);
|
||||||
return ar;
|
return ar;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Stream EndRequest(IAsyncResult asyncResult)
|
public Stream EndRequest(IAsyncResult asyncResult)
|
||||||
{
|
{
|
||||||
AsyncResult<Stream> ar = (AsyncResult<Stream>)asyncResult;
|
AsyncResult<Stream> ar = (AsyncResult<Stream>)asyncResult;
|
||||||
|
|
||||||
// Wait for operation to complete, then return result or
|
// Wait for operation to complete, then return result or
|
||||||
// throw exception
|
// throw exception
|
||||||
return ar.EndInvoke();
|
return ar.EndInvoke();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void RequestHelper(Object asyncResult)
|
private void RequestHelper(Object asyncResult)
|
||||||
{
|
{
|
||||||
// We know that it's really an AsyncResult<DateTime> object
|
// We know that it's really an AsyncResult<DateTime> object
|
||||||
AsyncResult<Stream> ar = (AsyncResult<Stream>)asyncResult;
|
AsyncResult<Stream> ar = (AsyncResult<Stream>)asyncResult;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
// Perform the operation; if sucessful set the result
|
// Perform the operation; if sucessful set the result
|
||||||
Stream s = Request();
|
Stream s = Request();
|
||||||
ar.SetAsCompleted(s, false);
|
ar.SetAsCompleted(s, false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
// If operation fails, set the exception
|
// If operation fails, set the exception
|
||||||
ar.HandleException(e, false);
|
ar.HandleException(e, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
#endregion Async Invocation
|
#endregion Async Invocation
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,132 +1,132 @@
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System.IO;
|
using System.IO;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Nini.Config;
|
using Nini.Config;
|
||||||
using OpenSim.Framework.Communications.Cache;
|
using OpenSim.Framework.Communications.Cache;
|
||||||
using OpenSim.Framework.Console;
|
using OpenSim.Framework.Console;
|
||||||
using OpenSim.Framework.Interfaces;
|
using OpenSim.Framework.Interfaces;
|
||||||
using OpenSim.Framework.Servers;
|
using OpenSim.Framework.Servers;
|
||||||
using OpenSim.Framework.Types;
|
using OpenSim.Framework.Types;
|
||||||
using OpenSim.Framework.Utilities;
|
using OpenSim.Framework.Utilities;
|
||||||
using OpenSim.Region.ClientStack;
|
using OpenSim.Region.ClientStack;
|
||||||
using OpenSim.Region.Communications.Local;
|
using OpenSim.Region.Communications.Local;
|
||||||
using OpenSim.Region.Communications.OGS1;
|
using OpenSim.Region.Communications.OGS1;
|
||||||
using OpenSim.Region.Environment;
|
using OpenSim.Region.Environment;
|
||||||
using OpenSim.Region.Environment.Scenes;
|
using OpenSim.Region.Environment.Scenes;
|
||||||
using OpenSim.Region.Physics.Manager;
|
using OpenSim.Region.Physics.Manager;
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Nwc.XmlRpc;
|
using Nwc.XmlRpc;
|
||||||
using RegionInfo = OpenSim.Framework.Types.RegionInfo;
|
using RegionInfo = OpenSim.Framework.Types.RegionInfo;
|
||||||
|
|
||||||
namespace OpenSim
|
namespace OpenSim
|
||||||
{
|
{
|
||||||
class OpenSimController
|
class OpenSimController
|
||||||
{
|
{
|
||||||
private OpenSimMain m_app;
|
private OpenSimMain m_app;
|
||||||
private BaseHttpServer m_httpServer;
|
private BaseHttpServer m_httpServer;
|
||||||
private const bool m_enablexmlrpc = false;
|
private const bool m_enablexmlrpc = false;
|
||||||
|
|
||||||
public OpenSimController(OpenSimMain core, BaseHttpServer httpd)
|
public OpenSimController(OpenSimMain core, BaseHttpServer httpd)
|
||||||
{
|
{
|
||||||
m_app = core;
|
m_app = core;
|
||||||
m_httpServer = httpd;
|
m_httpServer = httpd;
|
||||||
|
|
||||||
if (m_enablexmlrpc)
|
if (m_enablexmlrpc)
|
||||||
{
|
{
|
||||||
m_httpServer.AddXmlRPCHandler("admin_create_region", XmlRpcCreateRegionMethod);
|
m_httpServer.AddXmlRPCHandler("admin_create_region", XmlRpcCreateRegionMethod);
|
||||||
m_httpServer.AddXmlRPCHandler("admin_shutdown", XmlRpcShutdownMethod);
|
m_httpServer.AddXmlRPCHandler("admin_shutdown", XmlRpcShutdownMethod);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public XmlRpcResponse XmlRpcShutdownMethod(XmlRpcRequest request)
|
public XmlRpcResponse XmlRpcShutdownMethod(XmlRpcRequest request)
|
||||||
{
|
{
|
||||||
MainLog.Instance.Verbose("CONTROLLER", "Recieved Shutdown Administrator Request");
|
MainLog.Instance.Verbose("CONTROLLER", "Recieved Shutdown Administrator Request");
|
||||||
XmlRpcResponse response = new XmlRpcResponse();
|
XmlRpcResponse response = new XmlRpcResponse();
|
||||||
Hashtable requestData = (Hashtable)request.Params[0];
|
Hashtable requestData = (Hashtable)request.Params[0];
|
||||||
|
|
||||||
if ((string)requestData["shutdown"] == "delayed")
|
if ((string)requestData["shutdown"] == "delayed")
|
||||||
{
|
{
|
||||||
int timeout = Convert.ToInt32((string)requestData["milliseconds"]);
|
int timeout = Convert.ToInt32((string)requestData["milliseconds"]);
|
||||||
|
|
||||||
Hashtable responseData = new Hashtable();
|
Hashtable responseData = new Hashtable();
|
||||||
responseData["accepted"] = "true";
|
responseData["accepted"] = "true";
|
||||||
response.Value = responseData;
|
response.Value = responseData;
|
||||||
|
|
||||||
m_app.SceneManager.SendGeneralMessage("Region is going down in " + ((int)(timeout / 1000)).ToString() + " second(s). Please save what you are doing and log out.");
|
m_app.SceneManager.SendGeneralMessage("Region is going down in " + ((int)(timeout / 1000)).ToString() + " second(s). Please save what you are doing and log out.");
|
||||||
|
|
||||||
// Perform shutdown
|
// Perform shutdown
|
||||||
System.Timers.Timer shutdownTimer = new System.Timers.Timer(timeout); // Wait before firing
|
System.Timers.Timer shutdownTimer = new System.Timers.Timer(timeout); // Wait before firing
|
||||||
shutdownTimer.AutoReset = false;
|
shutdownTimer.AutoReset = false;
|
||||||
shutdownTimer.Elapsed += new System.Timers.ElapsedEventHandler(shutdownTimer_Elapsed);
|
shutdownTimer.Elapsed += new System.Timers.ElapsedEventHandler(shutdownTimer_Elapsed);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Hashtable responseData = new Hashtable();
|
Hashtable responseData = new Hashtable();
|
||||||
responseData["accepted"] = "true";
|
responseData["accepted"] = "true";
|
||||||
response.Value = responseData;
|
response.Value = responseData;
|
||||||
|
|
||||||
m_app.SceneManager.SendGeneralMessage("Region is going down now.");
|
m_app.SceneManager.SendGeneralMessage("Region is going down now.");
|
||||||
|
|
||||||
// Perform shutdown
|
// Perform shutdown
|
||||||
System.Timers.Timer shutdownTimer = new System.Timers.Timer(2000); // Wait 2 seconds before firing
|
System.Timers.Timer shutdownTimer = new System.Timers.Timer(2000); // Wait 2 seconds before firing
|
||||||
shutdownTimer.AutoReset = false;
|
shutdownTimer.AutoReset = false;
|
||||||
shutdownTimer.Elapsed += new System.Timers.ElapsedEventHandler(shutdownTimer_Elapsed);
|
shutdownTimer.Elapsed += new System.Timers.ElapsedEventHandler(shutdownTimer_Elapsed);
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void shutdownTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
void shutdownTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||||||
{
|
{
|
||||||
m_app.Shutdown();
|
m_app.Shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
public XmlRpcResponse XmlRpcCreateRegionMethod(XmlRpcRequest request)
|
public XmlRpcResponse XmlRpcCreateRegionMethod(XmlRpcRequest request)
|
||||||
{
|
{
|
||||||
MainLog.Instance.Verbose("CONTROLLER", "Recieved Create Region Administrator Request");
|
MainLog.Instance.Verbose("CONTROLLER", "Recieved Create Region Administrator Request");
|
||||||
XmlRpcResponse response = new XmlRpcResponse();
|
XmlRpcResponse response = new XmlRpcResponse();
|
||||||
Hashtable requestData = (Hashtable)request.Params[0];
|
Hashtable requestData = (Hashtable)request.Params[0];
|
||||||
|
|
||||||
RegionInfo newRegionData = new RegionInfo();
|
RegionInfo newRegionData = new RegionInfo();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
newRegionData.RegionID = (string)requestData["region_id"];
|
newRegionData.RegionID = (string)requestData["region_id"];
|
||||||
newRegionData.RegionName = (string)requestData["region_name"];
|
newRegionData.RegionName = (string)requestData["region_name"];
|
||||||
newRegionData.RegionLocX = Convert.ToUInt32((string)requestData["region_x"]);
|
newRegionData.RegionLocX = Convert.ToUInt32((string)requestData["region_x"]);
|
||||||
newRegionData.RegionLocY = Convert.ToUInt32((string)requestData["region_y"]);
|
newRegionData.RegionLocY = Convert.ToUInt32((string)requestData["region_y"]);
|
||||||
|
|
||||||
// Security risk
|
// Security risk
|
||||||
newRegionData.DataStore = (string)requestData["datastore"];
|
newRegionData.DataStore = (string)requestData["datastore"];
|
||||||
|
|
||||||
newRegionData.InternalEndPoint = new System.Net.IPEndPoint(
|
newRegionData.InternalEndPoint = new System.Net.IPEndPoint(
|
||||||
System.Net.IPAddress.Parse((string)requestData["listen_ip"]), 0);
|
System.Net.IPAddress.Parse((string)requestData["listen_ip"]), 0);
|
||||||
|
|
||||||
newRegionData.InternalEndPoint.Port = Convert.ToInt32((string)requestData["listen_port"]);
|
newRegionData.InternalEndPoint.Port = Convert.ToInt32((string)requestData["listen_port"]);
|
||||||
newRegionData.ExternalHostName = (string)requestData["external_address"];
|
newRegionData.ExternalHostName = (string)requestData["external_address"];
|
||||||
|
|
||||||
newRegionData.MasterAvatarFirstName = (string)requestData["region_master_first"];
|
newRegionData.MasterAvatarFirstName = (string)requestData["region_master_first"];
|
||||||
newRegionData.MasterAvatarLastName = (string)requestData["region_master_last"];
|
newRegionData.MasterAvatarLastName = (string)requestData["region_master_last"];
|
||||||
|
|
||||||
m_app.CreateRegion(newRegionData);
|
m_app.CreateRegion(newRegionData);
|
||||||
|
|
||||||
Hashtable responseData = new Hashtable();
|
Hashtable responseData = new Hashtable();
|
||||||
responseData["created"] = "true";
|
responseData["created"] = "true";
|
||||||
response.Value = responseData;
|
response.Value = responseData;
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
Hashtable responseData = new Hashtable();
|
Hashtable responseData = new Hashtable();
|
||||||
responseData["created"] = "false";
|
responseData["created"] = "false";
|
||||||
responseData["error"] = e.ToString();
|
responseData["error"] = e.ToString();
|
||||||
response.Value = responseData;
|
response.Value = responseData;
|
||||||
}
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue