Menu

[r12]: / trunk / libtop_engine / owl_import.cpp  Maximize  Restore  History

Download this file

632 lines (496 with data), 24.2 kB

  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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#include "owl_import.h"
namespace parser {
namespace xml {
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::error
//
// Overrides of the SAX ErrorHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::error(const SAXParseException& e)
{
std::cout << "\nERROR at file " << strx(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << strx(e.getMessage()) << std::endl;
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::fatalError
//
// Overrides of the SAX ErrorHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::fatalError(const SAXParseException& e)
{
std::cout << "\nFatal Error at file " << strx(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << strx(e.getMessage()) << std::endl;
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::warning
//
// Overrides of the SAX ErrorHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::warning(const SAXParseException& e)
{
std::cout << "\nWarning at file " << strx(e.getSystemId())
<< ", line " << e.getLineNumber()
<< ", char " << e.getColumnNumber()
<< "\n Message: " << strx(e.getMessage()) << std::endl;
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::characters
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::characters(XMLCh const* const chars, unsigned int const length)
{
std::string str(strx(chars).localForm(), length);
boost::trim(str);
if(str.size() == 0) return;
// std::cout << "rdf_handler::characters: called with " << str << std::endl;
if(m_stack.empty()) return;
parse_event_state & current = m_stack.back();
if(current.data_type == 1) {
current.object = m_graph_p->create_literal_as_index(str, boost::lexical_cast<int>(str));
} else {
current.object = m_graph_p->create_literal_as_index("top:text_"+boost::lexical_cast<std::string>(m_graph_p->size()), str);
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::endDocument
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::endDocument()
{
// std::cout << "rdf_handler::endDocument: called\n";
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::endElement
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::endElement(XMLCh const* const name)
{
strx namex(name);
std::string elm_name(namex.localForm());
if(m_verbose) std::cout << "\nrdf_handler::endElement: called with " << elm_name << std::endl;
if(m_stack.empty()) return;
// don't use reference here since we need to access 'current'
// after the call to pop_back.
parse_event_state current = m_stack.back();
if(!current.is_collection_parse_type and current.object != m_rdf_description) {
if(m_verbose) std::cout << "endElement: " << current << std::endl;
m_graph_p->insert(current.subject, current.predicate, current.object);
}
m_stack.pop_back();
// //*
// std::cout << "endElement: The stack size is (after pop this elm) " << m_stack.size() << std::endl;
if(current.is_collection_parse_type) {
// collection completed
//*
if(m_verbose) std::cout << "endElement: collection completed." << std::endl;
} else if(current.from_class_event and !m_stack.empty()) {
parse_event_state & parent = m_stack.back();
// check if current is an item into a collection
if(parent.is_collection_parse_type) {
if(current.subject != m_owl_thing) {
if(m_verbose) std::cout << "endElement: adding to collection: "
<< rdf::index_triple(parent.subject, parent.predicate, current.subject) << std::endl;
m_graph_p->insert(parent.subject, parent.predicate, current.subject);
}
} else {
if(!parent.object) parent.object = current.subject;
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::processingInstruction
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::processingInstruction(XMLCh const* const target, XMLCh const* const data)
{
if(is_verbose()) {
std::cout << "rdf_handler::processingInstruction: called with target " << strx(target);
if(data) std::cout << " and " << strx(data);
std::cout << std::endl;
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::startDocument
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::startDocument()
{
// std::cout << "rdf_handler::startDocument: called\n";
m_stack.reserve(100);
m_rdf_type = m_graph_p->create_resource_as_index("rdf:type");
m_owl_thing = m_graph_p->create_resource_as_index("owl:Thing");
m_rdf_description = m_graph_p->create_resource_as_index("rdf:Description");
m_top_label = m_graph_p->create_resource_as_index("top:label");
// some defensive measures, keep tag names that are known
m_known_class_name.insert("rdfs:Class");
m_known_class_name.insert("owl:AllDifferent");
m_known_class_name.insert("owl:AnnotationProperty");
m_known_class_name.insert("owl:Class");
m_known_class_name.insert("owl:DataRange");
m_known_class_name.insert("owl:DatatypeProperty");
m_known_class_name.insert("owl:DeprecatedClass");
m_known_class_name.insert("owl:DeprecatedProperty");
m_known_class_name.insert("owl:FunctionalProperty");
m_known_class_name.insert("owl:InverseFunctionalProperty");
m_known_class_name.insert("owl:Nothing");
m_known_class_name.insert("owl:ObjectProperty");
m_known_class_name.insert("owl:Ontology");
m_known_class_name.insert("owl:OntologyProperty");
m_known_class_name.insert("owl:Restriction");
m_known_class_name.insert("owl:SymmetricProperty");
m_known_class_name.insert("owl:Thing");
m_known_class_name.insert("owl:TransitiveProperty");
m_known_class_name.insert("rdf:Property");
m_known_predicate_name.insert("owl:allValuesFrom");
m_known_predicate_name.insert("owl:backwardCompatibleWith");
m_known_predicate_name.insert("owl:cardinality");
m_known_predicate_name.insert("owl:complementOf");
m_known_predicate_name.insert("owl:differentFrom");
m_known_predicate_name.insert("owl:disjointWith");
m_known_predicate_name.insert("owl:distinctMembers");
m_known_predicate_name.insert("owl:equivalentClass");
m_known_predicate_name.insert("owl:equivalentProperty");
m_known_predicate_name.insert("owl:hasValue");
m_known_predicate_name.insert("owl:imports");
m_known_predicate_name.insert("owl:incompatibleWith");
m_known_predicate_name.insert("owl:intersectionOf");
m_known_predicate_name.insert("owl:inverseOf");
m_known_predicate_name.insert("owl:maxCardinality");
m_known_predicate_name.insert("owl:minCardinality");
m_known_predicate_name.insert("owl:oneOf");
m_known_predicate_name.insert("owl:onProperty");
m_known_predicate_name.insert("owl:priorVersion");
m_known_predicate_name.insert("owl:sameAs");
m_known_predicate_name.insert("owl:someValuesFrom");
m_known_predicate_name.insert("owl:unionOf");
m_known_predicate_name.insert("owl:versionInfo");
};
/////////////////////////////////////////////////////////////////////////////////////////
// rdf_handler::startElement
//
// Overrides of the SAX DocumentHandler interface
/////////////////////////////////////////////////////////////////////////////////////////
void
rdf_handler::startElement(XMLCh const* const name, AttributeList & attributes)
{
strx namex(name);
std::string elm_name(namex.localForm());
// //*
// std::cout << "\nrdf_handler::startElement: called with " << elm_name << std::endl;
// std::cout << "startElement: The stack size is " << m_stack.size() << std::endl;
// pull the attributes into a map
str_map_type map;
unsigned int len = attributes.getLength();
for (unsigned int index = 0; index < len; index++) {
strx key(attributes.getName(index));
strx val(attributes.getValue(index));
// std::cout << "\twith attribute " << key << " = " << val << std::endl;
map.insert(str_map_type::value_type(key.localForm(), val.localForm()));
}
if(!m_namespace_done and elm_name == std::string("rdf:RDF")) {
m_namespace_done = true;
// keep the reverse mapping
str_map_type::const_iterator itor = map.begin();
str_map_type::const_iterator end = map.end();
for(; itor!=end; ++itor) {
std::string key = itor->first;
std::string val = itor->second;
if(key == "xml:base") {
m_model_xml_base = val;
key = "";
} else if(key == "xmlns") {
// no default short name for xml namespace
key = "";
} else {
std::string::size_type pos = 0;
if((pos=key.find(':')) != std::string::npos) {
key = key.substr(pos+1) + ":";
} else {
std::cout << "ERROR (WARNING): invalid ns attribute " << key << std::endl;
key = "";
}
}
// std::cout << "Namespace reverse mapping: "<< val << " --> " << key << std::endl;
// store the reverse mapping with trimmed ns
if(key != "") m_xml_ns_rmap.insert(str_map_type::value_type(val, key));
}
// get the short name for m_model_xml_base
std::string xmlns_base = m_model_xml_base+"#";
itor = m_xml_ns_rmap.find(xmlns_base);
if(itor != m_xml_ns_rmap.end()) {
m_xmlns = itor->second;
} else {
m_xmlns = "";
m_xml_ns_rmap.insert(str_map_type::value_type(xmlns_base, m_xmlns));
}
// //*
// std::cout << "processing rdf:RDF\n";
return;
}
if(expect_class()) {
if(!validate_tag(elm_name, true)) {
std::string msg = "ERROR-O1: startElement: invalid tag - expecting class tag but have: "+elm_name;
std::cout << msg << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, msg);
}
parse_event_state e(get_subject(map), m_rdf_type, get_resource(elm_name), true, false);
m_stack.push_back(e);
if(m_verbose) std::cout << "startElement: " << e << std::endl;
} else {
if(!validate_tag(elm_name, false)) {
std::string msg = "ERROR-O1: startElement: invalid tag - expecting predicate tag but have: "+elm_name;
std::cout << msg << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, msg);
}
if(m_stack.empty()) {
std::cout << "ERROR-O1: startElement: invalid state - having predicate w/o parent class state!" << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR-O1: startElement: invalid state - having predicate w/o parent class state!");
}
parse_event_state & current = m_stack.back();
parse_event_state e(current.subject, get_resource(elm_name), get_resource(map), false, has_collection_parse_type(map));
e.data_type = get_data_type(map);
m_stack.push_back(e);
if(m_verbose) std::cout << "startElement: " << e << std::endl;
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// process_imported_owl_model
//
// Utility function to cleanup and print info about imported model
/////////////////////////////////////////////////////////////////////////////////////////
void
process_imported_owl_model(rdf::rdf_graph_ptr_type & graph_p, bool verbose)
{
// Since in the asserted hierarchy it is very likely that the base classes does not
// explicitly rdfs_subClassOf owl_Thing, then we must scan all classes and find those who don't extend owl_Thing
// and fix this. This is to allow to construct the asserted class hierarchy simply.
rdf::index_type rdf_type = graph_p->create_resource_as_index("rdf:type");
rdf::index_type owl_Class = graph_p->create_resource_as_index("owl:Class");
rdf::index_type owl_Restriction = graph_p->create_resource_as_index("owl:Restriction");
rdf::index_type rdfs_subClassOf = graph_p->create_resource_as_index("rdfs:subClassOf");
rdf::index_type owl_Thing = graph_p->create_resource_as_index("owl:Thing");
// add triple (subject, rdfs_subClassOf, owl_Thing) to all subjects that have a class descriptor
// i.e., is not a bnode, but all it's parent classes do not have a class descriptor (are all bnodes)
rdf::rdf_graph::index_iterator itor = graph_p->find_index(rdf::all_subjects(), rdf_type, owl_Class);
while(!itor.is_end()) {
rdf::index_type subject = itor.get_triple().get_subject();
if(!subject->is_bnode()) {
bool has_parent_w_descriptor = false;
rdf::rdf_graph::index_iterator jtor = graph_p->find_index(subject, rdfs_subClassOf, rdf::all_objects());
while(!has_parent_w_descriptor and !jtor.is_end()) {
// now, check if parent class has a class descriptor
rdf::index_type parent = jtor.get_triple().get_object();
if(!parent->is_bnode()) {
has_parent_w_descriptor = true;
}
jtor.next();
}
if(!has_parent_w_descriptor) {
graph_p->insert(subject, rdfs_subClassOf, owl_Thing);
}
}
itor.next();
}
itor = graph_p->find_index(rdf::all_subjects(), rdf_type, owl_Restriction);
while(!itor.is_end()) {
rdf::index_type subject = itor.get_triple().get_subject();
if(!graph_p->contains(subject, rdfs_subClassOf, rdf::all_objects())) {
graph_p->insert(subject, rdfs_subClassOf, owl_Thing);
graph_p->insert(subject, rdfs_subClassOf, owl_Class);
}
itor.next();
}
if(verbose) {
unsigned int count = 0;
std::cout << "The graph contains the following statements:" << std::endl;
rdf::rdf_graph::iterator itor = graph_p->find();
while(!itor.is_end()) {
std::cout << "\t" << itor.get_triple() << std::endl;
itor.next();
++count;
};
std::cout << "\nThe graph contains " << count << " statements.\n";
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// import_owl_model
//
// main function to import owl model - import to the provided graph
/////////////////////////////////////////////////////////////////////////////////////////
rdf::rdf_graph_ptr_type
import_owl_model(std::string const& fname, rdf::rdf_graph_ptr_type & graph_p, bool verbose)
{
if(verbose) std::cout << "Importing owl model from file " << fname << std::endl;
if(fname.size() == 0) throw rdf::rdf_exception(rdf::parsing_error, "ERROR, invalid file name");
// Initialize the XML4C2 system
try {
XMLPlatformUtils::Initialize();
} catch (const XMLException& toCatch) {
std::cout << "ERROR: XMLException caught while initializing library, message: "
<< strx(toCatch.getMessage()) << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: XMLException caught while initializing library");
}
process_file(fname, graph_p, verbose);
XMLPlatformUtils::Terminate();
process_imported_owl_model(graph_p, verbose);
return graph_p;
};
/////////////////////////////////////////////////////////////////////////////////////////
// import_owl_model
//
// main function to import owl model
/////////////////////////////////////////////////////////////////////////////////////////
rdf::rdf_graph_ptr_type
import_owl_model(std::string const& fname, bool verbose)
{
// parameter can be set here such as pool_size, triple_size, sessions_map_size
// leaving to default for now.
rdf::rdf_graph_ptr_type graph_p = rdf::create_rdf_graph();
return import_owl_model(fname, graph_p, verbose);
};
/////////////////////////////////////////////////////////////////////////////////////////
// import_owl_model_membuffer
//
// main function to import owl model - importing to the provided graph from memory buffer
// unstead of from file
// Import into existing graph
/////////////////////////////////////////////////////////////////////////////////////////
rdf::rdf_graph_ptr_type
import_owl_model_membuffer(std::string const& buffer, rdf::rdf_graph_ptr_type & graph_p, bool verbose)
{
if(verbose) std::cout << "Importing owl model from buffer of size " << buffer.size() << std::endl;
if(buffer.size() == 0) throw rdf::rdf_exception(rdf::parsing_error, "ERROR, invalid buffer size");
// Initialize the XML4C2 system
try {
XMLPlatformUtils::Initialize();
} catch (const XMLException& toCatch) {
std::cout << "ERROR: XMLException caught while initializing library, message: "
<< strx(toCatch.getMessage()) << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: XMLException caught while initializing library");
}
process_membuffer(buffer, graph_p, verbose);
XMLPlatformUtils::Terminate();
process_imported_owl_model(graph_p, verbose);
return graph_p;
};
/////////////////////////////////////////////////////////////////////////////////////////
// import_owl_model_membuffer
//
// main function to import owl model - importing to the provided graph from memory buffer
// unstead of from file
// Import into new graph
/////////////////////////////////////////////////////////////////////////////////////////
rdf::rdf_graph_ptr_type
import_owl_model_membuffer(std::string const& buffer, bool verbose)
{
// parameter can be set here such as pool_size, triple_size, sessions_map_size
// leaving to default for now.
rdf::rdf_graph_ptr_type graph_p = rdf::create_rdf_graph();
return import_owl_model_membuffer(buffer, graph_p, verbose);
};
/////////////////////////////////////////////////////////////////////////////////////////
// process_file
//
/////////////////////////////////////////////////////////////////////////////////////////
void
process_file(std::string const& fname, rdf::rdf_graph_ptr_type & graph_p, bool verbose)
{
// Create a SAX parser object.
// the command line, set it to validate or not.
//
sax_parser_ptr_type parser_p = sax_parser_ptr_type(new SAXParser());
parser_p->setValidationScheme(SAXParser::Val_Never);
// Create the handler object and install it as the document and error
// handler for the parser_p-> Then parse the file and catch any exceptions
// that propogate out
int errorCount = 0;
try {
rdf_handler handler(graph_p, verbose);
parser_p->setDocumentHandler(&handler);
parser_p->setErrorHandler(&handler);
parser_p->parse(fname.c_str());
errorCount = parser_p->getErrorCount();
if(verbose) std::cout << "Error count is " << errorCount << std::endl;
} catch (OutOfMemoryException const&) {
std::cout << "ERROR: OutOfMemoryException caught while importing model" << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: OutOfMemoryException caught while importing owl model");
} catch (XMLException const& toCatch) {
std::cout << "ERROR: XMLException caught while importing model, message: "
<< strx(toCatch.getMessage()) << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: XMLException caught while importing model");
} catch(rdf::rdf_exception const& e) {
std::cout << "ERROR, exception caught with message: '" << e.what()
<< " while importing from file " << fname << std::endl;
throw e;
} catch(...) {
std::cout << "ERROR, unknown exception caught "
<< " while importing from file " << fname << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR, unknown exception!");
}
};
/////////////////////////////////////////////////////////////////////////////////////////
// process_membuffer
//
/////////////////////////////////////////////////////////////////////////////////////////
void
process_membuffer(std::string const& buffer, rdf::rdf_graph_ptr_type & graph_p, bool verbose)
{
// Create a SAX parser object.
// the command line, set it to validate or not.
//
sax_parser_ptr_type parser_p = sax_parser_ptr_type(new SAXParser());
parser_p->setValidationScheme(SAXParser::Val_Never);
// Create the handler object and install it as the document and error
// handler for the parser_p-> Then parse the file and catch any exceptions
// that propogate out
int errorCount = 0;
try {
rdf_handler handler(graph_p, verbose);
parser_p->setDocumentHandler(&handler);
parser_p->setErrorHandler(&handler);
// create an input source
mem_bufinput_source_ptr_type mem_bufinput_source_p =
mem_bufinput_source_ptr_type(new MemBufInputSource(
(const XMLByte*)buffer.c_str(),
buffer.length(),
"memory_buffer",
false));
parser_p->parse(*mem_bufinput_source_p);
errorCount = parser_p->getErrorCount();
if(verbose) std::cout << "Error count is " << errorCount << std::endl;
} catch (OutOfMemoryException const&) {
std::cout << "ERROR: OutOfMemoryException caught while importing model" << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: OutOfMemoryException caught while importing owl model");
} catch (XMLException const& toCatch) {
std::cout << "ERROR: XMLException caught while importing model, message: "
<< strx(toCatch.getMessage()) << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR: XMLException caught while importing model");
} catch(rdf::rdf_exception const& e) {
std::cout << "ERROR, exception caught with message: '" << e.what()
<< " while importing from buffer of size " << buffer.size() << std::endl;
throw e;
} catch(...) {
std::cout << "ERROR, unknown exception caught "
<< " while importing from buffer of size " << buffer.size() << std::endl;
throw rdf::rdf_exception(rdf::parsing_error, "ERROR, unknown exception!");
}
};
}; /* xml namespace */
}; /* parser namespace */
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.