View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.impl.nio.reactor;
29  
30  import java.io.IOException;
31  import java.nio.ByteBuffer;
32  import java.nio.CharBuffer;
33  import java.nio.channels.ReadableByteChannel;
34  import java.nio.channels.WritableByteChannel;
35  import java.nio.charset.CharacterCodingException;
36  import java.nio.charset.Charset;
37  import java.nio.charset.CharsetDecoder;
38  import java.nio.charset.CoderResult;
39  import java.nio.charset.CodingErrorAction;
40  
41  import org.apache.http.annotation.NotThreadSafe;
42  import org.apache.http.nio.reactor.SessionInputBuffer;
43  import org.apache.http.nio.util.ByteBufferAllocator;
44  import org.apache.http.nio.util.ExpandableBuffer;
45  import org.apache.http.nio.util.HeapByteBufferAllocator;
46  import org.apache.http.params.CoreProtocolPNames;
47  import org.apache.http.params.HttpParams;
48  import org.apache.http.protocol.HTTP;
49  import org.apache.http.util.Args;
50  import org.apache.http.util.CharArrayBuffer;
51  import org.apache.http.util.CharsetUtils;
52  
53  /**
54   * Default implementation of {@link SessionInputBuffer} based on
55   * the {@link ExpandableBuffer} class.
56   *
57   * @since 4.0
58   */
59  @SuppressWarnings("deprecation")
60  @NotThreadSafe
61  public class SessionInputBufferImpl extends ExpandableBuffer implements SessionInputBuffer {
62  
63      private final CharsetDecoder chardecoder;
64      private final int lineBuffersize;
65  
66      private CharBuffer charbuffer;
67  
68      /**
69       *  Creates SessionInputBufferImpl instance.
70       *
71       * @param buffersize input buffer size
72       * @param lineBuffersize buffer size for line operations. Has effect only if
73       *   <code>chardecoder</code> is not <code>null</code>.
74       * @param chardecoder chardecoder to be used for decoding HTTP protocol elements.
75       *   If <code>null</code> simple type cast will be used for byte to char conversion.
76       * @param allocator memory allocator.
77       *   If <code>null</code> {@link HeapByteBufferAllocator#INSTANCE} will be used.
78       *
79       * @since 4.3
80       */
81      public SessionInputBufferImpl(
82              final int buffersize,
83              final int lineBuffersize,
84              final CharsetDecoder chardecoder,
85              final ByteBufferAllocator allocator) {
86          super(buffersize, allocator != null ? allocator : HeapByteBufferAllocator.INSTANCE);
87          this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size");
88          this.chardecoder = chardecoder;
89      }
90  
91      /**
92       * @deprecated (4.3) use
93       *   {@link SessionInputBufferImpl#SessionInputBufferImpl(int, int, CharsetDecoder,
94       *     ByteBufferAllocator)}
95       */
96      @Deprecated
97      public SessionInputBufferImpl(
98              final int buffersize,
99              final int lineBuffersize,
100             final ByteBufferAllocator allocator,
101             final HttpParams params) {
102         super(buffersize, allocator);
103         this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size");
104         final String charsetName = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET);
105         final Charset charset = CharsetUtils.lookup(charsetName);
106         if (charset != null) {
107             this.chardecoder = charset.newDecoder();
108             final CodingErrorAction a1 = (CodingErrorAction) params.getParameter(
109                     CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION);
110             this.chardecoder.onMalformedInput(a1 != null ? a1 : CodingErrorAction.REPORT);
111             final CodingErrorAction a2 = (CodingErrorAction) params.getParameter(
112                     CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION);
113             this.chardecoder.onUnmappableCharacter(a2 != null? a2 : CodingErrorAction.REPORT);
114         } else {
115             this.chardecoder = null;
116         }
117     }
118 
119     /**
120      * @deprecated (4.3) use
121      *   {@link SessionInputBufferImpl#SessionInputBufferImpl(int, int, Charset)}
122      */
123     @Deprecated
124     public SessionInputBufferImpl(
125             final int buffersize,
126             final int linebuffersize,
127             final HttpParams params) {
128         this(buffersize, linebuffersize, HeapByteBufferAllocator.INSTANCE, params);
129     }
130 
131     /**
132      * @since 4.3
133      */
134     public SessionInputBufferImpl(
135             final int buffersize,
136             final int lineBuffersize,
137             final Charset charset) {
138         this(buffersize, lineBuffersize,
139                 charset != null ? charset.newDecoder() : null, HeapByteBufferAllocator.INSTANCE);
140     }
141 
142     /**
143      * @since 4.3
144      */
145     public SessionInputBufferImpl(
146             final int buffersize,
147             final int lineBuffersize) {
148         this(buffersize, lineBuffersize, null, HeapByteBufferAllocator.INSTANCE);
149     }
150 
151     /**
152      * @since 4.3
153      */
154     public SessionInputBufferImpl(final int buffersize) {
155         this(buffersize, 256, null, HeapByteBufferAllocator.INSTANCE);
156     }
157 
158     public int fill(final ReadableByteChannel channel) throws IOException {
159         Args.notNull(channel, "Channel");
160         setInputMode();
161         if (!this.buffer.hasRemaining()) {
162             expand();
163         }
164         return channel.read(this.buffer);
165     }
166 
167     public int read() {
168         setOutputMode();
169         return this.buffer.get() & 0xff;
170     }
171 
172     public int read(final ByteBuffer dst, final int maxLen) {
173         if (dst == null) {
174             return 0;
175         }
176         setOutputMode();
177         final int len = Math.min(dst.remaining(), maxLen);
178         final int chunk = Math.min(this.buffer.remaining(), len);
179         if (this.buffer.remaining() > chunk) {
180             final int oldLimit = this.buffer.limit();
181             final int newLimit = this.buffer.position() + chunk;
182             this.buffer.limit(newLimit);
183             dst.put(this.buffer);
184             this.buffer.limit(oldLimit);
185             return len;
186         } else {
187             dst.put(this.buffer);
188         }
189         return chunk;
190     }
191 
192     public int read(final ByteBuffer dst) {
193         if (dst == null) {
194             return 0;
195         }
196         return read(dst, dst.remaining());
197     }
198 
199     public int read(final WritableByteChannel dst, final int maxLen) throws IOException {
200         if (dst == null) {
201             return 0;
202         }
203         setOutputMode();
204         final int bytesRead;
205         if (this.buffer.remaining() > maxLen) {
206             final int oldLimit = this.buffer.limit();
207             final int newLimit = oldLimit - (this.buffer.remaining() - maxLen);
208             this.buffer.limit(newLimit);
209             bytesRead = dst.write(this.buffer);
210             this.buffer.limit(oldLimit);
211         } else {
212             bytesRead = dst.write(this.buffer);
213         }
214         return bytesRead;
215     }
216 
217     public int read(final WritableByteChannel dst) throws IOException {
218         if (dst == null) {
219             return 0;
220         }
221         setOutputMode();
222         return dst.write(this.buffer);
223     }
224 
225     public boolean readLine(
226             final CharArrayBuffer linebuffer,
227             final boolean endOfStream) throws CharacterCodingException {
228 
229         setOutputMode();
230         // See if there is LF char present in the buffer
231         int pos = -1;
232         boolean hasLine = false;
233         for (int i = this.buffer.position(); i < this.buffer.limit(); i++) {
234             final int b = this.buffer.get(i);
235             if (b == HTTP.LF) {
236                 hasLine = true;
237                 pos = i + 1;
238                 break;
239             }
240         }
241         if (!hasLine) {
242             if (endOfStream && this.buffer.hasRemaining()) {
243                 // No more data. Get the rest
244                 pos = this.buffer.limit();
245             } else {
246                 // Either no complete line present in the buffer
247                 // or no more data is expected
248                 return false;
249             }
250         }
251         final int origLimit = this.buffer.limit();
252         this.buffer.limit(pos);
253 
254         final int requiredCapacity = this.buffer.limit() - this.buffer.position();
255         // Ensure capacity of len assuming ASCII as the most likely charset
256         linebuffer.ensureCapacity(requiredCapacity);
257 
258         if (this.chardecoder == null) {
259             if (this.buffer.hasArray()) {
260                 final byte[] b = this.buffer.array();
261                 final int off = this.buffer.position();
262                 final int len = this.buffer.remaining();
263                 linebuffer.append(b, off, len);
264                 this.buffer.position(off + len);
265             } else {
266                 while (this.buffer.hasRemaining()) {
267                     linebuffer.append((char) (this.buffer.get() & 0xff));
268                 }
269             }
270         } else {
271             if (this.charbuffer == null) {
272                 this.charbuffer = CharBuffer.allocate(this.lineBuffersize);
273             }
274             this.chardecoder.reset();
275 
276             for (;;) {
277                 final CoderResult result = this.chardecoder.decode(
278                         this.buffer,
279                         this.charbuffer,
280                         true);
281                 if (result.isError()) {
282                     result.throwException();
283                 }
284                 if (result.isOverflow()) {
285                     this.charbuffer.flip();
286                     linebuffer.append(
287                             this.charbuffer.array(),
288                             this.charbuffer.position(),
289                             this.charbuffer.remaining());
290                     this.charbuffer.clear();
291                 }
292                 if (result.isUnderflow()) {
293                     break;
294                 }
295             }
296 
297             // flush the decoder
298             this.chardecoder.flush(this.charbuffer);
299             this.charbuffer.flip();
300             // append the decoded content to the line buffer
301             if (this.charbuffer.hasRemaining()) {
302                 linebuffer.append(
303                         this.charbuffer.array(),
304                         this.charbuffer.position(),
305                         this.charbuffer.remaining());
306             }
307 
308         }
309         this.buffer.limit(origLimit);
310 
311         // discard LF if found
312         int l = linebuffer.length();
313         if (l > 0) {
314             if (linebuffer.charAt(l - 1) == HTTP.LF) {
315                 l--;
316                 linebuffer.setLength(l);
317             }
318             // discard CR if found
319             if (l > 0) {
320                 if (linebuffer.charAt(l - 1) == HTTP.CR) {
321                     l--;
322                     linebuffer.setLength(l);
323                 }
324             }
325         }
326         return true;
327     }
328 
329     public String readLine(final boolean endOfStream) throws CharacterCodingException {
330         final CharArrayBuffer buffer = new CharArrayBuffer(64);
331         final boolean found = readLine(buffer, endOfStream);
332         if (found) {
333             return buffer.toString();
334         } else {
335             return null;
336         }
337     }
338 
339 }