01: /*
02: * :tabSize=8:indentSize=8:noTabs=false:
03: * :folding=explicit:collapseFolds=1:
04: *
05: * Copyright (C) 2007 Kazutoshi Satoda
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or any later version.
11: * This program is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: * GNU General Public License for more details.
15: *
16: * You should have received a copy of the GNU General Public License
17: * along with this program; if not, write to the Free Software
18: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19: */
20:
21: package org.gjt.sp.jedit.io;
22:
23: //{{{ Imports
24: import java.io.InputStream;
25: import java.io.IOException;
26: import java.nio.charset.Charset;
27: import java.nio.charset.IllegalCharsetNameException;
28:
29: import org.gjt.sp.util.Log;
30:
31: //}}}
32:
33: /**
34: * An encoding detector which extracts encoding from XML declaration.
35: *
36: * @since 4.3pre10
37: * @author Kazutoshi Satoda
38: */
39: public class XMLEncodingDetector implements EncodingDetector {
40: //{{{ implements EncodingDetector
41: public String detectEncoding(InputStream sample) throws IOException {
42: // Length of longest XML PI used for encoding detection.
43: // <?xml version="1.0" encoding="................"?>
44: final int XML_PI_LENGTH = 50;
45:
46: byte[] _xmlPI = new byte[XML_PI_LENGTH];
47: int offset = 0;
48: int count;
49: while ((count = sample.read(_xmlPI, offset, XML_PI_LENGTH
50: - offset)) != -1) {
51: offset += count;
52: if (offset == XML_PI_LENGTH)
53: break;
54: }
55: return getXMLEncoding(new String(_xmlPI, 0, offset, "ASCII"));
56: } //}}}
57:
58: //{{{ Private members
59: /**
60: * Extract XML encoding name from PI.
61: */
62: private static String getXMLEncoding(String xmlPI) {
63: if (!xmlPI.startsWith("<?xml"))
64: return null;
65:
66: int index = xmlPI.indexOf("encoding=");
67: if (index == -1 || index + 9 == xmlPI.length())
68: return null;
69:
70: char ch = xmlPI.charAt(index + 9);
71: int endIndex = xmlPI.indexOf(ch, index + 10);
72: if (endIndex == -1)
73: return null;
74:
75: String encoding = xmlPI.substring(index + 10, endIndex);
76:
77: try {
78: if (Charset.isSupported(encoding)) {
79: return encoding;
80: } else {
81: Log.log(Log.WARNING, XMLEncodingDetector.class,
82: "XML PI specifies unsupported encoding: "
83: + encoding);
84: }
85: } catch (IllegalCharsetNameException e) {
86: Log
87: .log(Log.WARNING, XMLEncodingDetector.class,
88: "XML PI specifies illegal encoding: "
89: + encoding, e);
90: }
91: return null;
92: }
93: //}}}
94: }
|