Coverage Report - org.apache.commons.io.input.BOMInputStream
 
Classes in this File Line Coverage Branch Coverage Complexity
BOMInputStream
100%
73/73
100%
56/56
2.833
BOMInputStream$1
100%
8/8
100%
4/4
2.833
 
 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  
 
 19  
 import static org.apache.commons.io.IOUtils.EOF;
 20  
 
 21  
 import java.io.IOException;
 22  
 import java.io.InputStream;
 23  
 import java.util.Arrays;
 24  
 import java.util.Comparator;
 25  
 import java.util.List;
 26  
 
 27  
 import org.apache.commons.io.ByteOrderMark;
 28  
 
 29  
 /**
 30  
  * This class is used to wrap a stream that includes an encoded {@link ByteOrderMark} as its first bytes.
 31  
  * 
 32  
  * This class detects these bytes and, if required, can automatically skip them and return the subsequent byte as the
 33  
  * first byte in the stream.
 34  
  * 
 35  
  * The {@link ByteOrderMark} implementation has the following pre-defined BOMs:
 36  
  * <ul>
 37  
  * <li>UTF-8 - {@link ByteOrderMark#UTF_8}</li>
 38  
  * <li>UTF-16BE - {@link ByteOrderMark#UTF_16LE}</li>
 39  
  * <li>UTF-16LE - {@link ByteOrderMark#UTF_16BE}</li>
 40  
  * <li>UTF-32BE - {@link ByteOrderMark#UTF_32LE}</li>
 41  
  * <li>UTF-32LE - {@link ByteOrderMark#UTF_32BE}</li>
 42  
  * </ul>
 43  
  * 
 44  
  * 
 45  
  * <h3>Example 1 - Detect and exclude a UTF-8 BOM</h3>
 46  
  * 
 47  
  * <pre>
 48  
  * BOMInputStream bomIn = new BOMInputStream(in);
 49  
  * if (bomIn.hasBOM()) {
 50  
  *     // has a UTF-8 BOM
 51  
  * }
 52  
  * </pre>
 53  
  * 
 54  
  * <h3>Example 2 - Detect a UTF-8 BOM (but don't exclude it)</h3>
 55  
  * 
 56  
  * <pre>
 57  
  * boolean include = true;
 58  
  * BOMInputStream bomIn = new BOMInputStream(in, include);
 59  
  * if (bomIn.hasBOM()) {
 60  
  *     // has a UTF-8 BOM
 61  
  * }
 62  
  * </pre>
 63  
  * 
 64  
  * <h3>Example 3 - Detect Multiple BOMs</h3>
 65  
  * 
 66  
  * <pre>
 67  
  * BOMInputStream bomIn = new BOMInputStream(in, 
 68  
  *   ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE,
 69  
  *   ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE
 70  
  *   );
 71  
  * if (bomIn.hasBOM() == false) {
 72  
  *     // No BOM found
 73  
  * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
 74  
  *     // has a UTF-16LE BOM
 75  
  * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
 76  
  *     // has a UTF-16BE BOM
 77  
  * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32LE)) {
 78  
  *     // has a UTF-32LE BOM
 79  
  * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32BE)) {
 80  
  *     // has a UTF-32BE BOM
 81  
  * }
 82  
  * </pre>
 83  
  * 
 84  
  * @see org.apache.commons.io.ByteOrderMark
 85  
  * @see <a href="http://en.wikipedia.org/wiki/Byte_order_mark">Wikipedia - Byte Order Mark</a>
 86  
  * @version $Id: BOMInputStream.java 1686527 2015-06-20 06:31:39Z krosenvold $
 87  
  * @since 2.0
 88  
  */
 89  
 public class BOMInputStream extends ProxyInputStream {
 90  
     private final boolean include;
 91  
     /**
 92  
      * BOMs are sorted from longest to shortest.
 93  
      */
 94  
     private final List<ByteOrderMark> boms;
 95  
     private ByteOrderMark byteOrderMark;
 96  
     private int[] firstBytes;
 97  
     private int fbLength;
 98  
     private int fbIndex;
 99  
     private int markFbIndex;
 100  
     private boolean markedAtStart;
 101  
 
 102  
     /**
 103  
      * Constructs a new BOM InputStream that excludes a {@link ByteOrderMark#UTF_8} BOM.
 104  
      * 
 105  
      * @param delegate
 106  
      *            the InputStream to delegate to
 107  
      */
 108  
     public BOMInputStream(final InputStream delegate) {
 109  28
         this(delegate, false, ByteOrderMark.UTF_8);
 110  28
     }
 111  
 
 112  
     /**
 113  
      * Constructs a new BOM InputStream that detects a a {@link ByteOrderMark#UTF_8} and optionally includes it.
 114  
      * 
 115  
      * @param delegate
 116  
      *            the InputStream to delegate to
 117  
      * @param include
 118  
      *            true to include the UTF-8 BOM or false to exclude it
 119  
      */
 120  
     public BOMInputStream(final InputStream delegate, final boolean include) {
 121  2
         this(delegate, include, ByteOrderMark.UTF_8);
 122  2
     }
 123  
 
 124  
     /**
 125  
      * Constructs a new BOM InputStream that excludes the specified BOMs.
 126  
      * 
 127  
      * @param delegate
 128  
      *            the InputStream to delegate to
 129  
      * @param boms
 130  
      *            The BOMs to detect and exclude
 131  
      */
 132  
     public BOMInputStream(final InputStream delegate, final ByteOrderMark... boms) {
 133  11
         this(delegate, false, boms);
 134  11
     }
 135  
 
 136  
     /**
 137  
      * Compares ByteOrderMark objects in descending length order.
 138  
      */
 139  2290
     private static final Comparator<ByteOrderMark> ByteOrderMarkLengthComparator = new Comparator<ByteOrderMark>() {
 140  
 
 141  
         public int compare(final ByteOrderMark bom1, final ByteOrderMark bom2) {
 142  2287
             final int len1 = bom1.length();
 143  2287
             final int len2 = bom2.length();
 144  2287
             if (len1 > len2) {
 145  31
                 return EOF;
 146  
             }
 147  2256
             if (len2 > len1) {
 148  747
                 return 1;
 149  
             }
 150  1509
             return 0;
 151  
         }
 152  
     };
 153  
 
 154  
     /**
 155  
      * Constructs a new BOM InputStream that detects the specified BOMs and optionally includes them.
 156  
      * 
 157  
      * @param delegate
 158  
      *            the InputStream to delegate to
 159  
      * @param include
 160  
      *            true to include the specified BOMs or false to exclude them
 161  
      * @param boms
 162  
      *            The BOMs to detect and optionally exclude
 163  
      */
 164  
     public BOMInputStream(final InputStream delegate, final boolean include, final ByteOrderMark... boms) {
 165  545
         super(delegate);
 166  545
         if (boms == null || boms.length == 0) {
 167  2
             throw new IllegalArgumentException("No BOMs specified");
 168  
         }
 169  543
         this.include = include;
 170  
         // Sort the BOMs to match the longest BOM first because some BOMs have the same starting two bytes.
 171  543
         Arrays.sort(boms, ByteOrderMarkLengthComparator);
 172  543
         this.boms = Arrays.asList(boms);
 173  
 
 174  543
     }
 175  
 
 176  
     /**
 177  
      * Indicates whether the stream contains one of the specified BOMs.
 178  
      * 
 179  
      * @return true if the stream has one of the specified BOMs, otherwise false if it does not
 180  
      * @throws IOException
 181  
      *             if an error reading the first bytes of the stream occurs
 182  
      */
 183  
     public boolean hasBOM() throws IOException {
 184  12
         return getBOM() != null;
 185  
     }
 186  
 
 187  
     /**
 188  
      * Indicates whether the stream contains the specified BOM.
 189  
      * 
 190  
      * @param bom
 191  
      *            The BOM to check for
 192  
      * @return true if the stream has the specified BOM, otherwise false if it does not
 193  
      * @throws IllegalArgumentException
 194  
      *             if the BOM is not one the stream is configured to detect
 195  
      * @throws IOException
 196  
      *             if an error reading the first bytes of the stream occurs
 197  
      */
 198  
     public boolean hasBOM(final ByteOrderMark bom) throws IOException {
 199  18
         if (!boms.contains(bom)) {
 200  5
             throw new IllegalArgumentException("Stream not configure to detect " + bom);
 201  
         }
 202  13
         return byteOrderMark != null && getBOM().equals(bom);
 203  
     }
 204  
 
 205  
     /**
 206  
      * Return the BOM (Byte Order Mark).
 207  
      * 
 208  
      * @return The BOM or null if none
 209  
      * @throws IOException
 210  
      *             if an error reading the first bytes of the stream occurs
 211  
      */
 212  
     public ByteOrderMark getBOM() throws IOException {
 213  6224
         if (firstBytes == null) {
 214  544
             fbLength = 0;
 215  
             // BOMs are sorted from longest to shortest
 216  544
             final int maxBomSize = boms.get(0).length();
 217  544
             firstBytes = new int[maxBomSize];
 218  
             // Read first maxBomSize bytes
 219  3462
             for (int i = 0; i < firstBytes.length; i++) {
 220  3143
                 firstBytes[i] = in.read();
 221  3143
                 fbLength++;
 222  3143
                 if (firstBytes[i] < 0) {
 223  225
                     break;
 224  
                 }
 225  
             }
 226  
             // match BOM in firstBytes
 227  544
             byteOrderMark = find();
 228  544
             if (byteOrderMark != null) {
 229  214
                 if (!include) {
 230  96
                     if (byteOrderMark.length() < firstBytes.length) {
 231  48
                         fbIndex = byteOrderMark.length();
 232  
                     } else {
 233  48
                         fbLength = 0;
 234  
                     }
 235  
                 }
 236  
             }
 237  
         }
 238  6224
         return byteOrderMark;
 239  
     }
 240  
 
 241  
     /**
 242  
      * Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}.
 243  
      * 
 244  
      * @return The BOM charset Name or null if no BOM found
 245  
      * @throws IOException
 246  
      *             if an error reading the first bytes of the stream occurs
 247  
      * 
 248  
      */
 249  
     public String getBOMCharsetName() throws IOException {
 250  502
         getBOM();
 251  502
         return byteOrderMark == null ? null : byteOrderMark.getCharsetName();
 252  
     }
 253  
 
 254  
     /**
 255  
      * This method reads and either preserves or skips the first bytes in the stream. It behaves like the single-byte
 256  
      * <code>read()</code> method, either returning a valid byte or -1 to indicate that the initial bytes have been
 257  
      * processed already.
 258  
      * 
 259  
      * @return the byte read (excluding BOM) or -1 if the end of stream
 260  
      * @throws IOException
 261  
      *             if an I/O error occurs
 262  
      */
 263  
     private int readFirstBytes() throws IOException {
 264  5688
         getBOM();
 265  5688
         return fbIndex < fbLength ? firstBytes[fbIndex++] : EOF;
 266  
     }
 267  
 
 268  
     /**
 269  
      * Find a BOM with the specified bytes.
 270  
      * 
 271  
      * @return The matched BOM or null if none matched
 272  
      */
 273  
     private ByteOrderMark find() {
 274  544
         for (final ByteOrderMark bom : boms) {
 275  2290
             if (matches(bom)) {
 276  214
                 return bom;
 277  
             }
 278  2076
         }
 279  330
         return null;
 280  
     }
 281  
 
 282  
     /**
 283  
      * Check if the bytes match a BOM.
 284  
      * 
 285  
      * @param bom
 286  
      *            The BOM
 287  
      * @return true if the bytes match the bom, otherwise false
 288  
      */
 289  
     private boolean matches(final ByteOrderMark bom) {
 290  
         // if (bom.length() != fbLength) {
 291  
         // return false;
 292  
         // }
 293  
         // firstBytes may be bigger than the BOM bytes
 294  3726
         for (int i = 0; i < bom.length(); i++) {
 295  3512
             if (bom.get(i) != firstBytes[i]) {
 296  2076
                 return false;
 297  
             }
 298  
         }
 299  214
         return true;
 300  
     }
 301  
 
 302  
     // ----------------------------------------------------------------------------
 303  
     // Implementation of InputStream
 304  
     // ----------------------------------------------------------------------------
 305  
 
 306  
     /**
 307  
      * Invokes the delegate's <code>read()</code> method, detecting and optionally skipping BOM.
 308  
      * 
 309  
      * @return the byte read (excluding BOM) or -1 if the end of stream
 310  
      * @throws IOException
 311  
      *             if an I/O error occurs
 312  
      */
 313  
     @Override
 314  
     public int read() throws IOException {
 315  3177
         final int b = readFirstBytes();
 316  3177
         return b >= 0 ? b : in.read();
 317  
     }
 318  
 
 319  
     /**
 320  
      * Invokes the delegate's <code>read(byte[], int, int)</code> method, detecting and optionally skipping BOM.
 321  
      * 
 322  
      * @param buf
 323  
      *            the buffer to read the bytes into
 324  
      * @param off
 325  
      *            The start offset
 326  
      * @param len
 327  
      *            The number of bytes to read (excluding BOM)
 328  
      * @return the number of bytes read or -1 if the end of stream
 329  
      * @throws IOException
 330  
      *             if an I/O error occurs
 331  
      */
 332  
     @Override
 333  
     public int read(final byte[] buf, int off, int len) throws IOException {
 334  793
         int firstCount = 0;
 335  793
         int b = 0;
 336  3298
         while (len > 0 && b >= 0) {
 337  2505
             b = readFirstBytes();
 338  2505
             if (b >= 0) {
 339  1935
                 buf[off++] = (byte) (b & 0xFF);
 340  1935
                 len--;
 341  1935
                 firstCount++;
 342  
             }
 343  
         }
 344  793
         final int secondCount = in.read(buf, off, len);
 345  793
         return secondCount < 0 ? firstCount > 0 ? firstCount : EOF : firstCount + secondCount;
 346  
     }
 347  
 
 348  
     /**
 349  
      * Invokes the delegate's <code>read(byte[])</code> method, detecting and optionally skipping BOM.
 350  
      * 
 351  
      * @param buf
 352  
      *            the buffer to read the bytes into
 353  
      * @return the number of bytes read (excluding BOM) or -1 if the end of stream
 354  
      * @throws IOException
 355  
      *             if an I/O error occurs
 356  
      */
 357  
     @Override
 358  
     public int read(final byte[] buf) throws IOException {
 359  285
         return read(buf, 0, buf.length);
 360  
     }
 361  
 
 362  
     /**
 363  
      * Invokes the delegate's <code>mark(int)</code> method.
 364  
      * 
 365  
      * @param readlimit
 366  
      *            read ahead limit
 367  
      */
 368  
     @Override
 369  
     public synchronized void mark(final int readlimit) {
 370  238
         markFbIndex = fbIndex;
 371  238
         markedAtStart = firstBytes == null;
 372  238
         in.mark(readlimit);
 373  238
     }
 374  
 
 375  
     /**
 376  
      * Invokes the delegate's <code>reset()</code> method.
 377  
      * 
 378  
      * @throws IOException
 379  
      *             if an I/O error occurs
 380  
      */
 381  
     @Override
 382  
     public synchronized void reset() throws IOException {
 383  238
         fbIndex = markFbIndex;
 384  238
         if (markedAtStart) {
 385  4
             firstBytes = null;
 386  
         }
 387  
 
 388  238
         in.reset();
 389  238
     }
 390  
 
 391  
     /**
 392  
      * Invokes the delegate's <code>skip(long)</code> method, detecting and optionallyskipping BOM.
 393  
      * 
 394  
      * @param n
 395  
      *            the number of bytes to skip
 396  
      * @return the number of bytes to skipped or -1 if the end of stream
 397  
      * @throws IOException
 398  
      *             if an I/O error occurs
 399  
      */
 400  
     @Override
 401  
     public long skip(long n) throws IOException {
 402  4
         int skipped = 0;
 403  8
         while ((n > skipped) && (readFirstBytes() >= 0)) {
 404  4
             skipped++;
 405  
         }
 406  4
         return in.skip(n - skipped) + skipped;
 407  
     }
 408  
 }