1 package com.thaiopensource.relaxng.parse.compact; 2 3 import com.thaiopensource.relaxng.parse.BuildException; 4 import com.thaiopensource.relaxng.parse.IllegalSchemaException; 5 import com.thaiopensource.relaxng.parse.IncludedGrammar; 6 import com.thaiopensource.relaxng.parse.Parseable; 7 import com.thaiopensource.relaxng.parse.ParsedPattern; 8 import com.thaiopensource.relaxng.parse.SchemaBuilder; 9 import com.thaiopensource.relaxng.parse.Scope; 10 import com.thaiopensource.xml.util.EncodingMap; 11 import org.xml.sax.ErrorHandler ; 12 import org.xml.sax.InputSource ; 13 14 import java.io.IOException ; 15 import java.io.InputStream ; 16 import java.io.InputStreamReader ; 17 import java.io.PushbackInputStream ; 18 import java.io.Reader ; 19 import java.net.URL ; 20 21 public class CompactParseable implements Parseable { 22 private final InputSource in; 23 private final ErrorHandler eh; 24 25 public CompactParseable(InputSource in, ErrorHandler eh) { 26 this.in = in; 27 this.eh = eh; 28 } 29 30 public ParsedPattern parse(SchemaBuilder sb, Scope scope) throws BuildException, IllegalSchemaException { 31 return new CompactSyntax(makeReader(in), in.getSystemId(), sb, eh).parse(scope); 32 } 33 34 public ParsedPattern parseInclude(String uri, SchemaBuilder sb, IncludedGrammar g) 35 throws BuildException, IllegalSchemaException { 36 InputSource tem = new InputSource (uri); 37 tem.setEncoding(in.getEncoding()); 38 return new CompactSyntax(makeReader(tem), uri, sb, eh).parseInclude(g); 39 } 40 41 public ParsedPattern parseExternal(String uri, SchemaBuilder sb, Scope scope) 42 throws BuildException, IllegalSchemaException { 43 InputSource tem = new InputSource (uri); 44 tem.setEncoding(in.getEncoding()); 45 return new CompactSyntax(makeReader(tem), uri, sb, eh).parse(scope); 46 } 47 48 private static final String UTF8 = EncodingMap.getJavaName("UTF-8"); 49 private static final String UTF16 = EncodingMap.getJavaName("UTF-16"); 50 51 private static Reader makeReader(InputSource is) throws BuildException { 52 try { 53 Reader r = is.getCharacterStream(); 54 if (r == null) { 55 InputStream in = is.getByteStream(); 56 if (in == null) { 57 String systemId = is.getSystemId(); 58 in = new URL (systemId).openStream(); 59 } 60 String encoding = is.getEncoding(); 61 if (encoding == null) { 62 PushbackInputStream pb = new PushbackInputStream (in, 2); 63 encoding = detectEncoding(pb); 64 in = pb; 65 } 66 r = new InputStreamReader (in, encoding); 67 } 68 return r; 69 } 70 catch (IOException e) { 71 throw new BuildException(e); 72 } 73 } 74 75 static private String detectEncoding(PushbackInputStream in) throws IOException { 76 String encoding = UTF8; 77 int b1 = in.read(); 78 if (b1 != -1) { 79 int b2 = in.read(); 80 if (b2 != -1) { 81 in.unread(b2); 82 if ((b1 == 0xFF && b2 == 0xFE) || (b1 == 0xFE && b2 == 0xFF)) 83 encoding = UTF16; 84 } 85 in.unread(b1); 86 } 87 return encoding; 88 } 89 } 90 | Popular Tags |