Debian Codegraph @

rdfloader/xmlreader/xmlreader.go

raw symbols SCIP
1 package rdfloader
2
3 /**
4 * This module provides the functions needed to read a file tag by tag.
5 * Since the documents are written in rdf/xml,
6 * Creating an xml reader for reading rdf tags.
7 */
8
9 import (
10 "bufio"
11 "errors"
12 "fmt"
13 "io"
14 "os"
15 )
16
17 // reads a:b into a Pair Object.
18 func (xmlReader *XMLReader) readColonPair(delim uint64) (pair Pair, colonFound bool, err error) {
19 // file pointer must point to the start of the attribute.
20 word, err := xmlReader.readTill(delim)
21 if err != nil {
22 return
23 }
24
25 for i, r := range word {
26 if r == ':' {
27 colonFound = true
28 pair.First = string(word[:i])
29 latter := string(word[i+1:])
30 if len(latter) == 0 {
31 err = errors.New("expected a word after colon")
32 return
33 }
34 pair.Second = latter
35 break
36 }
37 }
38 if !colonFound {
39 // no colon was found.
40 pair.First = string(word)
41 }
42 return
43 }
44
45 func (xmlReader *XMLReader) readAttribute() (attr Attribute, err error) {
46 // assumes the file pointer is pointing to the attribute name
47 pair, colonExists, err := xmlReader.readColonPair(WHITESPACE | 1<<'=')
48 if err != nil {
49 return
50 }
51
52 if colonExists {
53 attr.SchemaName = pair.First.(string)
54 attr.Name = pair.Second.(string)
55 } else {
56 attr.Name = pair.First.(string)
57 }
58 _, err = xmlReader.ignoreWhiteSpace()
59 if err != nil {
60 return
61 }
62
63 nextRune, err := xmlReader.readARune()
64 if err != nil {
65 return attr, err
66 }
67 if nextRune != '=' {
68 err = errors.New("expected an assignment sign (=)")
69 }
70
71 firstQuote, err := xmlReader.readARune()
72 if !(firstQuote == '\'' || firstQuote == '"') {
73 err = errors.New("assignment operator must be followed by an attribute enclosed within quotes")
74 }
75
76 // read till next quote or a blank character.
77 word, err := xmlReader.readTill(WHITESPACE | 1<<uint(firstQuote))
78 if err != nil {
79 return attr, err
80 }
81
82 secondQuote, _ := xmlReader.readARune()
83 if firstQuote != secondQuote {
84 return attr, errors.New("unexpected blank char. expected a closing quote")
85 }
86
87 attr.Value = string(word)
88 return attr, nil
89 }
90
91 func (xmlReader *XMLReader) readCDATA() (cdata string, err error) {
92 // Cdata tag is given by <![CDATA[ data ]]
93 // before calling this function, < should've be read.
94 // the file pointer should point to !
95 CDATA_OPENING := "<![CDATA["
96 CDATA_CLOSING := "]]>"
97 nBytes, err := xmlReader.readNBytes(len(CDATA_OPENING))
98 if err != nil {
99 return
100 }
101 tempString := string(nBytes)
102 if tempString != CDATA_OPENING {
103 return cdata, fmt.Errorf("not a valid cdata tag. expected: %s, found: %s", CDATA_OPENING, tempString)
104 }
105
106 // move the file pointer to exclude the cdata declaration tag.
107 data, err := xmlReader.readTillString(CDATA_CLOSING)
108 if err != nil {
109 return cdata, fmt.Errorf("%v reading CDATA End Tag", err)
110 }
111
112 // move file pointer by 3 to ignore the ]]> chars.
113 xmlReader.readNBytes(len(CDATA_CLOSING))
114
115 return CDATA_OPENING + string(data) + CDATA_CLOSING, nil
116 }
117
118 func (xmlReader *XMLReader) readOpeningTag() (tag Tag, isProlog, blockComplete bool, err error) {
119 // Opening Tag can be:
120 // <tag[:schema]
121 // [attr=attr_val]
122 // [attr=attr_val]... >
123 // or
124 // <tag[:schema]
125 // [attr=attr_val]
126 // [attr=attr_val]... />
127 // Second example is a completed block where no value or internal nodes were found.
128
129 var word []rune
130
131 // forward file pointer until a non-blank character is found.
132 // removing all blank characters before opening bracket.
133 _, err = xmlReader.ignoreWhiteSpace()
134 if err != nil {
135 return // possibly an eof error
136 }
137
138 // find the opening angular bracket.
139 // after stripping all the spaces, the next character should be '<'
140 // If the next character is not '<',
141 // there are few chars before opening tag. Which is not allowed!
142 word, err = xmlReader.readTill(1 << '<')
143 if err == io.EOF {
144 // we reached the end of the file while searching for a new tag.
145 if len(word) > 0 {
146 return tag, isProlog, blockComplete, errors.New("found stray characters at EOF")
147 } else {
148 // no new tags were found.
149 return tag, isProlog, blockComplete, io.EOF
150 }
151 }
152 if len(word) != 0 {
153 return tag, isProlog, blockComplete, errors.New("found extra chars before tag start")
154 }
155
156 // next char is '<'.
157 xmlReader.readARune()
158 xmlReader.ignoreWhiteSpace() // there shouldn't be any spaces in a well-formed rdf/xml document.
159
160 nextRune, err := xmlReader.peekARune()
161 if err != nil {
162 return
163 }
164
165 switch nextRune {
166 case '/':
167 return tag, isProlog, blockComplete, errors.New("unexpected closing tag")
168 case '?':
169 // a prolog is found.
170 isProlog = true
171 // ignore the question mark character.
172 xmlReader.readARune()
173 // read till the next question mark.
174 _, err := xmlReader.readTill(1 << '?')
175 if err != nil {
176 return tag, isProlog, blockComplete, err
177 }
178 // ignore the question mark character.
179 xmlReader.readARune()
180
181 _, err = xmlReader.ignoreWhiteSpace()
182 if err != nil {
183 return tag, isProlog, blockComplete, err
184 }
185
186 nextRune, err = xmlReader.peekARune()
187 if err != nil {
188 return tag, isProlog, blockComplete, err
189 }
190 if nextRune == '>' {
191 // ignore >
192 xmlReader.readARune()
193 return tag, isProlog, blockComplete, err
194 }
195 err = fmt.Errorf("expected a > char after ?. Found %v", nextRune)
196 return tag, isProlog, blockComplete, err
197 }
198
199 // reading the next word till we reach a colon or a blank-char or a closing angular bracket.
200 pair, colonExist, err := xmlReader.readColonPair(1<<'>' | WHITESPACE | 1<<'/')
201 if err != nil {
202 return
203 }
204
205 if colonExist {
206 tag.SchemaName = pair.First.(string)
207 tag.Name = pair.Second.(string)
208 } else {
209 tag.Name = pair.First.(string)
210 }
211
212 delim, _ := xmlReader.peekARune() // read the delimiter.
213 if ((1 << uint(delim)) & WHITESPACE) != 0 {
214 // delimiter was a blank space.
215 // <schemaName:tagName [whitespace] was found.
216 xmlReader.ignoreWhiteSpace()
217 }
218 delim, _ = xmlReader.peekARune()
219 switch delim {
220 case '>':
221 // found end of tag. entire tag was parsed.
222 xmlReader.readARune()
223 return
224
225 case '/':
226 // "<[schemaName:]tag /" was parsed. expecting next character to be a closing angular bracket.
227 xmlReader.readARune()
228 blockComplete = true
229
230 nextRune, err := xmlReader.readARune()
231 if err != nil {
232 return tag, isProlog, blockComplete, err
233 }
234
235 if nextRune != '>' {
236 err = errors.New("expected closing angular bracket after /")
237 }
238 return tag, isProlog, blockComplete, err
239 }
240
241 // "<[schemaName:]tagName" is parsed till now.
242
243 _, err = xmlReader.ignoreWhiteSpace()
244 if err != nil {
245 return
246 }
247
248 nextRune, err = xmlReader.peekARune()
249 if err != nil {
250 return
251 }
252
253 if nextRune == '>' {
254 // opening tag didn't had any attributes.
255 tag.Name = string(word)
256 xmlReader.readARune() // consuming the '>' character
257 return
258 }
259
260 // there are some attributes to be read.
261 // read attributes till the next character is a forward slash or a '>'
262 for !(nextRune == '>' || nextRune == '/') {
263 attr, err := xmlReader.readAttribute()
264 if err != nil {
265 return tag, isProlog, blockComplete, err
266 }
267
268 tag.Attrs = append(tag.Attrs, attr)
269 _, err = xmlReader.ignoreWhiteSpace()
270 if err != nil {
271 return tag, isProlog, blockComplete, err
272 }
273
274 nextRune, err = xmlReader.peekARune()
275 if err != nil {
276 return tag, isProlog, blockComplete, err
277 }
278 }
279
280 nextRune, _ = xmlReader.readARune()
281
282 if nextRune == '/' {
283 // "<[schemaName:]tag /" was parsed. expecting next character to be a closing angular bracket.
284 blockComplete = true
285
286 nextRune, err := xmlReader.readARune()
287 if err != nil {
288 return tag, isProlog, blockComplete, err
289 }
290
291 if nextRune != '>' {
292 err = errors.New("expected closing angular bracket after /")
293 }
294 }
295 return tag, isProlog, blockComplete, err
296 }
297
298 func (xmlReader *XMLReader) readClosingTag() (closingTag Tag, err error) {
299 // expects white space to be stripped before the call to this function.
300 next2Bytes, err := xmlReader.readNBytes(2)
301 if err != nil {
302 return closingTag, err
303 }
304
305 if string(next2Bytes) != "</" {
306 return closingTag, errors.New("expected a closing tag")
307 }
308
309 pair, colonExists, err := xmlReader.readColonPair(1<<'>' | WHITESPACE)
310 if err != nil {
311 return closingTag, err
312 }
313 if colonExists {
314 closingTag.SchemaName = pair.First.(string)
315 closingTag.Name = pair.Second.(string)
316 } else {
317 closingTag.Name = pair.First.(string)
318 }
319
320 xmlReader.ignoreWhiteSpace()
321 nextChar, err := xmlReader.readARune()
322 if err != nil {
323 return closingTag, err
324 }
325
326 if nextChar != '>' {
327 return closingTag, errors.New("expected a > char")
328 }
329
330 return closingTag, err
331 }
332
333 func (xmlReader *XMLReader) readBlock() (block Block, err error) {
334 openingTag, isProlog, blockComplete, err := xmlReader.readOpeningTag()
335 if isProlog {
336 return xmlReader.readBlock()
337 }
338 if err != nil {
339 return
340 }
341 block.OpeningTag = openingTag
342
343 if blockComplete {
344 // tag was of this type: <schemaName:tagName />
345 return block, err
346 }
347
348 xmlReader.ignoreWhiteSpace()
349
350 // <schemaName:tagName [attributes] > is read till now.
351 nextRune, err := xmlReader.peekARune()
352 if err != nil {
353 return
354 }
355
356 if nextRune != '<' {
357 // the tag must be wrapping a string resource within it.
358 // tag is of type <schemaName:tagName> value </schemaName:tagName>
359 word, err := xmlReader.readTill(1 << '<') // according to the example, word=value.
360 if err != nil {
361 return block, err
362 }
363 block.Value = string(word)
364 } else {
365 // expecting a new tag or closing tag of the currently read tag or CDATA.
366 nextTwoBytes, err := xmlReader.peekNBytes(2)
367 if err != nil {
368 return block, err
369 }
370
371 if string(nextTwoBytes) == "<!" {
372 // cdata tag is found
373 cdataTag, err := xmlReader.readCDATA()
374 if err != nil {
375 return block, err
376 }
377 block.Value = cdataTag
378 } else {
379 // while we don't get a closing tag, read the children.
380 for string(nextTwoBytes) != "</" {
381 // a new tag is found.
382 childBlock, err := xmlReader.readBlock()
383 if err != nil {
384 return block, err
385 }
386
387 block.Children = append(block.Children, &childBlock)
388
389 xmlReader.ignoreWhiteSpace()
390 nextTwoBytes, err = xmlReader.peekNBytes(2)
391 if err != nil {
392 return block, err
393 }
394 }
395 }
396 }
397 xmlReader.ignoreWhiteSpace() // if any
398 closingTag, err := xmlReader.readClosingTag()
399 if err != nil {
400 return block, err
401 }
402 if openingTag.Name != closingTag.Name || openingTag.SchemaName != closingTag.SchemaName {
403 // opening and closing tags are not same.
404 return block, fmt.Errorf("opening and closing tags doesn't match: opening tag; %v:%v, closing tag: %v:%v.", openingTag.SchemaName, openingTag.Name, closingTag.SchemaName, closingTag.Name)
405 }
406 return block, err
407 }
408
409 func (xmlReader *XMLReader) Read() (rootBlock Block, err error) {
410 rootBlock, err = xmlReader.readBlock()
411 if err != nil {
412 return rootBlock, err
413 }
414 if xmlReader.fileObj != nil {
415 xmlReader.fileObj.Close()
416 }
417
418 // after reading the first block ( the root block ),
419 // there shouldn't be any other tags or characters.
420 _, err = xmlReader.ignoreWhiteSpace()
421 if err == nil {
422 // some other chars were found after reading the rootblock.
423 // expected err to be an EOF error.
424 nextRune, _ := xmlReader.peekARune()
425 return rootBlock, fmt.Errorf("unexpected chars after reading root block. Char Found: %v", string(nextRune))
426 }
427 return rootBlock, nil
428 }
429
430 func XMLReaderFromFileObject(fileObject *bufio.Reader) XMLReader {
431 // user will be responsible for closing the file.
432 return XMLReader{fileObject, nil}
433 }
434
435 func XMLReaderFromFilePath(filePath string) (xmlReader XMLReader, err error) {
436 fileObj, err := os.Open(filePath)
437 if err != nil {
438 return xmlReader, err
439 }
440
441 xmlReader.fileReader = bufio.NewReader(fileObj)
442 xmlReader.fileObj = fileObj
443 return xmlReader, nil
444 }
445
446 func (xmlReader *XMLReader) CloseFileObj() {
447 if xmlReader.fileObj != nil {
448 xmlReader.fileObj.Close()
449 }
450 }