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  package org.apache.hc.core5.http.nio.entity;
28  
29  import java.io.IOException;
30  import java.nio.ByteBuffer;
31  import java.util.Set;
32  
33  import org.apache.hc.core5.http.ContentType;
34  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
35  import org.apache.hc.core5.http.nio.DataStreamChannel;
36  import org.apache.hc.core5.http.nio.StreamChannel;
37  import org.apache.hc.core5.util.Args;
38  
39  /**
40   * Abstract binary entity content producer.
41   *
42   * @since 5.0
43   */
44  public abstract class AbstractBinAsyncEntityProducer implements AsyncEntityProducer {
45  
46      private final ByteBuffer bytebuf;
47      private final int fragmentSizeHint;
48      private final ContentType contentType;
49  
50      private volatile boolean endStream;
51  
52      public AbstractBinAsyncEntityProducer(
53              final int bufferSize,
54              final int fragmentSizeHint,
55              final ContentType contentType) {
56          Args.positive(bufferSize, "Buffer size");
57          this.bytebuf = ByteBuffer.allocate(bufferSize);
58          this.fragmentSizeHint = fragmentSizeHint >= 0 ? fragmentSizeHint : bufferSize / 2;
59          this.contentType = contentType;
60      }
61  
62      /**
63       * Triggered to signal the ability of the underlying byte channel
64       * to accept more data. The data producer can choose to write data
65       * immediately inside the call or asynchronously at some later point.
66       *
67       * @param channel the data channel capable to accepting more data.
68       */
69      protected abstract void produceData(StreamChannel<ByteBuffer> channel) throws IOException;
70  
71      @Override
72      public final String getContentType() {
73          return contentType != null ? contentType.toString() : null;
74      }
75  
76      @Override
77      public String getContentEncoding() {
78          return null;
79      }
80  
81      @Override
82      public boolean isChunked() {
83          return false;
84      }
85  
86      @Override
87      public Set<String> getTrailerNames() {
88          return null;
89      }
90  
91      @Override
92      public final void produce(final DataStreamChannel channel) throws IOException {
93          produceData(new StreamChannel<ByteBuffer>() {
94  
95              @Override
96              public int write(final ByteBuffer src) throws IOException {
97                  Args.notNull(src, "Buffer");
98                  final int chunk = src.remaining();
99                  if (chunk == 0) {
100                     return 0;
101                 }
102                 if (bytebuf.remaining() >= chunk) {
103                     bytebuf.put(src);
104                     return chunk;
105                 }
106                 int totalBytesWritten = 0;
107                 if (!bytebuf.hasRemaining() || bytebuf.position() >= fragmentSizeHint) {
108                     bytebuf.flip();
109                     final int bytesWritten = channel.write(bytebuf);
110                     bytebuf.compact();
111                     totalBytesWritten += bytesWritten;
112                 }
113                 if (bytebuf.position() == 0) {
114                     final int bytesWritten = channel.write(src);
115                     totalBytesWritten += bytesWritten;
116                 }
117                 return totalBytesWritten;
118             }
119 
120             @Override
121             public void endStream() throws IOException {
122                 endStream = true;
123             }
124 
125         });
126 
127         if (endStream || !bytebuf.hasRemaining() || bytebuf.position() >= fragmentSizeHint) {
128             bytebuf.flip();
129             channel.write(bytebuf);
130             bytebuf.compact();
131         }
132         if (bytebuf.position() == 0 && endStream) {
133             channel.endStream();
134         }
135     }
136 
137 }