aboutsummaryrefslogtreecommitdiff
path: root/velocity-engine-core/src/main/java/org/apache/velocity/io/UnicodeInputStream.java
blob: 43abfef55d553930e98dcdf4e639b983eae296e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package org.apache.velocity.io;

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


import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;

import java.util.Locale;

/**
 * This is an input stream that is unicode BOM aware. This allows you to e.g. read
 * Windows Notepad Unicode files as Velocity templates.
 *
 * It allows you to check the actual encoding of a file by calling {@link #getEncodingFromStream()} on
 * the input stream reader.
 *
 * This class is not thread safe! When more than one thread wants to use an instance of UnicodeInputStream,
 * the caller must provide synchronization.
 *
 * @author <a href="mailto:mailmur@yahoo.com">Aki Nieminen</a>
 * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a>
 * @version $Id$
 * @since 1.5
 */
public class UnicodeInputStream
    extends InputStream
{

    /** BOM Marker for UTF 8. See http://www.unicode.org/unicode/faq/utf_bom.html */
    public static final UnicodeBOM UTF8_BOM = new UnicodeBOM("UTF-8", new byte [] { (byte)0xef, (byte)0xbb, (byte)0xbf });

    /** BOM Marker for UTF 16, little endian. See http://www.unicode.org/unicode/faq/utf_bom.html */
    public static final UnicodeBOM UTF16LE_BOM = new UnicodeBOM("UTF-16LE", new byte [] { (byte)0xff, (byte)0xfe });

    /** BOM Marker for UTF 16, big endian. See http://www.unicode.org/unicode/faq/utf_bom.html */
    public static final UnicodeBOM UTF16BE_BOM = new UnicodeBOM("UTF-16BE", new byte [] { (byte)0xfe, (byte)0xff });

    /**
     * BOM Marker for UTF 32, little endian. See http://www.unicode.org/unicode/faq/utf_bom.html
     *
     */
    public static final UnicodeBOM UTF32LE_BOM = new UnicodeBOM("UTF-32LE", new byte [] { (byte)0xff, (byte)0xfe, (byte)0x00, (byte)0x00 });

    /**
     * BOM Marker for UTF 32, big endian. See http://www.unicode.org/unicode/faq/utf_bom.html
     *
     */
    public static final UnicodeBOM UTF32BE_BOM = new UnicodeBOM("UTF-32BE", new byte [] { (byte)0x00, (byte)0x00, (byte)0xfe, (byte)0xff });

    /** The maximum amount of bytes to read for a BOM */
    private static final int MAX_BOM_SIZE = 4;

    /** Buffer for BOM reading */
    private byte [] buf = new byte[MAX_BOM_SIZE];

    /** Buffer pointer. */
    private int pos = 0;

    /** The stream encoding as read from the BOM or null. */
    private final String encoding;

    /** True if the BOM itself should be skipped and not read. */
    private final boolean skipBOM;

    private final PushbackInputStream inputStream;

    /**
     * Creates a new UnicodeInputStream object. Skips a BOM which defines the file encoding.
     *
     * @param  inputStream The input stream to use for reading.
     * @throws IllegalStateException
     * @throws IOException
     */
    public UnicodeInputStream(final InputStream inputStream)
            throws IllegalStateException, IOException
    {
        this(inputStream, true);
    }

    /**
     * Creates a new UnicodeInputStream object.
     *
     * @param  inputStream The input stream to use for reading.
     * @param skipBOM If this is set to true, a BOM read from the stream is discarded. This parameter should normally be true.
     * @throws IllegalStateException
     * @throws IOException
     */
    public UnicodeInputStream(final InputStream inputStream, boolean skipBOM)
            throws IllegalStateException, IOException
    {
        super();

        this.skipBOM = skipBOM;
        this.inputStream = new PushbackInputStream(inputStream, MAX_BOM_SIZE);

        try
        {
            this.encoding = readEncoding();
        }
        catch (IOException ioe)
        {
            throw new IllegalStateException("Could not read BOM from Stream", ioe);
        }
    }

    /**
     * Returns true if the input stream discards the BOM.
     *
     * @return  True if the input stream discards the BOM.
     */
    public boolean isSkipBOM()
    {
        return skipBOM;
    }

    /**
     * Read encoding based on BOM.
     *
     * @return  The encoding based on the BOM.
     *
     * @throws  IllegalStateException  When a problem reading the BOM occured.
     */
    public String getEncodingFromStream()
    {
        return encoding;
    }

    /**
     * This method gets the encoding from the stream contents if a BOM exists. If no BOM exists, the encoding
     * is undefined.
     *
     * @return The encoding of this streams contents as decided by the BOM or null if no BOM was found.
     * @throws IOException
     */
    protected String readEncoding()
        throws IOException
    {
        pos = 0;

        UnicodeBOM encoding = null;

        // read first byte.
        if (readByte())
        {
            // Build a list of matches
            //
            // 00 00 FE FF --> UTF 32 BE
            // EF BB BF    --> UTF 8
            // FE FF       --> UTF 16 BE
            // FF FE       --> UTF 16 LE
            // FF FE 00 00 --> UTF 32 LE

            switch (buf[0])
            {
            case (byte)0x00: // UTF32 BE
                encoding = match(UTF32BE_BOM, null);
                break;
            case (byte)0xef: // UTF8
                encoding = match(UTF8_BOM, null);
                break;
            case (byte)0xfe: // UTF16 BE
                encoding = match(UTF16BE_BOM, null);
                break;
            case (byte)0xff: // UTF16/32 LE
                encoding = match(UTF16LE_BOM, null);

                if (encoding != null)
                {
                    encoding = match(UTF32LE_BOM, encoding);
                }
                break;

            default:
                encoding = null;
                break;
            }
        }

        pushback(encoding);

        return (encoding != null) ? encoding.getEncoding() : null;
    }

    private UnicodeBOM match(final UnicodeBOM matchEncoding, final UnicodeBOM noMatchEncoding)
        throws IOException
    {
        byte [] bom = matchEncoding.getBytes();

        for (int i = 0; i < bom.length; i++)
        {
            if (pos <= i) // Byte has not yet been read
            {
                if (!readByte())
                {
                    return noMatchEncoding;
                }
            }

            if (bom[i] != buf[i])
            {
                return noMatchEncoding;
            }
        }

        return matchEncoding;
    }

    private boolean readByte()
            throws IOException
    {
        int res = inputStream.read();
        if (res == -1)
        {
            return false;
        }

        if (pos >= buf.length)
        {
            throw new IOException("BOM read error");
        }

        buf[pos++] = (byte) res;
        return true;
    }

    private void pushback(final UnicodeBOM matchBOM)
        throws IOException
    {
        int count = pos; // By default, all bytes are pushed back.
        int start = 0;

        if (matchBOM != null && skipBOM)
        {
            // We have a match (some bytes are part of the BOM)
            // and we want to skip the BOM. Push back only the bytes
            // after the BOM.
            start = matchBOM.getBytes().length;
            count = (pos - start);

            if (count < 0)
            {
                throw new IllegalStateException("Match has more bytes than available!");
            }
        }

        inputStream.unread(buf, start, count);
    }

    /**
     * @throws IOException
     * @see java.io.InputStream#close()
     */
    @Override
    public void close()
        throws IOException
    {
        inputStream.close();
    }

    /**
     * @throws IOException
     * @see java.io.InputStream#available()
     */
    @Override
    public int available()
        throws IOException
    {
        return inputStream.available();
    }

    /**
     * @param readlimit
     * @see java.io.InputStream#mark(int)
     */
    @Override
    public void mark(final int readlimit)
    {
        inputStream.mark(readlimit);
    }

    /**
     * @return mark supported
     * @see java.io.InputStream#markSupported()
     */
    @Override
    public boolean markSupported()
    {
        return inputStream.markSupported();
    }

    /**
     * @return read char
     * @see java.io.InputStream#read()
     */
    @Override
    public int read()
        throws IOException
    {
        return inputStream.read();
    }

    /**
     * @param b buffer
     * @return read chars count
     * @see java.io.InputStream#read(byte[])
     */
    @Override
    public int read(final byte [] b)
        throws IOException
    {
        return inputStream.read(b);
    }

    /**
     * @param b buffer
     * @param off offset
     * @param len length
     * @return reac char
     * @see java.io.InputStream#read(byte[], int, int)
     */
    @Override
    public int read(final byte [] b, final int off, final int len)
        throws IOException
    {
        return inputStream.read(b, off, len);
    }

    /**
     * @see java.io.InputStream#reset()
     */
    @Override
    public void reset()
        throws IOException
    {
        inputStream.reset();
    }

    /**
     * @param n
     * @return skipped count
     * @see java.io.InputStream#skip(long)
     */
    @Override
    public long skip(final long n)
        throws IOException
    {
        return inputStream.skip(n);
    }


    /**
     * Helper function to compare encodings
     * @param left
     * @param right
     * @return true for same encoding
     */
    public static boolean sameEncoding(String left, String right)
    {
        left = left.toUpperCase(Locale.ROOT).replace("-", "").replace("_","");
        right = right.toUpperCase(Locale.ROOT).replace("-", "").replace("_","");
        return left.equals(right);
    }

    /**
     * Helper class to bundle encoding and BOM marker.
     *
     * @author <a href="mailto:henning@apache.org">Henning P. Schmiedehausen</a>
     * @version $Id$
     */
    static final class UnicodeBOM
    {
        private final String encoding;

        private final byte [] bytes;

        private UnicodeBOM(final String encoding, final byte [] bytes)
        {
            this.encoding = encoding;
            this.bytes = bytes;
        }

        String getEncoding()
        {
            return encoding;
        }

        byte [] getBytes()
        {
            return bytes;
        }
    }
}