blob: 717907c5bd3ed734aa5684b68093c76b9fa2ef31 [file] [log] [blame]
Bryan Duxbury62359472010-06-24 20:34:34 +00001/**
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 *
20 */
21
22using System;
23using System.Collections.Generic;
24using System.IO;
25using System.Net;
Roger Meier284a9b52011-12-08 13:39:56 +000026using System.Threading;
Bryan Duxbury62359472010-06-24 20:34:34 +000027
28namespace Thrift.Transport
29{
30 public class THttpClient : TTransport
31 {
32 private readonly Uri uri;
33 private Stream inputStream;
34 private MemoryStream outputStream = new MemoryStream();
35 private int connectTimeout = 0;
36 private int readTimeout = 0;
37 private IDictionary<String, String> customHeaders = new Dictionary<string, string>();
38
39 public THttpClient(Uri u)
40 {
41 uri = u;
42 }
43
44 public int ConnectTimeout
45 {
46 set
47 {
48 connectTimeout = value;
49 }
50 }
51
52 public int ReadTimeout
53 {
54 set
55 {
56 readTimeout = value;
57 }
58 }
59
60 public IDictionary<String, String> CustomHeaders
61 {
62 get
63 {
64 return customHeaders;
65 }
66 }
67
68 public override bool IsOpen
69 {
70 get
71 {
72 return true;
73 }
74 }
75
76 public override void Open()
77 {
78 }
79
80 public override void Close()
81 {
82 if (inputStream != null)
83 {
84 inputStream.Close();
85 inputStream = null;
86 }
87 if (outputStream != null)
88 {
89 outputStream.Close();
90 outputStream = null;
91 }
92 }
93
94 public override int Read(byte[] buf, int off, int len)
95 {
96 if (inputStream == null)
97 {
98 throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent");
99 }
100
101 try
102 {
103 int ret = inputStream.Read(buf, off, len);
104
105 if (ret == -1)
106 {
107 throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available");
108 }
109
110 return ret;
111 }
112 catch (IOException iox)
113 {
114 throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString());
115 }
116 }
117
118 public override void Write(byte[] buf, int off, int len)
119 {
120 outputStream.Write(buf, off, len);
121 }
122
Roger Meier284a9b52011-12-08 13:39:56 +0000123#if !SILVERLIGHT
Bryan Duxbury62359472010-06-24 20:34:34 +0000124 public override void Flush()
125 {
Bryan Duxburyea67a782010-08-06 17:50:51 +0000126 try
127 {
128 SendRequest();
129 }
130 finally
131 {
132 outputStream = new MemoryStream();
133 }
Bryan Duxbury62359472010-06-24 20:34:34 +0000134 }
135
136 private void SendRequest()
137 {
138 try
139 {
140 HttpWebRequest connection = CreateRequest();
141
142 byte[] data = outputStream.ToArray();
143 connection.ContentLength = data.Length;
144
145 Stream requestStream = connection.GetRequestStream();
146 requestStream.Write(data, 0, data.Length);
147 inputStream = connection.GetResponse().GetResponseStream();
148 }
149 catch (IOException iox)
150 {
151 throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString());
152 }
153 catch (WebException wx)
154 {
155 throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx);
156 }
157 }
Roger Meier284a9b52011-12-08 13:39:56 +0000158#endif
159 private HttpWebRequest CreateRequest()
Bryan Duxbury62359472010-06-24 20:34:34 +0000160 {
161 HttpWebRequest connection = (HttpWebRequest)WebRequest.Create(uri);
162
Roger Meier284a9b52011-12-08 13:39:56 +0000163#if !SILVERLIGHT
Bryan Duxbury62359472010-06-24 20:34:34 +0000164 if (connectTimeout > 0)
165 {
166 connection.Timeout = connectTimeout;
167 }
168 if (readTimeout > 0)
169 {
170 connection.ReadWriteTimeout = readTimeout;
171 }
Roger Meier284a9b52011-12-08 13:39:56 +0000172#endif
Bryan Duxbury62359472010-06-24 20:34:34 +0000173 // Make the request
174 connection.ContentType = "application/x-thrift";
175 connection.Accept = "application/x-thrift";
176 connection.UserAgent = "C#/THttpClient";
177 connection.Method = "POST";
Roger Meier284a9b52011-12-08 13:39:56 +0000178#if !SILVERLIGHT
Bryan Duxbury62359472010-06-24 20:34:34 +0000179 connection.ProtocolVersion = HttpVersion.Version10;
Roger Meier284a9b52011-12-08 13:39:56 +0000180#endif
Bryan Duxbury62359472010-06-24 20:34:34 +0000181
Roger Meier284a9b52011-12-08 13:39:56 +0000182 //add custom headers here
Bryan Duxbury62359472010-06-24 20:34:34 +0000183 foreach (KeyValuePair<string, string> item in customHeaders)
184 {
Roger Meier284a9b52011-12-08 13:39:56 +0000185#if !SILVERLIGHT
Bryan Duxbury62359472010-06-24 20:34:34 +0000186 connection.Headers.Add(item.Key, item.Value);
Roger Meier284a9b52011-12-08 13:39:56 +0000187#else
188 connection.Headers[item.Key] = item.Value;
189#endif
Bryan Duxbury62359472010-06-24 20:34:34 +0000190 }
191
Jake Farrell12ac2ac2011-12-09 02:21:37 +0000192#if !SILVERLIGHT
Bryan Duxbury62359472010-06-24 20:34:34 +0000193 connection.Proxy = null;
Jake Farrell12ac2ac2011-12-09 02:21:37 +0000194#endif
Bryan Duxbury62359472010-06-24 20:34:34 +0000195
Roger Meier284a9b52011-12-08 13:39:56 +0000196 return connection;
Bryan Duxbury62359472010-06-24 20:34:34 +0000197 }
Roger Meier284a9b52011-12-08 13:39:56 +0000198
199#if SILVERLIGHT
200 public override IAsyncResult BeginFlush(AsyncCallback callback, object state)
201 {
202 // Extract request and reset buffer
203 var data = outputStream.ToArray();
204
205 //requestBuffer_ = new MemoryStream();
206
207 try
208 {
209 // Create connection object
210 var flushAsyncResult = new FlushAsyncResult(callback, state);
211 flushAsyncResult.Connection = CreateRequest();
212
213 flushAsyncResult.Data = data;
214
215
216 flushAsyncResult.Connection.BeginGetRequestStream(GetRequestStreamCallback, flushAsyncResult);
217 return flushAsyncResult;
218
219 }
220 catch (IOException iox)
221 {
222 throw new TTransportException(iox.ToString());
223 }
224 }
225
226 public override void EndFlush(IAsyncResult asyncResult)
227 {
228 try
229 {
230 var flushAsyncResult = (FlushAsyncResult) asyncResult;
231
232 if (!flushAsyncResult.IsCompleted)
233 {
234 var waitHandle = flushAsyncResult.AsyncWaitHandle;
235 waitHandle.WaitOne(); // blocking INFINITEly
236 waitHandle.Close();
237 }
238
239 if (flushAsyncResult.AsyncException != null)
240 {
241 throw flushAsyncResult.AsyncException;
242 }
243 } finally
244 {
245 outputStream = new MemoryStream();
246 }
247
248 }
249
250
251 private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
252 {
253 var flushAsyncResult = (FlushAsyncResult)asynchronousResult.AsyncState;
254 try
255 {
256 var reqStream = flushAsyncResult.Connection.EndGetRequestStream(asynchronousResult);
257 reqStream.Write(flushAsyncResult.Data, 0, flushAsyncResult.Data.Length);
258 reqStream.Flush();
259 reqStream.Close();
260
261 // Start the asynchronous operation to get the response
262 flushAsyncResult.Connection.BeginGetResponse(GetResponseCallback, flushAsyncResult);
263 }
264 catch (Exception exception)
265 {
266 flushAsyncResult.AsyncException = new TTransportException(exception.ToString());
267 flushAsyncResult.UpdateStatusToComplete();
268 flushAsyncResult.NotifyCallbackWhenAvailable();
269 }
270 }
271
272 private void GetResponseCallback(IAsyncResult asynchronousResult)
273 {
274 var flushAsyncResult = (FlushAsyncResult)asynchronousResult.AsyncState;
275 try
276 {
277 inputStream = flushAsyncResult.Connection.EndGetResponse(asynchronousResult).GetResponseStream();
278 }
279 catch (Exception exception)
280 {
281 flushAsyncResult.AsyncException = new TTransportException(exception.ToString());
282 }
283 flushAsyncResult.UpdateStatusToComplete();
284 flushAsyncResult.NotifyCallbackWhenAvailable();
285 }
286
287 // Based on http://msmvps.com/blogs/luisabreu/archive/2009/06/15/multithreading-implementing-the-iasyncresult-interface.aspx
288 class FlushAsyncResult : IAsyncResult
289 {
290 private volatile Boolean _isCompleted;
291 private ManualResetEvent _evt;
292 private readonly AsyncCallback _cbMethod;
293 private readonly Object _state;
294
295 public FlushAsyncResult(AsyncCallback cbMethod, Object state)
296 {
297 _cbMethod = cbMethod;
298 _state = state;
299 }
300
301 internal byte[] Data { get; set; }
302 internal HttpWebRequest Connection { get; set; }
303 internal TTransportException AsyncException { get; set; }
304
305 public object AsyncState
306 {
307 get { return _state; }
308 }
309 public WaitHandle AsyncWaitHandle
310 {
311 get { return GetEvtHandle(); }
312 }
313 public bool CompletedSynchronously
314 {
315 get { return false; }
316 }
317 public bool IsCompleted
318 {
319 get { return _isCompleted; }
320 }
321 private readonly Object _locker = new Object();
322 private ManualResetEvent GetEvtHandle()
323 {
324 lock (_locker)
325 {
326 if (_evt == null)
327 {
328 _evt = new ManualResetEvent(false);
329 }
330 if (_isCompleted)
331 {
332 _evt.Set();
333 }
334 }
335 return _evt;
336 }
337 internal void UpdateStatusToComplete()
338 {
339 _isCompleted = true; //1. set _iscompleted to true
340 lock (_locker)
341 {
342 if (_evt != null)
343 {
344 _evt.Set(); //2. set the event, when it exists
345 }
346 }
347 }
348
349 internal void NotifyCallbackWhenAvailable()
350 {
351 if (_cbMethod != null)
352 {
353 _cbMethod(this);
354 }
355 }
356 }
357
358#endif
359 }
Bryan Duxbury62359472010-06-24 20:34:34 +0000360}