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</code> is not <code>null</code>.
76       * @param charencoder charencoder to be used for encoding HTTP protocol elements.
77       *   If <code>null</code> simple type cast will be used for char to byte conversion.
78       * @param allocator memory allocator.
79       *   If <code>null</code> {@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     public int flush(final WritableByteChannel channel) throws IOException {
165         Args.notNull(channel, "Channel");
166         setOutputMode();
167         return channel.write(this.buffer);
168     }
169 
170     public void write(final ByteBuffer src) {
171         if (src == null) {
172             return;
173         }
174         setInputMode();
175         final int requiredCapacity = this.buffer.position() + src.remaining();
176         ensureCapacity(requiredCapacity);
177         this.buffer.put(src);
178     }
179 
180     public void write(final ReadableByteChannel src) throws IOException {
181         if (src == null) {
182             return;
183         }
184         setInputMode();
185         src.read(this.buffer);
186     }
187 
188     private void write(final byte[] b) {
189         if (b == null) {
190             return;
191         }
192         setInputMode();
193         final int off = 0;
194         final int len = b.length;
195         final int requiredCapacity = this.buffer.position() + len;
196         ensureCapacity(requiredCapacity);
197         this.buffer.put(b, off, len);
198     }
199 
200     private void writeCRLF() {
201         write(CRLF);
202     }
203 
204     public void writeLine(final CharArrayBuffer linebuffer) throws CharacterCodingException {
205         if (linebuffer == null) {
206             return;
207         }
208         setInputMode();
209         // Do not bother if the buffer is empty
210         if (linebuffer.length() > 0 ) {
211             if (this.charencoder == null) {
212                 final int requiredCapacity = this.buffer.position() + linebuffer.length();
213                 ensureCapacity(requiredCapacity);
214                 if (this.buffer.hasArray()) {
215                     final byte[] b = this.buffer.array();
216                     final int len = linebuffer.length();
217                     final int off = this.buffer.position();
218                     for (int i = 0; i < len; i++) {
219                         b[off + i]  = (byte) linebuffer.charAt(i);
220                     }
221                     this.buffer.position(off + len);
222                 } else {
223                     for (int i = 0; i < linebuffer.length(); i++) {
224                         this.buffer.put((byte) linebuffer.charAt(i));
225                     }
226                 }
227             } else {
228                 if (this.charbuffer == null) {
229                     this.charbuffer = CharBuffer.allocate(this.lineBuffersize);
230                 }
231                 this.charencoder.reset();
232                 // transfer the string in small chunks
233                 int remaining = linebuffer.length();
234                 int offset = 0;
235                 while (remaining > 0) {
236                     int l = this.charbuffer.remaining();
237                     boolean eol = false;
238                     if (remaining <= l) {
239                         l = remaining;
240                         // terminate the encoding process
241                         eol = true;
242                     }
243                     this.charbuffer.put(linebuffer.buffer(), offset, l);
244                     this.charbuffer.flip();
245 
246                     boolean retry = true;
247                     while (retry) {
248                         final CoderResult result = this.charencoder.encode(this.charbuffer, this.buffer, eol);
249                         if (result.isError()) {
250                             result.throwException();
251                         }
252                         if (result.isOverflow()) {
253                             expand();
254                         }
255                         retry = !result.isUnderflow();
256                     }
257                     this.charbuffer.compact();
258                     offset += l;
259                     remaining -= l;
260                 }
261                 // flush the encoder
262                 boolean retry = true;
263                 while (retry) {
264                     final CoderResult result = this.charencoder.flush(this.buffer);
265                     if (result.isError()) {
266                         result.throwException();
267                     }
268                     if (result.isOverflow()) {
269                         expand();
270                     }
271                     retry = !result.isUnderflow();
272                 }
273             }
274         }
275         writeCRLF();
276     }
277 
278     public void writeLine(final String s) throws IOException {
279         if (s == null) {
280             return;
281         }
282         if (s.length() > 0) {
283             final CharArrayBuffer tmp = new CharArrayBuffer(s.length());
284             tmp.append(s);
285             writeLine(tmp);
286         } else {
287             write(CRLF);
288         }
289     }
290 
291 }