001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.activemq.transport.nio;
018    
019    import java.io.IOException;
020    import java.io.InputStream;
021    import java.nio.BufferUnderflowException;
022    import java.nio.ByteBuffer;
023    
024    /**
025     * An optimized buffered input stream for Tcp
026     * 
027     * @version $Revision: 1.1.1.1 $
028     */
029    public class NIOInputStream extends InputStream {
030    
031        protected int count;
032        protected int position;
033        private final ByteBuffer in;
034    
035        public NIOInputStream(ByteBuffer in) {
036            this.in = in;
037        }
038    
039        public int read() throws IOException {
040            try {
041                int rc = in.get() & 0xff;
042                return rc;
043            } catch (BufferUnderflowException e) {
044                return -1;
045            }
046        }
047    
048        public int read(byte b[], int off, int len) throws IOException {
049            if (in.hasRemaining()) {
050                int rc = Math.min(len, in.remaining());
051                in.get(b, off, rc);
052                return rc;
053            } else {
054                return len == 0 ? 0 : -1;
055            }
056        }
057    
058        public long skip(long n) throws IOException {
059            int rc = Math.min((int)n, in.remaining());
060            in.position(in.position() + rc);
061            return rc;
062        }
063    
064        public int available() throws IOException {
065            return in.remaining();
066        }
067    
068        public boolean markSupported() {
069            return false;
070        }
071    
072        public void close() throws IOException {
073        }
074    }