VMWHttpProvider.jvm.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. using System;
  2. using System.IO;
  3. using System.Threading;
  4. using mainsoft.apache.commons.httpclient;
  5. using mainsoft.apache.commons.httpclient.methods;
  6. using mainsoft.apache.commons.httpclient.@params;
  7. using mainsoft.apache.commons.httpclient.auth;
  8. namespace System.Net
  9. {
  10. /// <summary>
  11. /// Summary description for VMWHttpProvider.
  12. /// </summary>
  13. internal class VMWHttpProvider : HttpProvider
  14. {
  15. protected static HttpClient _client; //todo init it in static constructor
  16. protected static HttpStateCache _stateCache = new HttpStateCache();
  17. protected static object LOCK_OBJECT = new object();
  18. protected HttpMethod _method;
  19. protected HttpState _state;
  20. protected HostConfiguration _hostConfig;
  21. protected HttpWebResponse _response;
  22. protected bool _hasResponse;
  23. protected bool _hasRequest;
  24. protected Stream _writeStream;
  25. private GHWebAsyncResult _asyncWrite;
  26. private GHWebAsyncResult _asyncRead;
  27. private bool _isConnectionOpened;
  28. static VMWHttpProvider()
  29. {
  30. if(java.lang.System.getProperty("mainsoft.apache.commons.logging.Log") == null)
  31. java.lang.System.setProperty("mainsoft.apache.commons.logging.Log",
  32. "mainsoft.apache.commons.logging.impl.SimpleLog");
  33. if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.showdatetime") == null)
  34. java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.showdatetime",
  35. "true");
  36. if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire") == null)
  37. java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire",
  38. "error");
  39. if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.mainsoft.apache.commons.httpclient")
  40. == null)
  41. java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.mainsoft.apache.commons.httpclient",
  42. "error");
  43. if(java.lang.System.getProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire.header")
  44. == null)
  45. java.lang.System.setProperty("mainsoft.apache.commons.logging.simplelog.log.httpclient.wire.header",
  46. "error");
  47. }
  48. public VMWHttpProvider(Uri uri) : base (uri)
  49. {
  50. }
  51. internal override ServicePoint ServicePoint
  52. {
  53. get {throw new NotImplementedException();}
  54. }
  55. public override bool IsRequestStarted()
  56. {
  57. if(_method == null)
  58. return false;
  59. return _method.isRequestSent();
  60. }
  61. public override Uri GetAddress()
  62. {
  63. if(_method == null)
  64. return GetOriginalAddress();
  65. mainsoft.apache.commons.httpclient.URI javaURI = _method.getURI();
  66. return new Uri(javaURI.ToString());
  67. }
  68. public override bool IsHaveResponse()
  69. {
  70. return _hasResponse;
  71. }
  72. private void SetJavaCredential(NetworkCredential nc, string type)
  73. {
  74. SetJavaCredential(nc, type, false);
  75. }
  76. private void SetJavaCredential(NetworkCredential nc, string type, bool proxyCredentials)
  77. {
  78. type = type.ToLower();
  79. string host = null;
  80. if(!proxyCredentials)
  81. host = GetOriginalAddress().Host;
  82. else
  83. host = ((WebProxy)this.Proxy).Address.Host;
  84. string domain = (nc.Domain == null) ? host : nc.Domain;
  85. if(type.Equals("any"))
  86. {
  87. if(!proxyCredentials)
  88. {
  89. _state.setCredentials(AuthScope.ANY,
  90. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  91. _state.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Ntlm"),
  92. new NTCredentials(nc.UserName, nc.Password, host, domain));
  93. }
  94. else
  95. {
  96. _state.setProxyCredentials(AuthScope.ANY,
  97. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  98. _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, "Ntlm"),
  99. new NTCredentials(nc.UserName, nc.Password, host, domain));
  100. }
  101. }
  102. else if(type.Equals("basic"))
  103. {
  104. if(!proxyCredentials)
  105. {
  106. _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
  107. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
  108. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  109. }
  110. else
  111. {
  112. _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
  113. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "basic"),
  114. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  115. }
  116. }
  117. else if(type.Equals("digest"))
  118. {
  119. if(!proxyCredentials)
  120. {
  121. _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
  122. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "digest"),
  123. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  124. }
  125. else
  126. {
  127. _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
  128. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "digest"),
  129. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  130. }
  131. }
  132. else if(type.Equals("ntlm"))
  133. {
  134. if(!proxyCredentials)
  135. {
  136. _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
  137. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "ntlm"),
  138. new NTCredentials(nc.UserName, nc.Password, host, domain));
  139. }
  140. else
  141. {
  142. _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
  143. AuthScope.ANY_PORT, AuthScope.ANY_REALM, "ntlm"),
  144. new NTCredentials(nc.UserName, nc.Password, host, domain));
  145. }
  146. }
  147. else
  148. {
  149. if(!proxyCredentials)
  150. {
  151. _state.setCredentials(new AuthScope(AuthScope.ANY_HOST,
  152. AuthScope.ANY_PORT, AuthScope.ANY_REALM, type),
  153. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  154. }
  155. else
  156. {
  157. _state.setProxyCredentials(new AuthScope(AuthScope.ANY_HOST,
  158. AuthScope.ANY_PORT, AuthScope.ANY_REALM, type),
  159. new UsernamePasswordCredentials(nc.UserName, nc.Password));
  160. }
  161. }
  162. }
  163. private void InitProxyCredentials()
  164. {
  165. if(this.Proxy == null)
  166. return;
  167. if(!(this.Proxy is WebProxy))
  168. return;
  169. WebProxy proxy = (WebProxy)this.Proxy;
  170. ICredentials creds = proxy.Credentials;
  171. if(creds == null)
  172. return;
  173. if(creds is CredentialCache)
  174. {
  175. string type = "basic";
  176. NetworkCredential nc = ((CredentialCache)creds).GetCredential(proxy.Address, "basic");
  177. if(nc == null)
  178. {
  179. type = "digest";
  180. nc = ((CredentialCache)creds).GetCredential(proxy.Address, "digest");
  181. if(nc == null)
  182. {
  183. type = "ntlm";
  184. nc = ((CredentialCache)creds).GetCredential(proxy.Address, "ntlm");
  185. }
  186. }
  187. if(nc != null)
  188. {
  189. SetJavaCredential(nc, type, true);
  190. }
  191. }
  192. else if (creds is NetworkCredential)
  193. {
  194. SetJavaCredential((NetworkCredential)creds, "any", true);
  195. }
  196. _method.setDoAuthentication(true);
  197. }
  198. private void InitCredentials()
  199. {
  200. if(_credentials == null)
  201. return;
  202. if(_credentials is CredentialCache)
  203. {
  204. NetworkCredential nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "basic");
  205. string type = "basic";
  206. if(nc == null)
  207. {
  208. nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "digest");
  209. type = "digest";
  210. if(nc == null)
  211. {
  212. nc = ((CredentialCache)_credentials).GetCredential(GetOriginalAddress(), "ntlm");
  213. type = "ntlm";
  214. }
  215. }
  216. if(nc != null)
  217. {
  218. SetJavaCredential(nc, type);
  219. }
  220. }
  221. else if(_credentials is NetworkCredential)
  222. {
  223. SetJavaCredential((NetworkCredential)_credentials, "any");
  224. }
  225. _method.setDoAuthentication(true);
  226. }
  227. private void InitHostConfig()
  228. {
  229. if(this.Proxy == null)
  230. return;
  231. if(this.Proxy.IsBypassed(GetOriginalAddress()))
  232. return;
  233. _hostConfig = new HostConfiguration();
  234. _hostConfig.setHost(new HttpHost(_method.getURI()));
  235. if(this.Proxy is WebProxy)
  236. {
  237. WebProxy wp = (WebProxy) this.Proxy;
  238. _hostConfig.setProxyHost(new ProxyHost(wp.Address.Host, wp.Address.Port));
  239. }
  240. else
  241. throw new NotImplementedException("Cannot accept Proxy which is not System.Net.WebProxy instance");
  242. }
  243. private void SetConnectionHeader(string val)
  244. {
  245. string connectionHeader = (this.Proxy != null) ? "Proxy-Connection" : "Connection";
  246. Headers.RemoveInternal ((this.Proxy != null) ? "Proxy-Connection" : "Connection");
  247. if(val != null)
  248. _method.setRequestHeader(connectionHeader, val);
  249. if (_keepAlive)
  250. {
  251. _method.addRequestHeader (connectionHeader, "keep-alive");
  252. Headers.SetInternal(connectionHeader,"keep-alive");
  253. }
  254. else if (!_keepAlive && _version == HttpVersion.Version11)
  255. {
  256. _method.addRequestHeader (connectionHeader, "close");
  257. Headers.SetInternal(connectionHeader,"close");
  258. }
  259. }
  260. private bool OpenConnection()
  261. {
  262. lock(this)
  263. {
  264. if(_isConnectionOpened)
  265. return false;
  266. _isConnectionOpened = true;
  267. }
  268. InitClient();
  269. InitMethod();
  270. _state = _stateCache.GetHttpState();
  271. //todo insert needed Authontication, Cookies info to state!
  272. _method.setDoAuthentication(this.PreAuthenticate);
  273. InitHostConfig();
  274. InitCredentials();
  275. InitProxyCredentials();
  276. if(this.ProtocolVersion == HttpVersion.Version11)
  277. _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_1);
  278. else if(ProtocolVersion == HttpVersion.Version10)
  279. _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_0);
  280. else
  281. throw new ProtocolViolationException("Unsupported protocol version: " + ProtocolVersion);
  282. if(!(_method is mainsoft.apache.commons.httpclient.methods.EntityEnclosingMethod))
  283. {
  284. _method.setFollowRedirects(this.AllowAutoRedirect);
  285. }
  286. else
  287. {
  288. if(!AllowWriteStreamBuffering && _contentLength < 0 && !SendChunked)
  289. throw new ProtocolViolationException();
  290. if(SendChunked)
  291. ((EntityEnclosingMethod)_method).setContentChunked(SendChunked);
  292. }
  293. if(MaxAutoRedirections != _defaultMaxRedirectsNum)
  294. {
  295. _method.getParams().setParameter(HttpClientParams.MAX_REDIRECTS,
  296. new java.lang.Integer(MaxAutoRedirections));
  297. }
  298. foreach(string k in Headers)
  299. {
  300. if(k.ToLower().Equals("connection"))
  301. continue;
  302. string val = Headers[k];
  303. val = (val == null) ? "" : val;
  304. _method.setRequestHeader(k, val);
  305. }
  306. if (this.CookieContainer != null)
  307. {
  308. string cookieHeader = this.CookieContainer.GetCookieHeader (this.GetOriginalAddress());
  309. if (cookieHeader != "")
  310. _method.setRequestHeader("Cookie", cookieHeader);
  311. }
  312. SetConnectionHeader(Headers["Connection"]);
  313. _method.getParams().setSoTimeout(ReadWriteTimeout);
  314. return true;
  315. }
  316. private static void InitClient()
  317. {
  318. lock(LOCK_OBJECT)
  319. {
  320. if(_client == null)
  321. {
  322. mainsoft.apache.commons.httpclient.MultiThreadedHttpConnectionManager manager =
  323. new mainsoft.apache.commons.httpclient.MultiThreadedHttpConnectionManager();
  324. manager.setConnectionStaleCheckingEnabled(true);
  325. manager.setMaxTotalConnections(200);
  326. //by some reasons RFC something - the default
  327. //value will be 2 , so we need to change it ...
  328. manager.setMaxConnectionsPerHost(20);
  329. _client = new HttpClient(manager);
  330. _client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, _defaultMaxRedirectsNum);
  331. _client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, new java.lang.Boolean(true));
  332. _client.getParams().setParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, new java.lang.Long(30000));
  333. _client.getParams().setParameter(HttpClientParams.USER_AGENT,
  334. "VMW4J HttpClient (based on Jakarta Commons HttpClient)");
  335. }
  336. }
  337. }
  338. private void InitMethod()
  339. {
  340. lock(this)
  341. {
  342. if(_method == null)
  343. {
  344. string uriString = this.GetOriginalAddress().AbsoluteUri;
  345. if(this.MethodName == null || this.MethodName == "")
  346. {
  347. this.MethodName = "GET";
  348. }
  349. string name = this.MethodName.ToUpper().Trim();
  350. switch(name)
  351. {
  352. case "GET" : _method = new GetMethod(uriString); break;
  353. case "PUT" : _method = new PutMethod(uriString); break;
  354. case "POST": _method = new PostMethod(uriString); break;
  355. case "HEAD": _method = new HeadMethod(uriString); break;
  356. case "TRACE": _method = new TraceMethod(uriString);break;
  357. case "DELETE": _method = new DeleteMethod(uriString);break;
  358. case "OPTIONS": _method = new OptionsMethod(uriString);break;
  359. default: _method = new GenericMethod(uriString, MethodName); break;
  360. }
  361. }
  362. }
  363. }
  364. private void InitHostConfiguration()
  365. {
  366. lock(this)
  367. {
  368. if(_hostConfig == null)
  369. {
  370. _hostConfig = new HostConfiguration();
  371. }
  372. }
  373. }
  374. public override Stream GetRequestStream()
  375. {
  376. bool isPutPost = String.Compare("post", MethodName, true) == 0
  377. || String.Compare("put", MethodName, true) == 0;
  378. if(!isPutPost)
  379. throw new ProtocolViolationException();
  380. lock(this)
  381. {
  382. if(_writeStream != null)
  383. return _writeStream;
  384. this.OpenConnection();
  385. //java.io.PipedInputStream inJavaStream = new java.io.PipedInputStream();
  386. //java.io.PipedOutputStream outJavaStream = new java.io.PipedOutputStream(inJavaStream);
  387. long contLen = _contentLength;
  388. OutputStreamRequestEntity reqEntity = new OutputStreamRequestEntity(contLen);
  389. _writeStream = new VMWRequestStream(reqEntity, contLen);
  390. EntityEnclosingMethod method = (EntityEnclosingMethod)_method;
  391. if(AllowWriteStreamBuffering )
  392. method.setRequestEntity(reqEntity);
  393. else if(!AllowWriteStreamBuffering && contLen < 0 && !SendChunked)
  394. throw new ProtocolViolationException();
  395. else
  396. method.setRequestEntity(reqEntity);
  397. _hasRequest = true;
  398. return _writeStream;
  399. }
  400. }
  401. private bool isRedirectNeeded(HttpMethod method)
  402. {
  403. switch (method.getStatusCode())
  404. {
  405. case 302:
  406. case 301:
  407. case 303:
  408. case 307:
  409. if (method.getFollowRedirects())
  410. return true;
  411. else
  412. return false;
  413. default:
  414. return false;
  415. } //end of switch
  416. }
  417. private void synchHeaders()
  418. {
  419. foreach(string k in Headers)
  420. {
  421. if(k.ToLower().Equals("connection"))
  422. continue;
  423. string val = Headers[k];
  424. val = (val == null) ? "" : val;
  425. _method.setRequestHeader(k, val);
  426. }
  427. }
  428. public override WebResponse GetResponse()
  429. {
  430. lock(this)
  431. {
  432. if(!_isConnectionOpened)
  433. OpenConnection();
  434. if(_response == null)
  435. {
  436. try
  437. {
  438. synchHeaders();
  439. _client.executeMethod(_hostConfig, _method, _state);
  440. //todo right place to re-put all headers again...
  441. mainsoft.apache.commons.httpclient.Header hostHeader =
  442. _method.getRequestHeader("Host");
  443. if(hostHeader != null)
  444. Headers.SetInternal("Host", hostHeader.getValue());
  445. _response = new HttpWebResponse(_method, _state, _stateCache, GetAddress(), this.MethodName);
  446. if(_response != null &&
  447. _response.Cookies != null &&
  448. _response.Cookies.Count > 0)
  449. {
  450. if(CookieContainer != null)
  451. {
  452. foreach(Cookie cooky in _response.Cookies)
  453. {
  454. CookieContainer.Add(GetAddress(), cooky);
  455. }
  456. }
  457. }
  458. _hasResponse = true;
  459. int respCodeAsInt = (int) _response.StatusCode;
  460. if(respCodeAsInt >= 400)
  461. {
  462. // The WebException contains the readable (not closed) response stream.
  463. // So, in case of WebException, we should read all data from the
  464. // network response stream into the memory stream, and after that
  465. // close the underlying network stream. The following requests to read
  466. // from the stream will actually read from the memory stream.
  467. // So, the this.Abort() should not be called in this case.
  468. _response.ReadAllAndClose();
  469. //this.Abort();
  470. throw new WebException("The remote server returned an error: (" + respCodeAsInt +") " +_response.StatusCode, null, WebExceptionStatus.ProtocolError, _response);
  471. }
  472. if(isRedirectNeeded(_method) && _method.getResponseHeader("location") == null)
  473. {
  474. // See comments above for the error >= 400
  475. _response.ReadAllAndClose();
  476. //this.Abort();
  477. throw new WebException("Got response code "+_response.StatusCode+", but no location provided", null, WebExceptionStatus.ProtocolError, _response);
  478. }
  479. }
  480. catch(ProtocolException e)
  481. {
  482. throw new WebException("", e);
  483. }
  484. catch(java.net.ConnectException e)
  485. {
  486. throw new WebException("Unable to connect to the remote server.", e);
  487. }
  488. catch(java.net.SocketTimeoutException e)
  489. {
  490. throw new WebException("Timeout exceeded", e);
  491. }
  492. catch(java.io.IOException e)
  493. {
  494. throw new WebException("", e);
  495. }
  496. }
  497. return _response;
  498. }
  499. }
  500. public override void Abort()
  501. {
  502. _isAborted = true;
  503. try
  504. {
  505. if(_hasResponse)
  506. {
  507. _response.Close();
  508. }
  509. }
  510. finally
  511. {
  512. _method.releaseConnection();
  513. }
  514. }
  515. public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
  516. {
  517. lock(this)
  518. {
  519. if(_asyncWrite != null)
  520. {
  521. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  522. "method while a previous call is still in progress.");
  523. }
  524. _asyncWrite = new GHWebAsyncResult (this, callback, state);
  525. if (_hasRequest)
  526. {
  527. if (_writeStream != null)
  528. {
  529. _asyncWrite.SetCompleted (true, _writeStream);
  530. _asyncWrite.DoCallback ();
  531. return _asyncWrite;
  532. }
  533. }
  534. try
  535. {
  536. this.GetRequestStream();
  537. }
  538. catch(Exception e)
  539. {
  540. _asyncWrite.SetCompleted(false, e);
  541. }
  542. _asyncWrite.SetCompleted (true, _writeStream);
  543. _asyncWrite.DoCallback ();
  544. return _asyncWrite;
  545. }
  546. }
  547. public override Stream EndGetRequestStream(IAsyncResult asyncResult)
  548. {
  549. if (asyncResult == null)
  550. throw new ArgumentNullException ("asyncResult");
  551. GHWebAsyncResult result = asyncResult as GHWebAsyncResult;
  552. if (result == null)
  553. throw new ArgumentException ("Invalid IAsyncResult");
  554. _asyncWrite = result;
  555. result.WaitUntilComplete ();
  556. Exception e = result.Exception;
  557. if (e != null)
  558. throw e;
  559. return result.WriteStream;
  560. }
  561. public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
  562. {
  563. lock(this)
  564. {
  565. if(_asyncRead != null && !_hasResponse)
  566. {
  567. throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
  568. "method while a previous call is still in progress.");
  569. }
  570. _asyncRead = new GHWebAsyncResult (this, callback, state);
  571. if (_hasResponse)
  572. {
  573. if (_response != null)
  574. {
  575. _asyncRead.SetCompleted (true, _writeStream);
  576. _asyncRead.DoCallback ();
  577. return _asyncRead;
  578. }
  579. }
  580. try
  581. {
  582. GetResponse();
  583. }
  584. catch(Exception e)
  585. {
  586. _asyncRead.SetCompleted(false, e);
  587. }
  588. _asyncRead.SetCompleted (true, _writeStream);
  589. _asyncRead.DoCallback ();
  590. return _asyncRead;
  591. }
  592. }
  593. public override WebResponse EndGetResponse(IAsyncResult asyncResult)
  594. {
  595. if (asyncResult == null)
  596. throw new ArgumentNullException ("asyncResult");
  597. GHWebAsyncResult result = asyncResult as GHWebAsyncResult;
  598. if (result == null)
  599. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  600. _asyncRead = result;
  601. if (!result.WaitUntilComplete (_timeout, false))
  602. {
  603. Abort ();
  604. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  605. }
  606. return result.Response;
  607. }
  608. #region VMWRequestStream class
  609. internal class VMWRequestStream : Stream, IDisposable
  610. {
  611. private java.io.OutputStream _javaOutput;
  612. private long _len;
  613. private long _contentLength;
  614. internal VMWRequestStream (java.io.OutputStream stream) :
  615. this(stream , -1L)
  616. {
  617. }
  618. internal VMWRequestStream (java.io.OutputStream stream, long contentLength)
  619. {
  620. _javaOutput = stream;
  621. _contentLength = contentLength;
  622. _len = 0;
  623. }
  624. public override bool CanRead
  625. {
  626. get {return false;}
  627. }
  628. public override bool CanWrite
  629. {
  630. get{return true;}
  631. }
  632. public override bool CanSeek
  633. {
  634. get { return false;}
  635. }
  636. public override long Length
  637. {
  638. get{ return _len;}
  639. }
  640. public override long Position
  641. {
  642. get
  643. {
  644. return _len;
  645. }
  646. set
  647. {
  648. throw new NotSupportedException();
  649. }
  650. }
  651. private volatile bool _closed = false;
  652. public override void Close()
  653. {
  654. if(!_closed)
  655. {
  656. lock(this)
  657. {
  658. if(!_closed)
  659. {
  660. _closed = true;
  661. _javaOutput.flush();
  662. _javaOutput.close();
  663. }
  664. }
  665. }
  666. }
  667. public override void Flush()
  668. {
  669. _javaOutput.flush();
  670. }
  671. public override int ReadByte()
  672. {
  673. throw new NotSupportedException();
  674. }
  675. public override int Read(byte[] buffer, int offset, int count)
  676. {
  677. throw new NotSupportedException();
  678. }
  679. public override void Write(byte[] buffer, int offset, int count)
  680. {
  681. if(_contentLength >= 0)
  682. {
  683. _len += count;
  684. if(_len > _contentLength)
  685. {
  686. throw new System.Net.ProtocolViolationException(
  687. "Bytes to be written to the stream exceed Content-Length bytes size specified.");
  688. }
  689. }
  690. _javaOutput.write(vmw.common.TypeUtils.ToSByteArray(buffer), offset, count);
  691. if(_contentLength == _len)
  692. {
  693. _javaOutput.flush();
  694. _javaOutput.close();
  695. }
  696. }
  697. public override long Seek(long offset, SeekOrigin origin)
  698. {
  699. throw new NotSupportedException();
  700. }
  701. public override void SetLength(long length)
  702. {
  703. throw new NotSupportedException();
  704. }
  705. void IDisposable.Dispose()
  706. {
  707. try
  708. {
  709. Close();
  710. }
  711. catch(Exception)
  712. {
  713. }
  714. }
  715. }
  716. #endregion
  717. #region GHWebAsyncResult
  718. internal class GHWebAsyncResult : IAsyncResult
  719. {
  720. private object _state;
  721. private AsyncCallback _callback;
  722. private ManualResetEvent _handle;
  723. private bool _isCompleted = false;
  724. private bool _callbackDone;
  725. private Stream _writeStream;
  726. private HttpProvider _provider;
  727. private Exception _exception;
  728. #region Constructors
  729. public GHWebAsyncResult(HttpProvider provider,
  730. AsyncCallback callback, object state) :
  731. this(state, callback)
  732. {
  733. _provider = provider;
  734. }
  735. public GHWebAsyncResult(object state, AsyncCallback callback)
  736. {
  737. _state = state;
  738. _callback = callback;
  739. }
  740. #endregion
  741. #region IAsyncResult Members
  742. public object AsyncState
  743. {
  744. get
  745. {
  746. return _state;
  747. }
  748. }
  749. public bool CompletedSynchronously
  750. {
  751. get
  752. {
  753. // TODO: Add HWebAsyncResult.CompletedSynchronously getter implementation
  754. return false;
  755. }
  756. }
  757. public WaitHandle AsyncWaitHandle
  758. {
  759. get
  760. {
  761. if (_handle == null)
  762. {
  763. lock (this)
  764. {
  765. if (_handle == null)
  766. _handle = new ManualResetEvent (_isCompleted);
  767. }
  768. }
  769. return _handle;
  770. }
  771. }
  772. public bool IsCompleted
  773. {
  774. get
  775. {
  776. return _isCompleted;
  777. }
  778. }
  779. #endregion
  780. #region Internal Properties
  781. internal Stream WriteStream
  782. {
  783. get
  784. {
  785. return _writeStream;
  786. }
  787. }
  788. internal Exception Exception
  789. {
  790. get
  791. {
  792. return _exception;
  793. }
  794. }
  795. internal HttpWebResponse Response
  796. {
  797. get
  798. {
  799. return ((VMWHttpProvider)_provider)._response;
  800. }
  801. }
  802. #endregion
  803. #region Internal Methods
  804. internal void SetCompleted(bool res, Stream writeStream)
  805. {
  806. _isCompleted = res;
  807. _writeStream = writeStream;
  808. ((ManualResetEvent) AsyncWaitHandle).Set ();
  809. }
  810. internal void SetCompleted(bool res, Exception exc)
  811. {
  812. _isCompleted = res;
  813. _exception = exc;
  814. ((ManualResetEvent) AsyncWaitHandle).Set ();
  815. }
  816. internal void DoCallback()
  817. {
  818. if (!_callbackDone && _callback != null)
  819. {
  820. _callbackDone = true;
  821. _callback (this);
  822. }
  823. }
  824. internal void WaitUntilComplete()
  825. {
  826. if(_isCompleted)
  827. return;
  828. AsyncWaitHandle.WaitOne ();
  829. }
  830. internal bool WaitUntilComplete (int timeout, bool exitContext)
  831. {
  832. if (_isCompleted)
  833. return true;
  834. return AsyncWaitHandle.WaitOne (timeout, exitContext);
  835. }
  836. #endregion
  837. }
  838. #endregion
  839. #region OutputStreamRequestEntity
  840. internal class OutputStreamRequestEntity : java.io.OutputStream, RequestEntity
  841. {
  842. private long _contentLength;
  843. private java.io.ByteArrayOutputStream _out;
  844. private sbyte[] _buffer;
  845. internal OutputStreamRequestEntity(): this(-1)
  846. {
  847. }
  848. internal OutputStreamRequestEntity(long length)
  849. {
  850. _contentLength = length;
  851. int tmp = (int) _contentLength;
  852. if(tmp <=0)
  853. tmp = 4096;
  854. _out = new java.io.ByteArrayOutputStream(tmp);
  855. }
  856. #region RequestEntity Members
  857. public bool isRepeatable()
  858. {
  859. return ((_out != null) || (_buffer != null));
  860. }
  861. public long getContentLength()
  862. {
  863. if(_out != null)
  864. {
  865. _buffer = _out.toByteArray();
  866. }
  867. if(_buffer != null)
  868. {
  869. _contentLength = _buffer.Length;
  870. _out = null;
  871. }
  872. return _contentLength;
  873. }
  874. public void writeRequest(java.io.OutputStream output)
  875. {
  876. if(_out != null)
  877. _buffer = _out.toByteArray();
  878. if(_buffer != null)
  879. {
  880. output.write(_buffer, 0, _buffer.Length);
  881. _out = null;
  882. }
  883. else throw new ApplicationException();
  884. }
  885. public string getContentType()
  886. {
  887. return null;
  888. }
  889. #endregion
  890. public override void write(int i)
  891. {
  892. _out.write(i);
  893. }
  894. }
  895. #endregion
  896. }
  897. }