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 */
017package org.apache.commons.io.input;
018
019import static org.apache.commons.io.IOUtils.EOF;
020
021import java.io.IOException;
022import java.io.InputStream;
023
024/**
025 * Proxy stream that closes and discards the underlying stream as soon as the end of input has been reached or when the stream is explicitly closed. Not even a
026 * reference to the underlying stream is kept after it has been closed, so any allocated in-memory buffers can be freed even if the client application still
027 * keeps a reference to the proxy stream.
028 * <p>
029 * This class is typically used to release any resources related to an open stream as soon as possible even if the client application (by not explicitly closing
030 * the stream when no longer needed) or the underlying stream (by not releasing resources once the last byte has been read) do not do that.
031 * </p>
032 * <p>
033 * To build an instance, use {@link Builder}.
034 * </p>
035 *
036 * @since 1.4
037 * @see Builder
038 */
039public class AutoCloseInputStream extends ProxyInputStream {
040
041    // @formatter:off
042    /**
043     * Builds a new {@link AutoCloseInputStream} instance.
044     *
045     * <p>
046     * For example:
047     * </p>
048     * <pre>{@code
049     * AutoCloseInputStream s = AutoCloseInputStream.builder()
050     *   .setPath(path)
051     *   .get();}
052     * </pre>
053     * <pre>{@code
054     * AutoCloseInputStream s = AutoCloseInputStream.builder()
055     *   .setInputStream(inputStream)
056     *   .get();}
057     * </pre>
058     *
059     * @see #get()
060     * @since 2.13.0
061     */
062    // @formatter:on
063    public static class Builder extends AbstractBuilder<AutoCloseInputStream, Builder> {
064
065        /**
066         * Builds a new {@link AutoCloseInputStream}.
067         * <p>
068         * You must set input that supports {@link #getInputStream()}, otherwise, this method throws an exception.
069         * </p>
070         * <p>
071         * This builder use the following aspects:
072         * </p>
073         * <ul>
074         * <li>{@link #getInputStream()}</li>
075         * </ul>
076         *
077         * @return a new instance.
078         * @throws IllegalStateException         if the {@code origin} is {@code null}.
079         * @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
080         * @throws IOException                   if an I/O error occurs.
081         * @see #getInputStream()
082         */
083        @Override
084        public AutoCloseInputStream get() throws IOException {
085            return new AutoCloseInputStream(this);
086        }
087
088    }
089
090    /**
091     * Constructs a new {@link Builder}.
092     *
093     * @return a new {@link Builder}.
094     * @since 2.12.0
095     */
096    public static Builder builder() {
097        return new Builder();
098    }
099
100    private AutoCloseInputStream(final Builder builder) throws IOException {
101        super(builder);
102    }
103
104    /**
105     * Constructs an automatically closing proxy for the given input stream.
106     *
107     * @param in underlying input stream
108     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
109     */
110    @SuppressWarnings("resource") // ClosedInputStream.nonNull() doesn't allocate
111    @Deprecated
112    public AutoCloseInputStream(final InputStream in) {
113        super(ClosedInputStream.ifNull(in));
114    }
115
116    /**
117     * Automatically closes the stream if the end of stream was reached.
118     *
119     * @param n number of bytes read, or -1 if no more bytes are available
120     * @throws IOException if the stream could not be closed
121     * @since 2.0
122     */
123    @Override
124    protected void afterRead(final int n) throws IOException {
125        if (n == EOF) {
126            close();
127        }
128        super.afterRead(n);
129    }
130
131    /**
132     * Closes the underlying input stream and replaces the reference to it with a {@link ClosedInputStream} instance.
133     * <p>
134     * This method is automatically called by the read methods when the end of input has been reached.
135     * </p>
136     * <p>
137     * Note that it is safe to call this method any number of times. The original underlying input stream is closed and discarded only once when this method is
138     * first called.
139     * </p>
140     *
141     * @throws IOException if the underlying input stream cannot be closed
142     */
143    @Override
144    public void close() throws IOException {
145        super.close();
146        in = ClosedInputStream.INSTANCE;
147    }
148
149    /**
150     * Ensures that the stream is closed before it gets garbage-collected. As mentioned in {@link #close()}, this is a no-op if the stream has already been
151     * closed.
152     *
153     * @throws Throwable if an error occurs
154     */
155    @Override
156    protected void finalize() throws Throwable {
157        close();
158        super.finalize();
159    }
160
161}