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         * Constructs a new builder of {@link AutoCloseInputStream}.
067         */
068        public Builder() {
069            // empty
070        }
071
072        /**
073         * Builds a new {@link AutoCloseInputStream}.
074         * <p>
075         * You must set an aspect that supports {@link #getInputStream()}, otherwise, this method throws an exception.
076         * </p>
077         * <p>
078         * This builder uses the following aspects:
079         * </p>
080         * <ul>
081         * <li>{@link #getInputStream()} gets the target aspect.</li>
082         * </ul>
083         *
084         * @return a new instance.
085         * @throws IllegalStateException         if the {@code origin} is {@code null}.
086         * @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
087         * @throws IOException                   if an I/O error occurs converting to an {@link InputStream} using {@link #getInputStream()}.
088         * @see #getInputStream()
089         * @see #getUnchecked()
090         */
091        @Override
092        public AutoCloseInputStream get() throws IOException {
093            return new AutoCloseInputStream(this);
094        }
095
096    }
097
098    /**
099     * Constructs a new {@link Builder}.
100     *
101     * @return a new {@link Builder}.
102     * @since 2.12.0
103     */
104    public static Builder builder() {
105        return new Builder();
106    }
107
108    private AutoCloseInputStream(final Builder builder) throws IOException {
109        super(builder);
110    }
111
112    /**
113     * Constructs an automatically closing proxy for the given input stream.
114     *
115     * @param in underlying input stream
116     * @deprecated Use {@link #builder()}, {@link Builder}, and {@link Builder#get()}
117     */
118    @SuppressWarnings("resource") // ClosedInputStream.nonNull() doesn't allocate
119    @Deprecated
120    public AutoCloseInputStream(final InputStream in) {
121        super(ClosedInputStream.ifNull(in));
122    }
123
124    /**
125     * Automatically closes the stream if the end of stream was reached.
126     *
127     * @param n number of bytes read, or -1 if no more bytes are available
128     * @throws IOException if the stream could not be closed
129     * @since 2.0
130     */
131    @Override
132    protected void afterRead(final int n) throws IOException {
133        if (n == EOF) {
134            close();
135        }
136        super.afterRead(n);
137    }
138
139    /**
140     * Closes the underlying input stream and replaces the reference to it with a {@link ClosedInputStream} instance.
141     * <p>
142     * This method is automatically called by the read methods when the end of input has been reached.
143     * </p>
144     * <p>
145     * 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
146     * first called.
147     * </p>
148     *
149     * @throws IOException if the underlying input stream cannot be closed
150     */
151    @Override
152    public void close() throws IOException {
153        super.close();
154        in = ClosedInputStream.INSTANCE;
155    }
156
157    /**
158     * 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
159     * closed.
160     *
161     * @throws Throwable if an error occurs
162     */
163    @Override
164    protected void finalize() throws Throwable {
165        close();
166        super.finalize();
167    }
168
169}