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.CharsetEncoder;
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.SessionOutputBuffer;
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 SessionOutputBuffer} based on
55   * the {@link ExpandableBuffer} class.
56   *
57   * @since 4.0
58   */
59  @SuppressWarnings("deprecation")
60  @NotThreadSafe
61  public class SessionOutputBufferImpl extends ExpandableBuffer implements SessionOutputBuffer {
62  
63      private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF};
64  
65      private final CharsetEncoder charencoder;
66      private final int lineBuffersize;
67  
68      private CharBuffer charbuffer;
69  
70      /**
71       *  Creates SessionOutputBufferImpl instance.
72       *
73       * @param buffersize input buffer size
74       * @param lineBuffersize buffer size for line operations. Has effect only if
75       *   {@code charencoder} is not {@code null}.
76       * @param charencoder charencoder to be used for encoding HTTP protocol elements.
77       *   If {@code null} simple type cast will be used for char to byte conversion.
78       * @param allocator memory allocator.
79       *   If {@code null} {@link HeapByteBufferAllocator#INSTANCE} will be used.
80       *
81       * @since 4.3
82       */
83      public SessionOutputBufferImpl(
84              final int buffersize,
85              final int lineBuffersize,
86              final CharsetEncoder charencoder,
87              final ByteBufferAllocator allocator) {
88          super(buffersize, allocator != null ? allocator : HeapByteBufferAllocator.INSTANCE);
89          this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size");
90          this.charencoder = charencoder;
91      }
92  
93      /**
94       * @deprecated (4.3) use
95       *   {@link SessionOutputBufferImpl#SessionOutputBufferImpl(int, int, CharsetEncoder,
96       *     ByteBufferAllocator)}
97       */
98      @Deprecated
99      public SessionOutputBufferImpl(
100             final int buffersize,
101             final int lineBuffersize,
102             final ByteBufferAllocator allocator,
103             final HttpParams params) {
104         super(buffersize, allocator);
105         this.lineBuffersize = Args.positive(lineBuffersize, "Line buffer size");
106         final String charsetName = (String) params.getParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET);
107         final Charset charset = CharsetUtils.lookup(charsetName);
108         if (charset != null) {
109             this.charencoder = charset.newEncoder();
110             final CodingErrorAction a1 = (CodingErrorAction) params.getParameter(
111                     CoreProtocolPNames.HTTP_MALFORMED_INPUT_ACTION);
112             this.charencoder.onMalformedInput(a1 != null ? a1 : CodingErrorAction.REPORT);
113             final CodingErrorAction a2 = (CodingErrorAction) params.getParameter(
114                     CoreProtocolPNames.HTTP_UNMAPPABLE_INPUT_ACTION);
115             this.charencoder.onUnmappableCharacter(a2 != null? a2 : CodingErrorAction.REPORT);
116         } else {
117             this.charencoder = null;
118         }
119     }
120 
121     /**
122      * @deprecated (4.3) use
123      *   {@link SessionOutputBufferImpl#SessionOutputBufferImpl(int, int, Charset)}
124      */
125     @Deprecated
126     public SessionOutputBufferImpl(
127             final int buffersize,
128             final int linebuffersize,
129             final HttpParams params) {
130         this(buffersize, linebuffersize, HeapByteBufferAllocator.INSTANCE, params);
131     }
132 
133     /**
134      * @since 4.3
135      */
136     public SessionOutputBufferImpl(final int buffersize) {
137         this(buffersize, 256, null, HeapByteBufferAllocator.INSTANCE);
138     }
139 
140     /**
141      * @since 4.3
142      */
143     public SessionOutputBufferImpl(
144             final int buffersize,
145             final int linebuffersize,
146             final Charset charset) {
147         this(buffersize, linebuffersize,
148                 charset != null ? charset.newEncoder() : null, HeapByteBufferAllocator.INSTANCE);
149     }
150 
151     /**
152      * @since 4.3
153      */
154     public SessionOutputBufferImpl(
155             final int buffersize,
156             final int linebuffersize) {
157         this(buffersize, linebuffersize, null, HeapByteBufferAllocator.INSTANCE);
158     }
159 
160     public void reset(final HttpParams params) {
161         clear();
162     }
163 
164     @Override
165     public int flush(final WritableByteChannel channel) throws IOException {
166         Args.notNull(channel, "Channel");
167         setOutputMode();
168         return channel.write(this.buffer);
169     }
170 
171     @Override
172     public void write(final ByteBuffer src) {
173         if (src == null) {
174             return;
175         }
176         setInputMode();
177         final int requiredCapacity = this.buffer.position() + src.remaining();
178         ensureCapacity(requiredCapacity);
179         this.buffer.put(src);
180     }
181 
182     @Override
183     public void write(final ReadableByteChannel src) throws IOException {
184         if (src == null) {
185             return;
186         }
187         setInputMode();
188         src.read(this.buffer);
189     }
190 
191     private void write(final byte[] b) {
192         if (b == null) {
193             return;
194         }
195         setInputMode();
196         final int off = 0;
197         final int len = b.length;
198         final int requiredCapacity = this.buffer.position() + len;
199         ensureCapacity(requiredCapacity);
200         this.buffer.put(b, off, len);
201     }
202 
203     private void writeCRLF() {
204         write(CRLF);
205     }
206 
207     @Override
208     public void writeLine(final CharArrayBuffer linebuffer) throws CharacterCodingException {
209         if (linebuffer == null) {
210             return;
211         }
212         setInputMode();
213         // Do not bother if the buffer is empty
214         if (linebuffer.length() > 0 ) {
215             if (this.charencoder == null) {
216                 final int requiredCapacity = this.buffer.position() + linebuffer.length();
217                 ensureCapacity(requiredCapacity);
218                 if (this.buffer.hasArray()) {
219                     final byte[] b = this.buffer.array();
220                     final int len = linebuffer.length();
221                     final int off = this.buffer.position();
222                     for (int i = 0; i < len; i++) {
223                         b[off + i]  = (byte) linebuffer.charAt(i);
224                     }
225                     this.buffer.position(off + len);
226                 } else {
227                     for (int i = 0; i < linebuffer.length(); i++) {
228                         this.buffer.put((byte) linebuffer.charAt(i));
229                     }
230                 }
231             } else {
232                 if (this.charbuffer == null) {
233                     this.charbuffer = CharBuffer.allocate(this.lineBuffersize);
234                 }
235                 this.charencoder.reset();
236                 // transfer the string in small chunks
237                 int remaining = linebuffer.length();
238                 int offset = 0;
239                 while (remaining > 0) {
240                     int l = this.charbuffer.remaining();
241                     boolean eol = false;
242                     if (remaining <= l) {
243                         l = remaining;
244                         // terminate the encoding process
245                         eol = true;
246                     }
247                     this.charbuffer.put(linebuffer.buffer(), offset, l);
248                     this.charbuffer.flip();
249 
250                     boolean retry = true;
251                     while (retry) {
252                         final CoderResult result = this.charencoder.encode(this.charbuffer, this.buffer, eol);
253                         if (result.isError()) {
254                             result.throwException();
255                         }
256                         if (result.isOverflow()) {
257                             expand();
258                         }
259                         retry = !result.isUnderflow();
260                     }
261                     this.charbuffer.compact();
262                     offset += l;
263                     remaining -= l;
264                 }
265                 // flush the encoder
266                 boolean retry = true;
267                 while (retry) {
268                     final CoderResult result = this.charencoder.flush(this.buffer);
269                     if (result.isError()) {
270                         result.throwException();
271                     }
272                     if (result.isOverflow()) {
273                         expand();
274                     }
275                     retry = !result.isUnderflow();
276                 }
277             }
278         }
279         writeCRLF();
280     }
281 
282     @Override
283     public void writeLine(final String s) throws IOException {
284         if (s == null) {
285             return;
286         }
287         if (s.length() > 0) {
288             final CharArrayBuffer tmp = new CharArrayBuffer(s.length());
289             tmp.append(s);
290             writeLine(tmp);
291         } else {
292             write(CRLF);
293         }
294     }
295 
296 }