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.hc.core5.http.impl.nio;
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.hc.core5.http.impl.BasicHttpTransportMetrics;
36  import org.apache.hc.core5.http.nio.FileContentEncoder;
37  import org.apache.hc.core5.http.nio.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 implements FileContentEncoder {
52  
53      private final int fragHint;
54  
55      /**
56       * @since 4.3
57       *
58       * @param channel underlying channel.
59       * @param buffer  session buffer.
60       * @param metrics transport metrics.
61       * @param chunkSizeHint fragment size hint defining an minimal size of a fragment
62       *   that should be written out directly to the channel bypassing the session buffer.
63       *   Value {@code 0} disables fragment buffering.
64       */
65      public IdentityEncoder(
66              final WritableByteChannel channel,
67              final SessionOutputBuffer buffer,
68              final BasicHttpTransportMetrics metrics,
69              final int chunkSizeHint) {
70          super(channel, buffer, metrics);
71          this.fragHint = chunkSizeHint > 0 ? chunkSizeHint : 0;
72      }
73  
74      public IdentityEncoder(
75              final WritableByteChannel channel,
76              final SessionOutputBuffer buffer,
77              final BasicHttpTransportMetrics metrics) {
78          this(channel, buffer, metrics, 0);
79      }
80  
81      @Override
82      public int write(final ByteBuffer src) throws IOException {
83          if (src == null) {
84              return 0;
85          }
86          assertNotCompleted();
87  
88          int total = 0;
89          while (src.hasRemaining()) {
90              if (this.buffer.hasData() || this.fragHint > 0) {
91                  if (src.remaining() <= this.fragHint) {
92                      final int capacity = this.fragHint - this.buffer.length();
93                      if (capacity > 0) {
94                          final int limit = Math.min(capacity, src.remaining());
95                          final int bytesWritten = writeToBuffer(src, limit);
96                          total += bytesWritten;
97                      }
98                  }
99              }
100             if (this.buffer.hasData()) {
101                 if (this.buffer.length() >= this.fragHint || src.hasRemaining()) {
102                     final int bytesWritten = flushToChannel();
103                     if (bytesWritten == 0) {
104                         break;
105                     }
106                 }
107             }
108             if (!this.buffer.hasData() && src.remaining() > this.fragHint) {
109                 final int bytesWritten = writeToChannel(src);
110                 total += bytesWritten;
111                 if (bytesWritten == 0) {
112                     break;
113                 }
114             }
115         }
116         return total;
117     }
118 
119     @Override
120     public long transfer(
121             final FileChannel src,
122             final long position,
123             final long count) throws IOException {
124 
125         if (src == null) {
126             return 0;
127         }
128         assertNotCompleted();
129 
130         flushToChannel();
131         if (this.buffer.hasData()) {
132             return 0;
133         }
134 
135         final long bytesWritten = src.transferTo(position, count, this.channel);
136         if (bytesWritten > 0) {
137             this.metrics.incrementBytesTransferred(bytesWritten);
138         }
139         return bytesWritten;
140     }
141 
142     @Override
143     public String toString() {
144         final StringBuilder sb = new StringBuilder();
145         sb.append("[identity; completed: ");
146         sb.append(isCompleted());
147         sb.append("]");
148         return sb.toString();
149     }
150 
151 }