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.codecs;
29  
30  import java.io.IOException;
31  import java.nio.ByteBuffer;
32  import java.nio.channels.FileChannel;
33  import java.nio.channels.WritableByteChannel;
34  
35  import org.apache.http.annotation.NotThreadSafe;
36  import org.apache.http.impl.io.HttpTransportMetricsImpl;
37  import org.apache.http.nio.FileContentEncoder;
38  import org.apache.http.nio.reactor.SessionOutputBuffer;
39  
40  /**
41   * Content encoder that writes data without any transformation. The end of
42   * the content entity is demarcated by closing the underlying connection
43   * (EOF condition). Entities transferred using this input stream can be of
44   * unlimited length.
45   * <p>
46   * This decoder is optimized to transfer data directly from
47   * a {@link FileChannel} to the underlying I/O session's channel whenever
48   * possible avoiding intermediate buffering in the session buffer.
49   *
50   * @since 4.0
51   */
52  @NotThreadSafe
53  public class IdentityEncoder extends AbstractContentEncoder
54          implements FileContentEncoder {
55  
56      private final int fragHint;
57  
58      /**
59       * @since 4.3
60       *
61       * @param channel underlying channel.
62       * @param buffer  session buffer.
63       * @param metrics transport metrics.
64       * @param fragementSizeHint fragment size hint defining an minimal size of a fragment
65       *   that should be written out directly to the channel bypassing the session buffer.
66       *   Value <code>0</code> disables fragment buffering.
67       */
68      public IdentityEncoder(
69              final WritableByteChannel channel,
70              final SessionOutputBuffer buffer,
71              final HttpTransportMetricsImpl metrics,
72              final int fragementSizeHint) {
73          super(channel, buffer, metrics);
74          this.fragHint = fragementSizeHint > 0 ? fragementSizeHint : 0;
75      }
76  
77      public IdentityEncoder(
78              final WritableByteChannel channel,
79              final SessionOutputBuffer buffer,
80              final HttpTransportMetricsImpl metrics) {
81          this(channel, buffer, metrics, 0);
82      }
83  
84      @Override
85      public int write(final ByteBuffer src) throws IOException {
86          if (src == null) {
87              return 0;
88          }
89          assertNotCompleted();
90  
91          int total = 0;
92          while (src.hasRemaining()) {
93              if (this.buffer.hasData() || this.fragHint > 0) {
94                  if (src.remaining() <= this.fragHint) {
95                      final int capacity = this.fragHint - this.buffer.length();
96                      if (capacity > 0) {
97                          final int limit = Math.min(capacity, src.remaining());
98                          final int bytesWritten = writeToBuffer(src, limit);
99                          total += bytesWritten;
100                     }
101                 }
102             }
103             if (this.buffer.hasData()) {
104                 if (this.buffer.length() >= this.fragHint || src.hasRemaining()) {
105                     final int bytesWritten = flushToChannel();
106                     if (bytesWritten == 0) {
107                         break;
108                     }
109                 }
110             }
111             if (!this.buffer.hasData() && src.remaining() > this.fragHint) {
112                 final int bytesWritten = writeToChannel(src);
113                 total += bytesWritten;
114                 if (bytesWritten == 0) {
115                     break;
116                 }
117             }
118         }
119         return total;
120     }
121 
122     @Override
123     public long transfer(
124             final FileChannel src,
125             final long position,
126             final long count) throws IOException {
127 
128         if (src == null) {
129             return 0;
130         }
131         assertNotCompleted();
132 
133         flushToChannel();
134         if (this.buffer.hasData()) {
135             return 0;
136         }
137 
138         final long bytesWritten = src.transferTo(position, count, this.channel);
139         if (bytesWritten > 0) {
140             this.metrics.incrementBytesTransferred(bytesWritten);
141         }
142         return bytesWritten;
143     }
144 
145     @Override
146     public String toString() {
147         final StringBuilder sb = new StringBuilder();
148         sb.append("[identity; completed: ");
149         sb.append(isCompleted());
150         sb.append("]");
151         return sb.toString();
152     }
153 
154 }