001/*
002 * ====================================================================
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *   http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing,
014 * software distributed under the License is distributed on an
015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
016 * KIND, either express or implied.  See the License for the
017 * specific language governing permissions and limitations
018 * under the License.
019 * ====================================================================
020 *
021 * This software consists of voluntary contributions made by many
022 * individuals on behalf of the Apache Software Foundation.  For more
023 * information on the Apache Software Foundation, please see
024 * <http://www.apache.org/>.
025 *
026 */
027
028package org.apache.http.impl.nio.codecs;
029
030import java.io.IOException;
031import java.nio.ByteBuffer;
032import java.nio.channels.FileChannel;
033import java.nio.channels.ReadableByteChannel;
034
035import org.apache.http.impl.io.HttpTransportMetricsImpl;
036import org.apache.http.nio.FileContentDecoder;
037import org.apache.http.nio.reactor.SessionInputBuffer;
038import org.apache.http.util.Args;
039
040/**
041 * Content decoder that reads data without any transformation. The end of the
042 * content entity is delineated by closing the underlying connection
043 * (EOF condition). Entities transferred using this input stream can be of
044 * unlimited length.
045 * <p>
046 * This decoder is optimized to transfer data directly from the underlying
047 * I/O session's channel to a {@link FileChannel}, whenever
048 * possible avoiding intermediate buffering in the session buffer.
049 *
050 * @since 4.0
051 */
052public class IdentityDecoder extends AbstractContentDecoder
053        implements FileContentDecoder {
054
055    public IdentityDecoder(
056            final ReadableByteChannel channel,
057            final SessionInputBuffer buffer,
058            final HttpTransportMetricsImpl metrics) {
059        super(channel, buffer, metrics);
060    }
061
062    /**
063     * Sets the completed status of this decoder. Normally this is not necessary
064     * (the decoder will automatically complete when the underlying channel
065     * returns EOF). It is useful to mark the decoder as completed if you have
066     * some other means to know all the necessary data has been read and want to
067     * reuse the underlying connection for more messages.
068     */
069    public void setCompleted(final boolean completed) {
070        this.completed = completed;
071    }
072
073    @Override
074    public int read(final ByteBuffer dst) throws IOException {
075        Args.notNull(dst, "Byte buffer");
076        if (this.completed) {
077            return -1;
078        }
079
080        final int bytesRead;
081        if (this.buffer.hasData()) {
082            bytesRead = this.buffer.read(dst);
083        } else {
084            bytesRead = readFromChannel(dst);
085        }
086        if (bytesRead == -1) {
087            this.completed = true;
088        }
089        return bytesRead;
090    }
091
092    @Override
093    public long transfer(
094            final FileChannel dst,
095            final long position,
096            final long count) throws IOException {
097
098        if (dst == null) {
099            return 0;
100        }
101        if (this.completed) {
102            return 0;
103        }
104
105        long bytesRead;
106        if (this.buffer.hasData()) {
107            dst.position(position);
108            bytesRead = this.buffer.read(dst);
109        } else {
110            if (this.channel.isOpen()) {
111                if (position > dst.size()) {
112                    throw new IOException("Position past end of file [" + position +
113                            " > " + dst.size() + "]");
114                }
115                bytesRead = dst.transferFrom(this.channel, position, count);
116                if (count > 0 && bytesRead == 0) {
117                    bytesRead = this.buffer.fill(this.channel);
118                }
119            } else {
120                bytesRead = -1;
121            }
122            if (bytesRead > 0) {
123                this.metrics.incrementBytesTransferred(bytesRead);
124            }
125        }
126        if (bytesRead == -1) {
127            this.completed = true;
128        }
129        return bytesRead;
130    }
131
132    @Override
133    public String toString() {
134        final StringBuilder sb = new StringBuilder();
135        sb.append("[identity; completed: ");
136        sb.append(this.completed);
137        sb.append("]");
138        return sb.toString();
139    }
140
141}