forked from nytlabs/streamtools
/
parseXML.go
121 lines (106 loc) · 2.58 KB
/
parseXML.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package library
import (
"encoding/json"
"github.com/nytlabs/gojee" // jee
"github.com/nytlabs/mxj"
"github.com/nytlabs/streamtools/st/blocks" // blocks
"github.com/nytlabs/streamtools/st/util"
)
// specify those channels we're going to use to communicate with streamtools
type ParseXML struct {
blocks.Block
queryrule chan chan interface{}
inrule chan interface{}
in chan interface{}
out chan interface{}
quit chan interface{}
}
// we need to build a simple factory so that streamtools can make new blocks of this kind
func NewParseXML() blocks.BlockInterface {
return &ParseXML{}
}
// Setup is called once before running the block. We build up the channels and specify what kind of block this is.
func (b *ParseXML) Setup() {
b.Kind = "ParseXML"
b.Desc = "converts incoming XML messages to JSON for use in streamtools"
b.in = b.InRoute("in")
b.inrule = b.InRoute("rule")
b.queryrule = b.QueryRoute("rule")
b.quit = b.Quit()
b.out = b.Broadcast()
}
// Run is the block's main loop. Here we listen on the different channels we set up.
func (b *ParseXML) Run() {
var tree *jee.TokenTree
var path string
var err error
var xmlData []byte
for {
select {
case ruleI := <-b.inrule:
// set a parameter of the block
path, err = util.ParseString(ruleI, "Path")
if err != nil {
b.Error(err)
continue
}
token, err := jee.Lexer(path)
if err != nil {
b.Error(err)
continue
}
tree, err = jee.Parser(token)
if err != nil {
b.Error(err)
continue
}
case <-b.quit:
// quit the block
return
case msg := <-b.in:
// deal with inbound data
if tree == nil {
continue
}
dataI, err := jee.Eval(tree, msg)
if err != nil {
b.Error(err)
continue
}
switch v := dataI.(type) {
case []byte:
xmlData = v
case string:
xmlData = []byte(v)
default:
b.Error("data should be a string or a []byte")
continue
}
// parse xml -> map[string]interface{} with mxj
// http://godoc.org/github.com/clbanning/mxj#NewMapXml
mapVal, err := mxj.NewMapXml(xmlData)
if err != nil {
b.Error(err)
continue
}
// TODO: replace this json.Marshal / Unmarshal dance with Nik's recursive map copy from the map block
outMsg, err := json.Marshal(mapVal)
if err != nil {
b.Error(err)
continue
}
var newMsg interface{}
err = json.Unmarshal(outMsg, &newMsg)
if err != nil {
b.Error(err)
continue
}
b.out <- newMsg
case respChan := <-b.queryrule:
// deal with a query request
respChan <- map[string]interface{}{
"Path": path,
}
}
}
}