001    /*
002     * Copyright (C) 2010 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    
020    package org.crsh.util;
021    
022    import java.io.IOException;
023    import java.io.InputStream;
024    
025    /**
026     * A stream that reads a portion of a delegate input stream.
027     * The impl is very basic and could be improved but it is enough at the moment.
028     *
029     * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
030     * @version $Revision$
031     */
032    public class SubInputStream extends InputStream {
033    
034      /** . */
035      private final InputStream in;
036    
037      /** . */
038      private final long length;
039    
040      /** . */
041      private long count;
042    
043      public SubInputStream(InputStream in, long length) {
044        if (in == null) {
045          throw new NullPointerException("Stream cannot be null");
046        }
047        if (length < 0) {
048          throw new IllegalArgumentException("Length cannot be negative");
049        }
050    
051        //
052        this.in = in ;
053        this.length = length;
054        this.count = 0;
055      }
056    
057      @Override
058      public int read() throws IOException {
059        if (count < length) {
060          int value = in.read();
061          count++;
062          return value;
063        } else {
064          return -1;
065        }
066      }
067    }