summaryrefslogtreecommitdiff
path: root/qpid/dotnet/Qpid.Client/Client/Transport/IoHandler.cs
blob: 0475236d92d94eef0a666cf24ed3c3ed7ccd62a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
using System;
using System.IO;
using System.Threading;
using log4net;
using Apache.Qpid.Buffer;
using Apache.Qpid.Client.Protocol;

namespace Apache.Qpid.Client.Transport
{
   /// <summary>
   /// Responsible for reading and writing
   /// ByteBuffers from/to network streams, and handling
   /// the stream filters
   /// </summary>
   public class IoHandler : IByteChannel, IDisposable
   {
      private static readonly ILog _log = LogManager.GetLogger(typeof(IoHandler));
      private const int DEFAULT_BUFFER_SIZE = 32 * 1024;

      private Stream _topStream;
      private IProtocolListener _protocolListener;
      private int _readBufferSize;

      public int ReadBufferSize
      {
         get { return _readBufferSize; }
         set { _readBufferSize = value; }
      }

      /// <summary>
      /// Initialize a new instance
      /// </summary>
      /// <param name="stream">Underlying network stream</param>
      /// <param name="protocolListener">Protocol listener to report exceptions to</param>
      public IoHandler(Stream stream, IProtocolListener protocolListener)
      {
         if ( stream == null )
            throw new ArgumentNullException("stream");
         if ( protocolListener == null )
            throw new ArgumentNullException("protocolListener");

         // initially, the stream at the top of the filter 
         // chain is the underlying network stream
         _topStream = stream;
         _protocolListener = protocolListener;
         _readBufferSize = DEFAULT_BUFFER_SIZE;
      }

      /// <summary>
      /// Adds a new filter on the top of the chain
      /// </summary>
      /// <param name="filter">Stream filter to put on top of the chain</param>
      /// <remarks>
      /// This should *only* be called during initialization. We don't
      /// support changing the filter change after the first read/write
      /// has been done and it's not thread-safe to boot!
      /// </remarks>
      public void AddFilter(IStreamFilter filter)
      {
         _topStream = filter.CreateFilterStream(_topStream);
      }

      #region IByteChannel Implementation
      //
      // IByteChannel Implementation
      //

      /// <summary>
      /// Read a <see cref="ByteBuffer"/> from the underlying 
      /// network stream and any configured filters 
      /// </summary>
      /// <returns>A ByteBuffer, if available</returns>
      public ByteBuffer Read()
      {
         byte[] bytes = AllocateBuffer();

         int numOctets = _topStream.Read(bytes, 0, bytes.Length);

         return WrapByteArray(bytes, numOctets);
      }

      /// <summary>
      /// Begin an asynchronous read operation
      /// </summary>
      /// <param name="callback">Callback method to call when read operation completes</param>
      /// <param name="state">State object</param>
      /// <returns>An <see cref="System.IAsyncResult"/> object</returns>
      public IAsyncResult BeginRead(AsyncCallback callback, object state)
      {
         byte[] bytes = AllocateBuffer();
         ReadData rd = new ReadData(callback, state, bytes);
         
         // only put a callback if the caller wants one.
         AsyncCallback myCallback = null;
         if ( callback != null )
            myCallback = new AsyncCallback(OnAsyncReadDone);

         IAsyncResult result = _topStream.BeginRead(
            bytes, 0, bytes.Length, myCallback,rd
            );
         return new WrappedAsyncResult(result, bytes);
      }

      /// <summary>
      /// End an asynchronous read operation
      /// </summary>
      /// <param name="result">The <see cref="System.IAsyncResult"/> object returned from <see cref="BeginRead"/></param>
      /// <returns>The <see cref="ByteBuffer"/> read</returns>
      public ByteBuffer EndRead(IAsyncResult result)
      {
         WrappedAsyncResult theResult = (WrappedAsyncResult)result;
         int bytesRead = _topStream.EndRead(theResult.InnerResult);
         return WrapByteArray(theResult.Buffer, bytesRead);
      }

      /// <summary>
      /// Write a <see cref="ByteBuffer"/> to the underlying network 
      /// stream, going through any configured filters
      /// </summary>
      /// <param name="buffer"></param>
      public void Write(ByteBuffer buffer)
      {
         try
         {
            _topStream.Write(buffer.Array, buffer.Position, buffer.Limit); // FIXME
         } 
         catch (Exception e)
         {
            _log.Warn("Write caused exception", e);
            _protocolListener.OnException(e);
         }
      }

      /// <summary>
      /// Begin an asynchronous write operation
      /// </summary>
      /// <param name="buffer">Buffer to write</param>
      /// <param name="callback">A callback to call when the operation completes</param>
      /// <param name="state">State object</param>
      /// <returns>An <see cref="System.IAsyncResult"/> object</returns>
      public IAsyncResult BeginWrite(ByteBuffer buffer, AsyncCallback callback, object state)
      {
         try 
         {
            return _topStream.BeginWrite(
               buffer.Array, buffer.Position, buffer.Limit,
               callback, state
               );
         } catch ( Exception e )
         {
            _log.Error("BeginWrite caused exception", e);
            // not clear if an exception here should be propagated? we still
            // need to propagate it upwards anyway!
            _protocolListener.OnException(e);
            throw;
         }
      }

      /// <summary>
      /// End an asynchronous write operation
      /// </summary>
      /// <param name="result">The <see cref="System.IAsyncResult"/> object returned by <see cref="BeginWrite"/></param>
      public void EndWrite(IAsyncResult result)
      {
         try
         {
            _topStream.EndWrite(result);
         } catch ( Exception e )
         {
            _log.Error("EndWrite caused exception", e);
            // not clear if an exception here should be propagated? 
            _protocolListener.OnException(e);
            //throw;
         }
      }
      #endregion // IByteChannel Implementation

      #region IDisposable Implementation
      //
      // IDisposable Implementation
      //

      public void Dispose()
      {
         if ( _topStream != null )
         {
            _topStream.Close();
         }
      }

      #endregion // IDisposable Implementation

      #region Private and Helper Classes/Methods
      //
      // Private and Helper Classes/Methods
      //

      private byte[] AllocateBuffer()
      {
         return new byte[ReadBufferSize];
      }

      private static ByteBuffer WrapByteArray(byte[] bytes, int size)
      {
         ByteBuffer byteBuffer = ByteBuffer.Wrap(bytes);
         byteBuffer.Limit = size;
         byteBuffer.Flip();

         return byteBuffer;
      }


      private static void OnAsyncReadDone(IAsyncResult result)
      {
         ReadData rd = (ReadData) result.AsyncState;
         IAsyncResult wrapped = new WrappedAsyncResult(result, rd.Buffer);
         rd.Callback(wrapped);
      }

      class ReadData
      {
         private object _state;
         private AsyncCallback _callback;
         private byte[] _buffer;

         public object State
         {
            get { return _state; }
         }

         public AsyncCallback Callback
         {
            get { return _callback; }
         }

         public byte[] Buffer
         {
            get { return _buffer; }
         }

         public ReadData(AsyncCallback callback, object state, byte[] buffer)
         {
            _callback = callback;
            _state = state;
            _buffer = buffer;
         }
      }

      class WrappedAsyncResult : IAsyncResult
      {
         private IAsyncResult _innerResult;
         private byte[] _buffer;

         #region IAsyncResult Properties
         //
         // IAsyncResult Properties
         //
         public bool IsCompleted
         {
            get { return _innerResult.IsCompleted; }
         }

         public WaitHandle AsyncWaitHandle
         {
            get { return _innerResult.AsyncWaitHandle; }
         }

         public object AsyncState
         {
            get { return _innerResult.AsyncState; }
         }

         public bool CompletedSynchronously
         {
            get { return _innerResult.CompletedSynchronously; }
         }
         #endregion // IAsyncResult Properties

         public IAsyncResult InnerResult
         {
            get { return _innerResult; }
         }
         public byte[] Buffer
         {
            get { return _buffer; }
         }

         public WrappedAsyncResult(IAsyncResult result, byte[] buffer)
         {
            if ( result == null )
               throw new ArgumentNullException("result");
            if ( buffer == null )
               throw new ArgumentNullException("buffer");

            _innerResult = result;
            _buffer = buffer;
         }
      }

      #endregion // Private and Helper Classes/Methods
   }
}