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.nio.entity;
029
030import java.io.IOException;
031import java.io.InputStream;
032
033import org.apache.http.io.BufferInfo;
034import org.apache.http.nio.util.ContentInputBuffer;
035import org.apache.http.util.Args;
036
037/**
038 * {@link InputStream} adaptor for {@link ContentInputBuffer}.
039 *
040 * @since 4.0
041 */
042public class ContentInputStream extends InputStream {
043
044    private final ContentInputBuffer buffer;
045
046    public ContentInputStream(final ContentInputBuffer buffer) {
047        super();
048        Args.notNull(buffer, "Input buffer");
049        this.buffer = buffer;
050    }
051
052    @Override
053    public int available() throws IOException {
054        if (this.buffer instanceof BufferInfo) {
055            return ((BufferInfo) this.buffer).length();
056        } else {
057            return super.available();
058        }
059    }
060
061    @Override
062    public int read(final byte[] b, final int off, final int len) throws IOException {
063        return this.buffer.read(b, off, len);
064    }
065
066    @Override
067    public int read(final byte[] b) throws IOException {
068        if (b == null) {
069            return 0;
070        }
071        return this.buffer.read(b, 0, b.length);
072    }
073
074    @Override
075    public int read() throws IOException {
076        return this.buffer.read();
077    }
078
079    @Override
080    public void close() throws IOException {
081        // read and discard the remainder of the message
082        final byte tmp[] = new byte[1024];
083        while (this.buffer.read(tmp, 0, tmp.length) >= 0) {
084        }
085        super.close();
086    }
087
088}