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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use crate::model::OwnedSubject;
use crate::utils::*;
use quick_xml::events::*;
use quick_xml::Writer;
use rio_api::formatter::TriplesFormatter;
use rio_api::model::*;
use std::convert::TryInto;
use std::io;
use std::io::Write;
pub struct RdfXmlFormatter<W: Write> {
writer: Writer<W>,
current_subject: Option<OwnedSubject>,
}
impl<W: Write> RdfXmlFormatter<W> {
pub fn new(write: W) -> io::Result<Self> {
Self {
writer: Writer::new(write),
current_subject: None,
}
.write_start()
}
pub fn with_indentation(write: W, indentation_size: usize) -> io::Result<Self> {
Self {
writer: Writer::new_with_indent(write, b' ', indentation_size),
current_subject: None,
}
.write_start()
}
fn write_start(mut self) -> io::Result<Self> {
self.writer
.write_event(Event::Decl(BytesDecl::new(b"1.0", Some(b"UTF-8"), None)))
.map_err(map_err)?;
let mut rdf_open = BytesStart::borrowed_name(b"rdf:RDF");
rdf_open.push_attribute(("xmlns:rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
self.writer
.write_event(Event::Start(rdf_open))
.map_err(map_err)?;
Ok(self)
}
pub fn finish(mut self) -> io::Result<W> {
if self.current_subject.is_some() {
self.writer
.write_event(Event::End(BytesEnd::borrowed(b"rdf:Description")))
.map_err(map_err)?;
}
self.writer
.write_event(Event::End(BytesEnd::borrowed(b"rdf:RDF")))
.map_err(map_err)?;
let mut inner = self.writer.into_inner();
inner.flush()?;
Ok(inner)
}
}
impl<W: Write> TriplesFormatter for RdfXmlFormatter<W> {
type Error = io::Error;
fn format(&mut self, triple: &Triple<'_>) -> io::Result<()> {
if self.current_subject.as_ref().map(|v| v.into()) != Some(triple.subject) {
if self.current_subject.is_some() {
self.writer
.write_event(Event::End(BytesEnd::borrowed(b"rdf:Description")))
.map_err(map_err)?;
}
let mut description_open = BytesStart::borrowed_name(b"rdf:Description");
match triple.subject {
Subject::NamedNode(n) => description_open.push_attribute(("rdf:about", n.iri)),
Subject::BlankNode(n) => description_open.push_attribute(("rdf:nodeID", n.id)),
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"RDF/XML only supports named or blank subject",
))
}
}
self.writer
.write_event(Event::Start(description_open))
.map_err(map_err)?;
}
let (prop_prefix, prop_value) = split_iri(triple.predicate.iri);
let (prop_qname, prop_xmlns) = if prop_value.is_empty() {
("prop:", ("xmlns:prop", prop_prefix))
} else {
(prop_value, ("xmlns", prop_prefix))
};
let mut property_open = BytesStart::borrowed_name(prop_qname.as_bytes());
property_open.push_attribute(prop_xmlns);
let content = match triple.object {
Term::NamedNode(n) => {
property_open.push_attribute(("rdf:resource", n.iri));
None
}
Term::BlankNode(n) => {
property_open.push_attribute(("rdf:nodeID", n.id));
None
}
Term::Literal(l) => match l {
Literal::Simple { value } => Some(value),
Literal::LanguageTaggedString { value, language } => {
property_open.push_attribute(("xml:lang", language));
Some(value)
}
Literal::Typed { value, datatype } => {
property_open.push_attribute(("rdf:datatype", datatype.iri));
Some(value)
}
},
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"RDF/XML only supports named, blank or literal object",
))
}
};
if let Some(content) = content {
self.writer
.write_event(Event::Start(property_open))
.map_err(map_err)?;
self.writer
.write_event(Event::Text(BytesText::from_plain_str(content)))
.map_err(map_err)?;
self.writer
.write_event(Event::End(BytesEnd::borrowed(prop_qname.as_bytes())))
.map_err(map_err)?;
} else {
self.writer
.write_event(Event::Empty(property_open))
.map_err(map_err)?;
}
self.current_subject = Some(triple.subject.try_into()?);
Ok(())
}
}
fn map_err(error: quick_xml::Error) -> io::Error {
if let quick_xml::Error::Io(error) = error {
error
} else {
io::Error::new(io::ErrorKind::Other, error)
}
}
fn split_iri(iri: &str) -> (&str, &str) {
if let Some(position_base) = iri.rfind(|c| !is_name_char(c) || c == ':') {
if let Some(position_add) = iri[position_base..].find(|c| is_name_start_char(c) && c != ':')
{
(
&iri[..position_base + position_add],
&iri[position_base + position_add..],
)
} else {
(iri, "")
}
} else {
(iri, "")
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_split_iri() {
assert_eq!(
split_iri("http://schema.org/Person"),
("http://schema.org/", "Person")
);
assert_eq!(split_iri("http://schema.org/"), ("http://schema.org/", ""));
}
#[cfg(feature = "rio_api/star")]
#[test]
fn formmatting_rdf_star_fails_cleanly() {
use rio_api::formatter::TriplesFormatter;
let iri = NamedNode { iri: "tag:iri" };
let triple = Triple {
subject: Triple {
subject: iri.into(),
predicate: iri,
object: iri.into(),
}
.into(),
predicate: iri,
object: iri.into(),
};
let mut fmt = RdfXmlFormatter::new(std::io::sink()).unwrap();
let res = fmt.format(&triple).and_then(|_| fmt.finish());
assert!(res.is_err());
}
}