BoundedInputStream.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.io.input;

  18. import static org.apache.commons.io.IOUtils.EOF;

  19. import java.io.IOException;
  20. import java.io.InputStream;

  21. import org.apache.commons.io.IOUtils;
  22. import org.apache.commons.io.function.IOBiConsumer;

  23. //@formatter:off
  24. /**
  25.  * Reads bytes up to a maximum count and stops once reached.
  26.  * <p>
  27.  * To build an instance: Use the {@link #builder()} to access all features.
  28.  * </p>
  29.  * <p>
  30.  * By default, a {@link BoundedInputStream} is <em>unbound</em>; so make sure to call {@link AbstractBuilder#setMaxCount(long)}.
  31.  * </p>
  32.  * <p>
  33.  * You can find out how many bytes this stream has seen so far by calling {@link BoundedInputStream#getCount()}. This value reflects bytes read and skipped.
  34.  * </p>
  35.  * <h2>Using a ServletInputStream</h2>
  36.  * <p>
  37.  * A {@code ServletInputStream} can block if you try to read content that isn't there
  38.  * because it doesn't know whether the content hasn't arrived yet or whether the content has finished. Initialize an {@link BoundedInputStream} with the
  39.  * {@code Content-Length} sent in the {@code ServletInputStream}'s header, this stop it from blocking, providing it's been sent with a correct content
  40.  * length in the first place.
  41.  * </p>
  42.  * <h2>Using NIO</h2>
  43.  * <pre>{@code
  44.  * BoundedInputStream s = BoundedInputStream.builder()
  45.  *   .setPath(Paths.get("MyFile.xml"))
  46.  *   .setMaxCount(1024)
  47.  *   .setPropagateClose(false)
  48.  *   .get();
  49.  * }
  50.  * </pre>
  51.  * <h2>Using IO</h2>
  52.  * <pre>{@code
  53.  * BoundedInputStream s = BoundedInputStream.builder()
  54.  *   .setFile(new File("MyFile.xml"))
  55.  *   .setMaxCount(1024)
  56.  *   .setPropagateClose(false)
  57.  *   .get();
  58.  * }
  59.  * </pre>
  60.  * <h2>Counting Bytes</h2>
  61.  * <p>You can set the running count when building, which is most useful when starting from another stream:
  62.  * <pre>{@code
  63.  * InputStream in = ...;
  64.  * BoundedInputStream s = BoundedInputStream.builder()
  65.  *   .setInputStream(in)
  66.  *   .setCount(12)
  67.  *   .setMaxCount(1024)
  68.  *   .setPropagateClose(false)
  69.  *   .get();
  70.  * }
  71.  * </pre>
  72.  * <h2>Listening for the max count reached</h2>
  73.  * <pre>{@code
  74.  * BoundedInputStream s = BoundedInputStream.builder()
  75.  *   .setPath(Paths.get("MyFile.xml"))
  76.  *   .setMaxCount(1024)
  77.  *   .setOnMaxCount((max, count) -> System.out.printf("Max count %,d reached with a last read count of %,d%n", max, count))
  78.  *   .get();
  79.  * }
  80.  * </pre>
  81.  * @see Builder
  82.  * @since 2.0
  83.  */
  84. //@formatter:on
  85. public class BoundedInputStream extends ProxyInputStream {

  86.     /**
  87.      * For subclassing builders from {@link BoundedInputStream} subclassses.
  88.      *
  89.      * @param <T> The subclass.
  90.      */
  91.     abstract static class AbstractBuilder<T extends AbstractBuilder<T>> extends ProxyInputStream.AbstractBuilder<BoundedInputStream, T> {

  92.         /** The current count of bytes counted. */
  93.         private long count;

  94.         /** The max count of bytes to read. */
  95.         private long maxCount = EOF;

  96.         private IOBiConsumer<Long, Long> onMaxCount = IOBiConsumer.noop();

  97.         /** Flag if {@link #close()} should be propagated, {@code true} by default. */
  98.         private boolean propagateClose = true;

  99.         long getCount() {
  100.             return count;
  101.         }

  102.         long getMaxCount() {
  103.             return maxCount;
  104.         }

  105.         IOBiConsumer<Long, Long> getOnMaxCount() {
  106.             return onMaxCount;
  107.         }

  108.         boolean isPropagateClose() {
  109.             return propagateClose;
  110.         }

  111.         /**
  112.          * Sets the current number of bytes counted.
  113.          * <p>
  114.          * Useful when building from another stream to carry forward a read count.
  115.          * </p>
  116.          * <p>
  117.          * Default is {@code 0}, negative means 0.
  118.          * </p>
  119.          *
  120.          * @param count The current number of bytes counted.
  121.          * @return {@code this} instance.
  122.          */
  123.         public T setCount(final long count) {
  124.             this.count = Math.max(0, count);
  125.             return asThis();
  126.         }

  127.         /**
  128.          * Sets the maximum number of bytes to return.
  129.          * <p>
  130.          * Default is {@value IOUtils#EOF}, negative means unbound.
  131.          * </p>
  132.          *
  133.          * @param maxCount The maximum number of bytes to return, negative means unbound.
  134.          * @return {@code this} instance.
  135.          */
  136.         public T setMaxCount(final long maxCount) {
  137.             this.maxCount = Math.max(EOF, maxCount);
  138.             return asThis();
  139.         }

  140.         /**
  141.          * Sets the default {@link BoundedInputStream#onMaxLength(long, long)} behavior, {@code null} resets to a NOOP.
  142.          * <p>
  143.          * The first Long is the max count of bytes to read. The second Long is the count of bytes read.
  144.          * </p>
  145.          * <p>
  146.          * This does <em>not</em> override a {@code BoundedInputStream} subclass' implementation of the {@link BoundedInputStream#onMaxLength(long, long)}
  147.          * method.
  148.          * </p>
  149.          *
  150.          * @param onMaxCount the {@link ProxyInputStream#afterRead(int)} behavior.
  151.          * @return this instance.
  152.          * @since 2.18.0
  153.          */
  154.         public T setOnMaxCount(final IOBiConsumer<Long, Long> onMaxCount) {
  155.             this.onMaxCount = onMaxCount != null ? onMaxCount : IOBiConsumer.noop();
  156.             return asThis();
  157.         }

  158.         /**
  159.          * Sets whether the {@link #close()} method should propagate to the underling {@link InputStream}.
  160.          * <p>
  161.          * Default is {@code true}.
  162.          * </p>
  163.          *
  164.          * @param propagateClose {@code true} if calling {@link #close()} propagates to the {@code close()} method of the underlying stream or {@code false} if
  165.          *                       it does not.
  166.          * @return {@code this} instance.
  167.          */
  168.         public T setPropagateClose(final boolean propagateClose) {
  169.             this.propagateClose = propagateClose;
  170.             return asThis();
  171.         }

  172.     }

  173.     //@formatter:off
  174.     /**
  175.      * Builds a new {@link BoundedInputStream}.
  176.      * <p>
  177.      * By default, a {@link BoundedInputStream} is <em>unbound</em>; so make sure to call {@link AbstractBuilder#setMaxCount(long)}.
  178.      * </p>
  179.      * <p>
  180.      * You can find out how many bytes this stream has seen so far by calling {@link BoundedInputStream#getCount()}. This value reflects bytes read and skipped.
  181.      * </p>
  182.      * <h2>Using a ServletInputStream</h2>
  183.      * <p>
  184.      * A {@code ServletInputStream} can block if you try to read content that isn't there
  185.      * because it doesn't know whether the content hasn't arrived yet or whether the content has finished. Initialize an {@link BoundedInputStream} with the
  186.      * {@code Content-Length} sent in the {@code ServletInputStream}'s header, this stop it from blocking, providing it's been sent with a correct content
  187.      * length in the first place.
  188.      * </p>
  189.      * <h2>Using NIO</h2>
  190.      * <pre>{@code
  191.      * BoundedInputStream s = BoundedInputStream.builder()
  192.      *   .setPath(Paths.get("MyFile.xml"))
  193.      *   .setMaxCount(1024)
  194.      *   .setPropagateClose(false)
  195.      *   .get();
  196.      * }
  197.      * </pre>
  198.      * <h2>Using IO</h2>
  199.      * <pre>{@code
  200.      * BoundedInputStream s = BoundedInputStream.builder()
  201.      *   .setFile(new File("MyFile.xml"))
  202.      *   .setMaxCount(1024)
  203.      *   .setPropagateClose(false)
  204.      *   .get();
  205.      * }
  206.      * </pre>
  207.      * <h2>Counting Bytes</h2>
  208.      * <p>You can set the running count when building, which is most useful when starting from another stream:
  209.      * <pre>{@code
  210.      * InputStream in = ...;
  211.      * BoundedInputStream s = BoundedInputStream.builder()
  212.      *   .setInputStream(in)
  213.      *   .setCount(12)
  214.      *   .setMaxCount(1024)
  215.      *   .setPropagateClose(false)
  216.      *   .get();
  217.      * }
  218.      * </pre>
  219.      *
  220.      * @see #get()
  221.      * @since 2.16.0
  222.      */
  223.     //@formatter:on
  224.     public static class Builder extends AbstractBuilder<Builder> {

  225.         /**
  226.          * Constructs a new builder of {@link BoundedInputStream}.
  227.          */
  228.         public Builder() {
  229.             // empty
  230.         }

  231.         /**
  232.          * Builds a new {@link BoundedInputStream}.
  233.          * <p>
  234.          * You must set an aspect that supports {@link #getInputStream()}, otherwise, this method throws an exception.
  235.          * </p>
  236.          * <p>
  237.          * If you start from an input stream, an exception can't be thrown, and you can call {@link #getUnchecked()} instead.
  238.          * </p>
  239.          * <p>
  240.          * This builder uses the following aspects:
  241.          * </p>
  242.          * <ul>
  243.          * <li>{@link #getInputStream()} gets the target aspect.</li>
  244.          * <li>{@link #getAfterRead()}</li>
  245.          * <li>{@link #getCount()}</li>
  246.          * <li>{@link #getMaxCount()}</li>
  247.          * <li>{@link #getOnMaxCount()}</li>
  248.          * <li>{@link #isPropagateClose()}</li>
  249.          * </ul>
  250.          *
  251.          * @return a new instance.
  252.          * @throws IllegalStateException         if the {@code origin} is {@code null}.
  253.          * @throws UnsupportedOperationException if the origin cannot be converted to an {@link InputStream}.
  254.          * @throws IOException                   if an I/O error occurs converting to an {@link InputStream} using {@link #getInputStream()}.
  255.          * @see #getInputStream()
  256.          * @see #getUnchecked()
  257.          */
  258.         @Override
  259.         public BoundedInputStream get() throws IOException {
  260.             return new BoundedInputStream(this);
  261.         }

  262.     }

  263.     /**
  264.      * Constructs a new {@link AbstractBuilder}.
  265.      *
  266.      * @return a new {@link AbstractBuilder}.
  267.      * @since 2.16.0
  268.      */
  269.     public static Builder builder() {
  270.         return new Builder();
  271.     }

  272.     /** The current count of bytes counted. */
  273.     private long count;

  274.     /** The current mark. */
  275.     private long mark;

  276.     /** The max count of bytes to read. */
  277.     private final long maxCount;

  278.     private final IOBiConsumer<Long, Long> onMaxCount;

  279.     /**
  280.      * Flag if close should be propagated.
  281.      *
  282.      * TODO Make final in 3.0.
  283.      */
  284.     private boolean propagateClose = true;

  285.     BoundedInputStream(final Builder builder) throws IOException {
  286.         super(builder);
  287.         this.count = builder.getCount();
  288.         this.maxCount = builder.getMaxCount();
  289.         this.propagateClose = builder.isPropagateClose();
  290.         this.onMaxCount = builder.getOnMaxCount();
  291.     }

  292.     /**
  293.      * Constructs a new {@link BoundedInputStream} that wraps the given input stream and is <em>unbounded</em>.
  294.      * <p>
  295.      * To build an instance: Use the {@link #builder()} to access all features.
  296.      * </p>
  297.      *
  298.      * @param in The wrapped input stream.
  299.      * @deprecated Use {@link AbstractBuilder#get()}.
  300.      */
  301.     @Deprecated
  302.     public BoundedInputStream(final InputStream in) {
  303.         this(in, EOF);
  304.     }

  305.     BoundedInputStream(final InputStream inputStream, final Builder builder) {
  306.         super(inputStream, builder);
  307.         this.count = builder.getCount();
  308.         this.maxCount = builder.getMaxCount();
  309.         this.propagateClose = builder.isPropagateClose();
  310.         this.onMaxCount = builder.getOnMaxCount();
  311.     }

  312.     /**
  313.      * Constructs a new {@link BoundedInputStream} that wraps the given input stream and limits it to a certain size.
  314.      *
  315.      * @param inputStream The wrapped input stream.
  316.      * @param maxCount    The maximum number of bytes to return, negative means unbound.
  317.      * @deprecated Use {@link AbstractBuilder#get()}.
  318.      */
  319.     @Deprecated
  320.     public BoundedInputStream(final InputStream inputStream, final long maxCount) {
  321.         // Some badly designed methods - e.g. the Servlet API - overload length
  322.         // such that "-1" means stream finished
  323.         this(inputStream, builder().setMaxCount(maxCount));
  324.     }

  325.     /**
  326.      * Adds the number of read bytes to the count.
  327.      *
  328.      * @param n number of bytes read, or -1 if no more bytes are available
  329.      * @throws IOException Not thrown here but subclasses may throw.
  330.      * @since 2.0
  331.      */
  332.     @Override
  333.     protected synchronized void afterRead(final int n) throws IOException {
  334.         if (n != EOF) {
  335.             count += n;
  336.         }
  337.         super.afterRead(n);
  338.     }

  339.     /**
  340.      * {@inheritDoc}
  341.      */
  342.     @Override
  343.     public int available() throws IOException {
  344.         if (isMaxCount()) {
  345.             onMaxLength(maxCount, getCount());
  346.             return 0;
  347.         }
  348.         return in.available();
  349.     }

  350.     /**
  351.      * Invokes the delegate's {@link InputStream#close()} method if {@link #isPropagateClose()} is {@code true}.
  352.      *
  353.      * @throws IOException if an I/O error occurs.
  354.      */
  355.     @Override
  356.     public void close() throws IOException {
  357.         if (propagateClose) {
  358.             super.close();
  359.         }
  360.     }

  361.     /**
  362.      * Gets the count of bytes read.
  363.      *
  364.      * @return The count of bytes read.
  365.      * @since 2.12.0
  366.      */
  367.     public synchronized long getCount() {
  368.         return count;
  369.     }

  370.     /**
  371.      * Gets the max count of bytes to read.
  372.      *
  373.      * @return The max count of bytes to read.
  374.      * @since 2.16.0
  375.      */
  376.     public long getMaxCount() {
  377.         return maxCount;
  378.     }

  379.     /**
  380.      * Gets the max count of bytes to read.
  381.      *
  382.      * @return The max count of bytes to read.
  383.      * @since 2.12.0
  384.      * @deprecated Use {@link #getMaxCount()}.
  385.      */
  386.     @Deprecated
  387.     public long getMaxLength() {
  388.         return maxCount;
  389.     }

  390.     /**
  391.      * Gets how many bytes remain to read.
  392.      *
  393.      * @return bytes how many bytes remain to read.
  394.      * @since 2.16.0
  395.      */
  396.     public long getRemaining() {
  397.         return Math.max(0, getMaxCount() - getCount());
  398.     }

  399.     private boolean isMaxCount() {
  400.         return maxCount >= 0 && getCount() >= maxCount;
  401.     }

  402.     /**
  403.      * Tests whether the {@link #close()} method should propagate to the underling {@link InputStream}.
  404.      *
  405.      * @return {@code true} if calling {@link #close()} propagates to the {@code close()} method of the underlying stream or {@code false} if it does not.
  406.      */
  407.     public boolean isPropagateClose() {
  408.         return propagateClose;
  409.     }

  410.     /**
  411.      * Invokes the delegate's {@link InputStream#mark(int)} method.
  412.      *
  413.      * @param readLimit read ahead limit
  414.      */
  415.     @Override
  416.     public synchronized void mark(final int readLimit) {
  417.         in.mark(readLimit);
  418.         mark = count;
  419.     }

  420.     /**
  421.      * Invokes the delegate's {@link InputStream#markSupported()} method.
  422.      *
  423.      * @return true if mark is supported, otherwise false
  424.      */
  425.     @Override
  426.     public boolean markSupported() {
  427.         return in.markSupported();
  428.     }

  429.     /**
  430.      * A caller has caused a request that would cross the {@code maxLength} boundary.
  431.      * <p>
  432.      * Delegates to the consumer set in {@link Builder#setOnMaxCount(IOBiConsumer)}.
  433.      * </p>
  434.      *
  435.      * @param max The max count of bytes to read.
  436.      * @param count     The count of bytes read.
  437.      * @throws IOException Subclasses may throw.
  438.      * @since 2.12.0
  439.      */
  440.     @SuppressWarnings("unused")
  441.     // TODO Rename to onMaxCount for 3.0
  442.     protected void onMaxLength(final long max, final long count) throws IOException {
  443.         onMaxCount.accept(max, count);
  444.     }

  445.     /**
  446.      * Invokes the delegate's {@link InputStream#read()} method if the current position is less than the limit.
  447.      *
  448.      * @return the byte read or -1 if the end of stream or the limit has been reached.
  449.      * @throws IOException if an I/O error occurs.
  450.      */
  451.     @Override
  452.     public int read() throws IOException {
  453.         if (isMaxCount()) {
  454.             onMaxLength(maxCount, getCount());
  455.             return EOF;
  456.         }
  457.         return super.read();
  458.     }

  459.     /**
  460.      * Invokes the delegate's {@link InputStream#read(byte[])} method.
  461.      *
  462.      * @param b the buffer to read the bytes into
  463.      * @return the number of bytes read or -1 if the end of stream or the limit has been reached.
  464.      * @throws IOException if an I/O error occurs.
  465.      */
  466.     @Override
  467.     public int read(final byte[] b) throws IOException {
  468.         return read(b, 0, b.length);
  469.     }

  470.     /**
  471.      * Invokes the delegate's {@link InputStream#read(byte[], int, int)} method.
  472.      *
  473.      * @param b   the buffer to read the bytes into
  474.      * @param off The start offset
  475.      * @param len The number of bytes to read
  476.      * @return the number of bytes read or -1 if the end of stream or the limit has been reached.
  477.      * @throws IOException if an I/O error occurs.
  478.      */
  479.     @Override
  480.     public int read(final byte[] b, final int off, final int len) throws IOException {
  481.         if (isMaxCount()) {
  482.             onMaxLength(maxCount, getCount());
  483.             return EOF;
  484.         }
  485.         return super.read(b, off, (int) toReadLen(len));
  486.     }

  487.     /**
  488.      * Invokes the delegate's {@link InputStream#reset()} method.
  489.      *
  490.      * @throws IOException if an I/O error occurs.
  491.      */
  492.     @Override
  493.     public synchronized void reset() throws IOException {
  494.         in.reset();
  495.         count = mark;
  496.     }

  497.     /**
  498.      * Sets whether the {@link #close()} method should propagate to the underling {@link InputStream}.
  499.      *
  500.      * @param propagateClose {@code true} if calling {@link #close()} propagates to the {@code close()} method of the underlying stream or {@code false} if it
  501.      *                       does not.
  502.      * @deprecated Use {@link AbstractBuilder#setPropagateClose(boolean)}.
  503.      */
  504.     @Deprecated
  505.     public void setPropagateClose(final boolean propagateClose) {
  506.         this.propagateClose = propagateClose;
  507.     }

  508.     /**
  509.      * Invokes the delegate's {@link InputStream#skip(long)} method.
  510.      *
  511.      * @param n the number of bytes to skip
  512.      * @return the actual number of bytes skipped
  513.      * @throws IOException if an I/O error occurs.
  514.      */
  515.     @Override
  516.     public synchronized long skip(final long n) throws IOException {
  517.         final long skip = super.skip(toReadLen(n));
  518.         count += skip;
  519.         return skip;
  520.     }

  521.     private long toReadLen(final long len) {
  522.         return maxCount >= 0 ? Math.min(len, maxCount - getCount()) : len;
  523.     }

  524.     /**
  525.      * Invokes the delegate's {@link InputStream#toString()} method.
  526.      *
  527.      * @return the delegate's {@link InputStream#toString()}
  528.      */
  529.     @Override
  530.     public String toString() {
  531.         return in.toString();
  532.     }
  533. }