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