| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071 |
- using System;
- using System.IO;
- using System.Threading;
- using mainsoft.apache.commons.httpclient;
- using mainsoft.apache.commons.httpclient.methods;
- using mainsoft.apache.commons.httpclient.@params;
- using mainsoft.apache.commons.httpclient.auth;
- namespace System.Net
- {
- /// <summary>
- /// Summary description for VMWHttpProvider.
- /// </summary>
- internal class VMWHttpProvider : HttpProvider
- {
- protected static HttpClient _client; //todo init it in static constructor
- protected static HttpStateCache _stateCache = new HttpStateCache();
- protected static object LOCK_OBJECT = new object();
-
-
- protected HttpMethod _method;
- protected HttpState _state;
- protected HostConfiguration _hostConfig;
-
- protected HttpWebResponse _response;
- protected bool _hasResponse;
- protected bool _hasRequest;
- protected Stream _writeStream;
- private GHWebAsyncResult _asyncWrite;
- private GHWebAsyncResult _asyncRead;
- private bool _isConnectionOpened;
-
- static VMWHttpProvider()
- {
- if(java.lang.System.getProperty("mainsoft.apache.commons.logging.Log") == null)
- java.lang.System.setProperty("mainsoft.apache.commons.logging.Log",
- "mainsoft.apache.commons.logging.impl.SimpleLog");
- if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.showdatetime") == null)
- java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.showdatetime",
- "true");
- if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire") == null)
- java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire",
- "error");
- if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.mainsoft.apache.commons.httpclient")
- == null)
- java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.mainsoft.apache.commons.httpclient",
- "error");
- if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire.header")
- == null)
- java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire.header",
- "error");
- }
- public VMWHttpProvider(Uri uri) : base (uri)
- {
- }
- internal override ServicePoint ServicePoint
- {
- get {throw new NotImplementedException();}
- }
- public override bool IsRequestStarted()
- {
- if(_method == null)
- return false;
- return _method.isRequestSent();
- }
- public override Uri GetAddress()
- {
- if(_method == null)
- return GetOriginalAddress();
- mainsoft.apache.commons.httpclient.URI javaURI = _method.getURI();
- return new Uri(javaURI.ToString());
- }
- public override bool IsHaveResponse()
- {
- return _hasResponse;
- }
- private void SetJavaCredential(NetworkCredential nc, string type)
- {
- SetJavaCredential(nc, type, false);
- }
- private void SetJavaCredential(NetworkCredential nc, string type, bool proxyCredentials)
- {
- type = type.ToLower();
- string host = null;
-
- if(!proxyCredentials)
- host = GetOriginalAddress().Host;
- else
- host = ((WebProxy)this.Proxy).Address.Host;
- string domain = (nc.Domain == null) ? host : nc.Domain;
- if(type.Equals("any"))
- {
- if(!proxyCredentials)
- {
- _state.setCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- _state.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Ntlm"),
- new NTCredentials(nc.UserName, nc.Password, host, domain));
- }
- else
- {
- _state.setProxyCredentials(AuthScope.ANY,
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Ntlm"),
- new NTCredentials(nc.UserName, nc.Password, host, domain));
- }
- }
- else if(type.Equals("basic"))
- {
- if(!proxyCredentials)
- {
- _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- else
- {
- _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- }
- else if(type.Equals("digest"))
- {
- if(!proxyCredentials)
- {
- _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "digest"),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- else
- {
- _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "digest"),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- }
- else if(type.Equals("ntlm"))
- {
- if(!proxyCredentials)
- {
- _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "ntlm"),
- new NTCredentials(nc.UserName, nc.Password, host, domain));
- }
- else
- {
- _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, "ntlm"),
- new NTCredentials(nc.UserName, nc.Password, host, domain));
- }
- }
- else
- {
- if(!proxyCredentials)
- {
- _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, type),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- else
- {
- _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
- AuthScope.ANY_PORT, AuthScope.ANY_REALM, type),
- new UsernamePasswordCredentials(nc.UserName, nc.Password));
- }
- }
- }
- private void InitProxyCredentials()
- {
- if(this.Proxy == null)
- return;
- if(!(this.Proxy is WebProxy))
- return;
-
- WebProxy proxy = (WebProxy)this.Proxy;
- ICredentials creds = proxy.Credentials;
- if(creds == null)
- return;
- if(creds is CredentialCache)
- {
- string type = "basic";
- NetworkCredential nc = ((CredentialCache)creds).GetCredential(proxy.Address, "basic");
- if(nc == null)
- {
- type = "digest";
- nc = ((CredentialCache)creds).GetCredential(proxy.Address, "digest");
- if(nc == null)
- {
- type = "ntlm";
- nc = ((CredentialCache)creds).GetCredential(proxy.Address, "ntlm");
- }
- }
- if(nc != null)
- {
- SetJavaCredential(nc, type, true);
- }
- }
- else if (creds is NetworkCredential)
- {
- SetJavaCredential((NetworkCredential)creds, "any", true);
- }
- _method.setDoAuthentication(true);
- }
- private void InitCredentials()
- {
- if(_credentials == null)
- return;
- if(_credentials is CredentialCache)
- {
- NetworkCredential nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "basic");
- string type = "basic";
- if(nc == null)
- {
- nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "digest");
- type = "digest";
- if(nc == null)
- {
- nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "ntlm");
- type = "ntlm";
- }
- }
- if(nc != null)
- {
- SetJavaCredential(nc, type);
- }
- }
- else if(_credentials is NetworkCredential)
- {
- SetJavaCredential((NetworkCredential)_credentials, "any");
- }
- _method.setDoAuthentication(true);
- }
- private void InitHostConfig()
- {
- if(this.Proxy == null)
- return;
- if(this.Proxy.IsBypassed(GetOriginalAddress()))
- return;
- _hostConfig = new HostConfiguration();
- _hostConfig.setHost(new HttpHost(_method.getURI()));
-
- if(this.Proxy is WebProxy)
- {
- WebProxy wp = (WebProxy) this.Proxy;
- _hostConfig.setProxyHost(new ProxyHost(wp.Address.Host, wp.Address.Port));
- }
- else
- throw new NotImplementedException("Cannot accept Proxy which is not System.Net.WebProxy instance");
-
- }
- private void SetConnectionHeader(string val)
- {
- string connectionHeader = (this.Proxy != null) ? "Proxy-Connection" : "Connection";
- Headers.RemoveInternal ((this.Proxy != null) ? "Proxy-Connection" : "Connection");
-
- if(val != null)
- _method.setRequestHeader(connectionHeader, val);
- if (_keepAlive)
- {
- _method.addRequestHeader (connectionHeader, "keep-alive");
- Headers.SetInternal(connectionHeader,"keep-alive");
- }
- else if (!_keepAlive && _version == HttpVersion.Version11)
- {
- _method.addRequestHeader (connectionHeader, "close");
- Headers.SetInternal(connectionHeader,"close");
- }
- }
- private bool OpenConnection()
- {
- lock(this)
- {
- if(_isConnectionOpened)
- return false;
- _isConnectionOpened = true;
- }
- InitClient();
- InitMethod();
- _state = _stateCache.GetHttpState();
- //todo insert needed Authontication, Cookies info to state!
- _method.setDoAuthentication(this.PreAuthenticate);
-
- InitHostConfig();
- InitCredentials();
- InitProxyCredentials();
-
- if(this.ProtocolVersion == HttpVersion.Version11)
- _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_1);
- else if(ProtocolVersion == HttpVersion.Version10)
- _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_0);
- else
- throw new ProtocolViolationException("Unsupported protocol version: " + ProtocolVersion);
- if(!(_method is mainsoft.apache.commons.httpclient.methods.EntityEnclosingMethod))
- {
- _method.setFollowRedirects(this.AllowAutoRedirect);
- }
- else
- {
- if(!AllowWriteStreamBuffering && _contentLength < 0 && !SendChunked)
- throw new ProtocolViolationException();
- if(SendChunked)
- ((EntityEnclosingMethod)_method).setContentChunked(SendChunked);
- }
- if(MaxAutoRedirections != _defaultMaxRedirectsNum)
- {
- _method.getParams().setParameter(HttpClientParams.MAX_REDIRECTS,
- new java.lang.Integer(MaxAutoRedirections));
- }
-
-
-
- foreach(string k in Headers)
- {
- if(k.ToLower().Equals("connection"))
- continue;
- string val = Headers[k];
- val = (val == null) ? "" : val;
- _method.setRequestHeader(k, val);
- }
- if (this.CookieContainer != null)
- {
- string cookieHeader = this.CookieContainer.GetCookieHeader (this.GetOriginalAddress());
- if (cookieHeader != "")
- _method.setRequestHeader("Cookie", cookieHeader);
- }
- SetConnectionHeader(Headers["Connection"]);
-
- _method.getParams().setSoTimeout(ReadWriteTimeout);
- return true;
-
- }
- private static void InitClient()
- {
- lock(LOCK_OBJECT)
- {
- if(_client == null)
- {
- mainsoft.apache.commons.httpclient.MultiThreadedHttpConnectionManager manager =
- new mainsoft.apache.commons.httpclient.MultiThreadedHttpConnectionManager();
- manager.setConnectionStaleCheckingEnabled(true);
- manager.setMaxTotalConnections(200);
- //by some reasons RFC something - the default
- //value will be 2 , so we need to change it ...
- manager.setMaxConnectionsPerHost(20);
- _client = new HttpClient(manager);
- _client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, _defaultMaxRedirectsNum);
- _client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, new java.lang.Boolean(true));
- _client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new java.lang.Long(30000));
- _client.getParams().setParameter(HttpClientParams.USER_AGENT,
- "VMW4J HttpClient (based on Jakarta Commons HttpClient)");
- }
- }
- }
- private void InitMethod()
- {
- lock(this)
- {
- if(_method == null)
- {
- string uriString = this.GetOriginalAddress().AbsoluteUri;
- if(this.MethodName == null || this.MethodName == "")
- {
- this.MethodName = "GET";
- }
-
- string name = this.MethodName.ToUpper().Trim();
- switch(name)
- {
- case "GET" : _method = new GetMethod(uriString); break;
- case "PUT" : _method = new PutMethod(uriString); break;
- case "POST": _method = new PostMethod(uriString); break;
- case "HEAD": _method = new HeadMethod(uriString); break;
- case "TRACE": _method = new TraceMethod(uriString);break;
- case "DELETE": _method = new DeleteMethod(uriString);break;
- case "OPTIONS": _method = new OptionsMethod(uriString);break;
- default: _method = new GenericMethod(uriString, MethodName); break;
- }
- }
- }
- }
- private void InitHostConfiguration()
- {
- lock(this)
- {
- if(_hostConfig == null)
- {
- _hostConfig = new HostConfiguration();
- }
- }
- }
-
- public override Stream GetRequestStream()
- {
- bool isPutPost = String.Compare("post", MethodName, true) == 0
- || String.Compare("put", MethodName, true) == 0;
- if(!isPutPost)
- throw new ProtocolViolationException();
- lock(this)
- {
- if(_writeStream != null)
- return _writeStream;
- this.OpenConnection();
- //java.io.PipedInputStream inJavaStream = new java.io.PipedInputStream();
- //java.io.PipedOutputStream outJavaStream = new java.io.PipedOutputStream(inJavaStream);
-
- long contLen = _contentLength;
-
- OutputStreamRequestEntity reqEntity = new OutputStreamRequestEntity(contLen);
- _writeStream = new VMWRequestStream(reqEntity, contLen);
-
- EntityEnclosingMethod method = (EntityEnclosingMethod)_method;
- if(AllowWriteStreamBuffering )
- method.setRequestEntity(reqEntity);
- else if(!AllowWriteStreamBuffering && contLen < 0 && !SendChunked)
- throw new ProtocolViolationException();
- else
- method.setRequestEntity(reqEntity);
-
- _hasRequest = true;
- return _writeStream;
- }
- }
- private bool isRedirectNeeded(HttpMethod method)
- {
- switch (method.getStatusCode())
- {
- case 302:
- case 301:
- case 303:
- case 307:
- if (method.getFollowRedirects())
- return true;
- else
- return false;
- default:
- return false;
- } //end of switch
- }
- private void synchHeaders()
- {
- foreach(string k in Headers)
- {
- if(k.ToLower().Equals("connection"))
- continue;
- string val = Headers[k];
- val = (val == null) ? "" : val;
- _method.setRequestHeader(k, val);
- }
- }
- public override WebResponse GetResponse()
- {
- lock(this)
- {
- if(!_isConnectionOpened)
- OpenConnection();
- if(_response == null)
- {
- try
- {
- synchHeaders();
- _client.executeMethod(_hostConfig, _method, _state);
- //todo right place to re-put all headers again...
- mainsoft.apache.commons.httpclient.Header hostHeader =
- _method.getRequestHeader("Host");
- if(hostHeader != null)
- Headers.SetInternal("Host", hostHeader.getValue());
- _response = new HttpWebResponse(_method, _state, _stateCache, GetAddress(), this.MethodName);
-
- if(_response != null &&
- _response.Cookies != null &&
- _response.Cookies.Count > 0)
- {
- if(CookieContainer != null)
- {
- foreach(Cookie cooky in _response.Cookies)
- {
- CookieContainer.Add(GetAddress(), cooky);
- }
- }
- }
- _hasResponse = true;
- int respCodeAsInt = (int) _response.StatusCode;
- if(respCodeAsInt >= 400)
- {
- // The WebException contains the readable (not closed) response stream.
- // So, in case of WebException, we should read all data from the
- // network response stream into the memory stream, and after that
- // close the underlying network stream. The following requests to read
- // from the stream will actually read from the memory stream.
- // So, the this.Abort() should not be called in this case.
- _response.ReadAllAndClose();
- //this.Abort();
- throw new WebException("The remote server returned an error: (" + respCodeAsInt +") " +_response.StatusCode, null, WebExceptionStatus.ProtocolError, _response);
- }
- if(isRedirectNeeded(_method) && _method.getResponseHeader("location") == null)
- {
- // See comments above for the error >= 400
- _response.ReadAllAndClose();
- //this.Abort();
- throw new WebException("Got response code "+_response.StatusCode+", but no location provided", null, WebExceptionStatus.ProtocolError, _response);
- }
- }
- catch(ProtocolException e)
- {
- throw new WebException("", e);
- }
- catch(java.net.ConnectException e)
- {
- throw new WebException("Unable to connect to the remote server.", e);
- }
- catch(java.net.SocketTimeoutException e)
- {
- throw new WebException("Timeout exceeded", e);
- }
- catch(java.io.IOException e)
- {
- throw new WebException("", e);
- }
- }
- return _response;
- }
- }
- public override void Abort()
- {
- _isAborted = true;
- try
- {
- if(_hasResponse)
- {
- _response.Close();
- }
- }
- finally
- {
- _method.releaseConnection();
- }
- }
- public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
- {
- lock(this)
- {
- if(_asyncWrite != null)
- {
- throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
- "method while a previous call is still in progress.");
- }
-
- _asyncWrite = new GHWebAsyncResult (this, callback, state);
- if (_hasRequest)
- {
- if (_writeStream != null)
- {
- _asyncWrite.SetCompleted (true, _writeStream);
- _asyncWrite.DoCallback ();
- return _asyncWrite;
- }
- }
-
-
- try
- {
- this.GetRequestStream();
- }
- catch(Exception e)
- {
- _asyncWrite.SetCompleted(false, e);
- }
- _asyncWrite.SetCompleted (true, _writeStream);
- _asyncWrite.DoCallback ();
- return _asyncWrite;
-
- }
- }
- public override Stream EndGetRequestStream(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- throw new ArgumentNullException ("asyncResult");
- GHWebAsyncResult result = asyncResult as GHWebAsyncResult;
- if (result == null)
- throw new ArgumentException ("Invalid IAsyncResult");
- _asyncWrite = result;
- result.WaitUntilComplete ();
- Exception e = result.Exception;
-
- if (e != null)
- throw e;
- return result.WriteStream;
- }
- public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
- {
- lock(this)
- {
- if(_asyncRead != null && !_hasResponse)
- {
- throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
- "method while a previous call is still in progress.");
- }
-
- _asyncRead = new GHWebAsyncResult (this, callback, state);
- if (_hasResponse)
- {
- if (_response != null)
- {
- _asyncRead.SetCompleted (true, _writeStream);
- _asyncRead.DoCallback ();
- return _asyncRead;
- }
- }
-
- try
- {
- GetResponse();
- }
- catch(Exception e)
- {
- _asyncRead.SetCompleted(false, e);
- }
- _asyncRead.SetCompleted (true, _writeStream);
- _asyncRead.DoCallback ();
- return _asyncRead;
-
- }
- }
- public override WebResponse EndGetResponse(IAsyncResult asyncResult)
- {
- if (asyncResult == null)
- throw new ArgumentNullException ("asyncResult");
- GHWebAsyncResult result = asyncResult as GHWebAsyncResult;
- if (result == null)
- throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
-
- _asyncRead = result;
- if (!result.WaitUntilComplete (_timeout, false))
- {
- Abort ();
- throw new WebException("The request timed out", WebExceptionStatus.Timeout);
- }
-
- return result.Response;
- }
-
- #region VMWRequestStream class
- internal class VMWRequestStream : Stream, IDisposable
- {
- private java.io.OutputStream _javaOutput;
- private long _len;
- private long _contentLength;
- internal VMWRequestStream (java.io.OutputStream stream) :
- this(stream , -1L)
- {
- }
- internal VMWRequestStream (java.io.OutputStream stream, long contentLength)
- {
- _javaOutput = stream;
- _contentLength = contentLength;
- _len = 0;
- }
- public override bool CanRead
- {
- get {return false;}
- }
- public override bool CanWrite
- {
- get{return true;}
- }
- public override bool CanSeek
- {
- get { return false;}
- }
- public override long Length
- {
- get{ return _len;}
- }
- public override long Position
- {
- get
- {
- return _len;
- }
- set
- {
- throw new NotSupportedException();
- }
- }
- private volatile bool _closed = false;
- public override void Close()
- {
- if(!_closed)
- {
- lock(this)
- {
- if(!_closed)
- {
- _closed = true;
- _javaOutput.flush();
- _javaOutput.close();
- }
- }
- }
- }
- public override void Flush()
- {
- _javaOutput.flush();
- }
- public override int ReadByte()
- {
- throw new NotSupportedException();
- }
- public override int Read(byte[] buffer, int offset, int count)
- {
- throw new NotSupportedException();
- }
- public override void Write(byte[] buffer, int offset, int count)
- {
- if(_contentLength >= 0)
- {
- _len += count;
- if(_len > _contentLength)
- {
- throw new System.Net.ProtocolViolationException(
- "Bytes to be written to the stream exceed Content-Length bytes size specified.");
- }
- }
- _javaOutput.write(vmw.common.TypeUtils.ToSByteArray(buffer), offset, count);
- if(_contentLength == _len)
- {
- _javaOutput.flush();
- _javaOutput.close();
- }
- }
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotSupportedException();
- }
- public override void SetLength(long length)
- {
- throw new NotSupportedException();
- }
- void IDisposable.Dispose()
- {
- try
- {
- Close();
- }
- catch(Exception)
- {
- }
- }
- }
-
- #endregion
- #region GHWebAsyncResult
- internal class GHWebAsyncResult : IAsyncResult
- {
- private object _state;
- private AsyncCallback _callback;
- private ManualResetEvent _handle;
- private bool _isCompleted = false;
- private bool _callbackDone;
- private Stream _writeStream;
- private HttpProvider _provider;
- private Exception _exception;
- #region Constructors
- public GHWebAsyncResult(HttpProvider provider,
- AsyncCallback callback, object state) :
- this(state, callback)
- {
- _provider = provider;
- }
- public GHWebAsyncResult(object state, AsyncCallback callback)
- {
- _state = state;
- _callback = callback;
- }
- #endregion
- #region IAsyncResult Members
- public object AsyncState
- {
- get
- {
- return _state;
- }
- }
- public bool CompletedSynchronously
- {
- get
- {
- // TODO: Add HWebAsyncResult.CompletedSynchronously getter implementation
- return false;
- }
- }
- public WaitHandle AsyncWaitHandle
- {
- get
- {
- if (_handle == null)
- {
- lock (this)
- {
- if (_handle == null)
- _handle = new ManualResetEvent (_isCompleted);
- }
- }
-
- return _handle;
- }
- }
- public bool IsCompleted
- {
- get
- {
- return _isCompleted;
- }
- }
- #endregion
- #region Internal Properties
- internal Stream WriteStream
- {
- get
- {
- return _writeStream;
- }
- }
- internal Exception Exception
- {
- get
- {
- return _exception;
- }
- }
- internal HttpWebResponse Response
- {
- get
- {
- return ((VMWHttpProvider)_provider)._response;
- }
- }
- #endregion
- #region Internal Methods
- internal void SetCompleted(bool res, Stream writeStream)
- {
- _isCompleted = res;
- _writeStream = writeStream;
- ((ManualResetEvent) AsyncWaitHandle).Set ();
- }
- internal void SetCompleted(bool res, Exception exc)
- {
- _isCompleted = res;
- _exception = exc;
- ((ManualResetEvent) AsyncWaitHandle).Set ();
- }
- internal void DoCallback()
- {
- if (!_callbackDone && _callback != null)
- {
- _callbackDone = true;
- _callback (this);
- }
- }
- internal void WaitUntilComplete()
- {
- if(_isCompleted)
- return;
- AsyncWaitHandle.WaitOne ();
- }
- internal bool WaitUntilComplete (int timeout, bool exitContext)
- {
- if (_isCompleted)
- return true;
- return AsyncWaitHandle.WaitOne (timeout, exitContext);
- }
- #endregion
- }
- #endregion
- #region OutputStreamRequestEntity
- internal class OutputStreamRequestEntity : java.io.OutputStream, RequestEntity
- {
- private long _contentLength;
- private java.io.ByteArrayOutputStream _out;
- private sbyte[] _buffer;
- internal OutputStreamRequestEntity(): this(-1)
- {
- }
- internal OutputStreamRequestEntity(long length)
- {
- _contentLength = length;
- int tmp = (int) _contentLength;
- if(tmp <=0)
- tmp = 4096;
- _out = new java.io.ByteArrayOutputStream(tmp);
- }
- #region RequestEntity Members
- public bool isRepeatable()
- {
- return ((_out != null) || (_buffer != null));
- }
- public long getContentLength()
- {
- if(_out != null)
- {
- _buffer = _out.toByteArray();
- }
- if(_buffer != null)
- {
- _contentLength = _buffer.Length;
- _out = null;
- }
- return _contentLength;
- }
- public void writeRequest(java.io.OutputStream output)
- {
- if(_out != null)
- _buffer = _out.toByteArray();
- if(_buffer != null)
- {
- output.write(_buffer, 0, _buffer.Length);
- _out = null;
- }
- else throw new ApplicationException();
- }
- public string getContentType()
- {
- return null;
- }
- #endregion
- public override void write(int i)
- {
- _out.write(i);
- }
- }
- #endregion
- }
- }
|