source: gli/trunk/src/org/greenstone/gatherer/util/RemoveContentBeforeRootElementXMLReader.java@ 18170

Last change on this file since 18170 was 18170, checked in by oranfry, 15 years ago

merged in code to do error reporting on xml parsing, even without debug mode on

File size: 1.7 KB
Line 
1package org.greenstone.gatherer.util;
2
3import java.io.Reader;
4import java.io.IOException;
5
6public class RemoveContentBeforeRootElementXMLReader extends Reader {
7
8 static final byte[] xmlIndicator = "<?xml".getBytes();
9
10 Reader ur;
11 int foundBytesReturned = 0;
12 boolean allFoundBytesReturned = false; //redundant, but may help performance
13
14
15 public RemoveContentBeforeRootElementXMLReader( Reader ur ) {
16
17 this.ur = ur;
18
19 //read up to the xml indicator
20 int foundBytes = 0;
21 char c = 0;
22 while ( c != -1 ) {
23 try {
24 c = (char)ur.read();
25 } catch( Exception e ) {
26 System.err.println( "Exception while reading underlying Reader in RemoveContentBeforeRootElementXMLReader" );
27 }
28
29 if ( c == xmlIndicator[foundBytes] ) {
30 foundBytes++;
31 } else {
32 System.out.print( c );
33 foundBytes = 0;
34 }
35
36 if ( foundBytes == xmlIndicator.length ) {
37 //System.out.println();
38 return;
39 }
40
41 }
42 System.err.println( "RemoveContentBeforeRootElementXMLReader:\n" +
43 "The XML being loaded was did not contain the '<?xml' string as expected" );
44
45 }
46
47 public int read( char[] cbuf, int off, int len ) throws IOException {
48
49 for ( int i=off; i<off+len && i<cbuf.length; i++ ) {
50
51 //read from underlying reader
52 int c = read();
53
54 //catch end of stream
55 if ( c == -1 ) {
56 if ( i == off ) {
57 return -1;
58 }
59 return i - off;
60 }
61
62 //insert character into the array
63 cbuf[i] = (char)c;
64 }
65 return len;
66
67 }
68
69 public int read() throws IOException {
70
71 if ( allFoundBytesReturned ) {
72 return ur.read();
73 }
74
75 if ( foundBytesReturned < xmlIndicator.length ) {
76 return xmlIndicator[foundBytesReturned++];
77 }
78
79 allFoundBytesReturned = true;
80 return ur.read();
81 }
82
83 public void close() throws IOException {
84 ur.close();
85 }
86}
Note: See TracBrowser for help on using the repository browser.