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
018package org.apache.commons.net.io;
019
020import java.io.FilterInputStream;
021import java.io.IOException;
022import java.io.InputStream;
023import java.net.Socket;
024
025/***
026 * This class wraps an input stream, storing a reference to its originating
027 * socket.  When the stream is closed, it will also close the socket
028 * immediately afterward.  This class is useful for situations where you
029 * are dealing with a stream originating from a socket, but do not have
030 * a reference to the socket, and want to make sure it closes when the
031 * stream closes.
032 *
033 *
034 * @see SocketOutputStream
035 ***/
036
037public class SocketInputStream extends FilterInputStream
038{
039    private final Socket __socket;
040
041    /***
042     * Creates a SocketInputStream instance wrapping an input stream and
043     * storing a reference to a socket that should be closed on closing
044     * the stream.
045     *
046     * @param socket  The socket to close on closing the stream.
047     * @param stream  The input stream to wrap.
048     ***/
049    public SocketInputStream(Socket socket, InputStream stream)
050    {
051        super(stream);
052        __socket = socket;
053    }
054
055    /***
056     * Closes the stream and immediately afterward closes the referenced
057     * socket.
058     *
059     * @throws IOException  If there is an error in closing the stream
060     *                         or socket.
061     ***/
062    @Override
063    public void close() throws IOException
064    {
065        super.close();
066        __socket.close();
067    }
068}