31
31
32
32
import com .jcabi .log .Logger ;
33
33
import java .io .ByteArrayInputStream ;
34
+ import java .io .File ;
34
35
import java .io .IOException ;
35
36
import java .nio .charset .StandardCharsets ;
37
+ import java .util .function .Function ;
36
38
import javax .xml .parsers .DocumentBuilder ;
37
39
import javax .xml .parsers .DocumentBuilderFactory ;
38
40
import javax .xml .parsers .ParserConfigurationException ;
@@ -55,13 +57,15 @@ final class DomParser {
55
57
/**
56
58
* The XML as a text.
57
59
*/
58
- private final transient byte [] xml ;
60
+ // private final transient byte[] xml;
59
61
60
62
/**
61
63
* Document builder factory to use for parsing.
62
64
*/
63
65
private final transient DocumentBuilderFactory factory ;
64
66
67
+ private final Parser parser ;
68
+
65
69
/**
66
70
* Public ctor.
67
71
*
@@ -92,7 +96,33 @@ final class DomParser {
92
96
*/
93
97
@ SuppressWarnings ("PMD.ArrayIsStoredDirectly" )
94
98
DomParser (final DocumentBuilderFactory fct , final byte [] bytes ) {
95
- this .xml = bytes ;
99
+ // this.xml = bytes;
100
+ this .parser = new Parser () {
101
+ @ Override
102
+ public Document apply (final DocumentBuilder builder ) throws IOException , SAXException {
103
+ return builder .parse (new ByteArrayInputStream (bytes ));
104
+ }
105
+
106
+ @ Override
107
+ public long length () {
108
+ return bytes .length ;
109
+ }
110
+ };
111
+ this .factory = fct ;
112
+ }
113
+
114
+ DomParser (final DocumentBuilderFactory fct , final File file ){
115
+ this .parser = new Parser () {
116
+ @ Override
117
+ public Document apply (final DocumentBuilder builder ) throws IOException , SAXException {
118
+ return builder .parse (file );
119
+ }
120
+
121
+ @ Override
122
+ public long length () {
123
+ return file .length ();
124
+ }
125
+ };
96
126
this .factory = fct ;
97
127
}
98
128
@@ -116,7 +146,8 @@ public Document document() {
116
146
final long start = System .nanoTime ();
117
147
final Document doc ;
118
148
try {
119
- doc = builder .parse (new ByteArrayInputStream (this .xml ));
149
+ // doc = builder.parse(new ByteArrayInputStream(this.xml));
150
+ doc = this .parser .apply (builder );
120
151
} catch (final IOException | SAXException ex ) {
121
152
throw new IllegalArgumentException (
122
153
String .format (
@@ -131,11 +162,18 @@ public Document document() {
131
162
this ,
132
163
"%s parsed %d bytes of XML in %[nano]s" ,
133
164
builder .getClass ().getName (),
134
- this .xml .length ,
165
+ this .parser .length () ,
135
166
System .nanoTime () - start
136
167
);
137
168
}
138
169
return doc ;
139
170
}
140
171
172
+ private interface Parser {
173
+
174
+ Document apply (DocumentBuilder builder ) throws IOException , SAXException ;
175
+
176
+ long length ();
177
+ }
178
+
141
179
}
0 commit comments