XdmfCoreReader.cpp 29.9 KB
Newer Older
Kenneth Leiter's avatar
Kenneth Leiter committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfCoreReader.cpp                                                  */
/*                                                                           */
/*  Author:                                                                  */
/*     Kenneth Leiter                                                        */
/*     kenneth.leiter@arl.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2011 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/
23

24
#include <libxml/uri.h>
25
#include <libxml/xpointer.h>
26
#include <libxml/xmlreader.h>
27
#include "boost/tokenizer.hpp"
28
#include <map>
29
#include <sstream>
30
#include <cstring>
31 32
#include <utility>
#include "XdmfArray.hpp"
33 34
#include "XdmfArrayType.hpp"
#include "XdmfHDF5Controller.hpp"
35 36
#include "XdmfCoreItemFactory.hpp"
#include "XdmfCoreReader.hpp"
37
#include "XdmfError.hpp"
38
#include "XdmfItem.hpp"
39
#include "XdmfSystemUtils.hpp"
40

41 42 43 44 45 46 47
/**
 * PIMPL
 */
class XdmfCoreReader::XdmfCoreReaderImpl {

public:

48
  XdmfCoreReaderImpl(const shared_ptr<const XdmfCoreItemFactory> itemFactory,
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
                     const XdmfCoreReader * const coreReader) :
    mCoreReader(coreReader),
    mItemFactory(itemFactory)
  {
  };

  ~XdmfCoreReaderImpl()
  {
  };

  void
  closeFile()
  {
    mXPathMap.clear();
    xmlXPathFreeContext(mXPathContext);
64 65 66 67 68 69
    for(std::map<std::string, xmlDocPtr>::const_iterator iter = 
	  mDocuments.begin(); iter != mDocuments.end(); ++iter) {
      xmlFreeDoc(iter->second);
    }
    mDocuments.clear();
    
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    xmlCleanupParser();
  }

  void
  openFile(const std::string & filePath)
  {
    mXMLDir = XdmfSystemUtils::getRealPath(filePath);
    size_t index = mXMLDir.find_last_of("/\\");
    if(index != std::string::npos) {
      mXMLDir = mXMLDir.substr(0, index + 1);
    }

    mDocument = xmlReadFile(filePath.c_str(), NULL, 0);

    if(mDocument == NULL) {
85 86 87 88 89 90 91 92
      try {
        XdmfError::message(XdmfError::FATAL,
                           "xmlReadFile could not read " + filePath +
                           " in XdmfCoreReader::XdmfCoreReaderImpl::openFile");
      }
      catch (XdmfError e) {
        throw e;
      }
93 94
    }

95 96
    mDocuments.insert(std::make_pair((char*)mDocument->URL, mDocument));

97 98 99 100
    mXPathContext = xmlXPtrNewContext(mDocument, NULL, NULL);
    mXPathMap.clear();
  }

101 102 103 104 105 106
  void
  parse(const std::string & lightData) 
  {
    mDocument = xmlParseDoc((const xmlChar*)lightData.c_str());
                               
    if(mDocument == NULL) {
107 108 109 110 111 112 113 114
      try {
        XdmfError::message(XdmfError::FATAL,
                           "xmlReadFile could not parse passed light data string"
                           " in XdmfCoreReader::XdmfCoreReaderImpl::parse");
      }
      catch (XdmfError e) {
        throw e;
      }
115 116
    }

117
    //    mDocuments.insert(std::make_pair((char*)mDocument->URL, mDocument));
118 119 120 121
    mXPathContext = xmlXPtrNewContext(mDocument, NULL, NULL);
    mXPathMap.clear();
  }

122 123 124 125 126
  /**
   * Constructs XdmfItems for all nodes in currNode's tree.
   * XdmfItems are constructed by recursively calling this function for all
   * children of currNode.
   */
127
  std::vector<shared_ptr<XdmfItem> >
128 129
  read(xmlNodePtr currNode)
  {
130
    std::vector<shared_ptr<XdmfItem> > myItems;
131 132 133 134 135

    while(currNode != NULL) {
      if(currNode->type == XML_ELEMENT_NODE) {
        if(xmlStrcmp(currNode->name, (xmlChar*)"include") == 0) {
          // Deal with proper reading of XIncludes
136 137 138 139

          xmlChar * xpointer = NULL;
          xmlChar * href = NULL;

140 141 142 143 144
          xmlAttrPtr currAttribute = currNode->properties;
          while(currAttribute != NULL) {
            if(xmlStrcmp(currAttribute->name, (xmlChar*)"xpointer") == 0) {
              xpointer = currAttribute->children->content;
            }
145 146 147 148 149 150 151 152
            if(xmlStrcmp(currAttribute->name, (xmlChar*)"href") == 0) {
              href = currAttribute->children->content;
            }
            currAttribute = currAttribute->next;
          }

          xmlXPathContextPtr context = mXPathContext;
          if(href) {
153
	    xmlDocPtr document;
154
            xmlChar * filePath = xmlBuildURI(href, mDocument->URL);
155 156 157 158 159 160 161 162 163 164
	    std::map<std::string, xmlDocPtr>::const_iterator iter = 
	      mDocuments.find((char*)filePath);
	    if(iter == mDocuments.end()) {
	      document = xmlReadFile((char*)filePath, NULL, 0);
	      mDocuments.insert(std::make_pair((char*)document->URL, document));
	    }
	    else {
	      document = iter->second;
	    }

165
            context = xmlXPtrNewContext(document, NULL, NULL);           
166
          }
167

168
          if(xpointer) {
169 170 171 172
            xmlXPathObjectPtr result = xmlXPtrEval(xpointer, context);
            if(result && !xmlXPathNodeSetIsEmpty(result->nodesetval)) {
              for(int i=0; i<result->nodesetval->nodeNr; ++i) {
                this->readSingleNode(result->nodesetval->nodeTab[i],
173 174 175
                                     myItems);
              }
            }
176 177 178 179 180
            xmlXPathFreeObject(result);
          }

          if(href) {
            xmlXPathFreeContext(context);
181
          }
182

183
        }
184
        else if (xmlStrcmp(currNode->name, (xmlChar*)"Function") == 0) {
185
          // function handling goes here
186 187 188
          xmlNodePtr childNode = currNode->children;

          std::string arraySubType = "";
189
          // get Array Subtype, if any
190 191 192 193
          xmlAttrPtr currAttribute = currNode->properties;
          while (currAttribute != NULL) {
            if (xmlStrcmp(currAttribute->name, (xmlChar*)"Type") == 0 ) {
              arraySubType = (char*)currAttribute->children->content;
194 195
              break;
              // uses the first type found
196 197 198 199 200 201 202
            }
          }

          std::string expressionToParse = "";

          while (childNode != NULL) {
            if (xmlStrcmp(childNode->name, (xmlChar*)"Expression") == 0){
203
              // store expression
204 205 206 207 208 209 210 211 212 213 214 215 216 217
              xmlAttrPtr childAttribute = childNode->properties;
              while (childAttribute != NULL) {
                if(xmlStrcmp(childAttribute->name, (xmlChar*)"Value") == 0) {
                  expressionToParse = (char*)childAttribute->children->content;
                  break;
                }
                childAttribute = childAttribute->next;
              }
              break;
            }
            childNode = childNode->next;
          }

          if (expressionToParse.compare("") == 0) {
218 219 220 221 222 223 224
            try {
              XdmfError::message(XdmfError::FATAL,
                "Error: No Expression in Function");
            }
            catch (XdmfError e) {
              throw e;
            }
225 226
          }

227
          // two seperate loops to allow for different orders and multiple variable sets
228 229 230 231 232
          childNode = currNode->children;

          std::map<std::string, shared_ptr<XdmfArray> > variableCollection;
          while (childNode != NULL) {
            if (xmlStrcmp(childNode->name, (xmlChar*)"Variable") == 0) {
233
              // store child variables
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
              xmlNodePtr childVariable = childNode->children;

              while (childVariable != NULL) {
                if (xmlStrcmp(childVariable->name, (xmlChar*)"DataItem") == 0) {
                  xmlAttrPtr childAttribute = childVariable->properties;
                  std::string childKey = "";
                  shared_ptr<XdmfArray> childArray = XdmfArray::New();
                  std::string dataString = "";
                  shared_ptr<const XdmfArrayType> dataType;
                  xmlChar * childXPointer = NULL;
                  xmlChar * childhref = NULL;
                  std::string childhdf5 = "";
                  std::map<std::string, std::string> typeMap;

                  while (childAttribute != NULL) {
249
                    // the variable type of the array
250 251 252
                    if (xmlStrcmp(childAttribute->name, (xmlChar*)"DataType") == 0) {
                      typeMap["DataType"] = (char*)childAttribute->children->content;
                    }
253
                    // the precision of the variable type (only used for long and double)
254 255 256
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Precision") == 0) {
                      typeMap["Precision"] = (char*)childAttribute->children->content;
                    }
257
                    // the key or mapped string for the variable
258 259 260
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Key") == 0) {
                      childKey = (char*)childAttribute->children->content;
                    }
261
                    // text based xml data
262 263 264
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"Value") == 0) {
                      dataString = (char*)childAttribute->children->content;
                    }
265
                    // an x pointer to another XdmfArray
266 267 268
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"XPointer") == 0) {
                      childXPointer = childAttribute->children->content;
                    }
269
                    // used in conjunction with Xpointers to reference objects in a different file
270 271 272
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"href") == 0) {
                      childhref = childAttribute->children->content;
                    }
273
                    // path to hdf5 data sets and the dimensions of those sets
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
                    else if (xmlStrcmp(childAttribute->name, (xmlChar*)"hdf5") == 0) {
                      childhdf5 = (char*)childAttribute->children->content;
                    }
                    childAttribute = childAttribute->next;
                  }

                  if (typeMap["DataType"].compare("Float") == 0) {
                    if (typeMap["Precision"].compare("8") == 0) {
                      dataType = XdmfArrayType::Float64();
                    }
                    else {
                      dataType = XdmfArrayType::Float32();
                    }
                  }
                  else if (typeMap["DataType"].compare("Int") == 0) {
                    if (typeMap["Precision"].compare("8") == 0) {
                      dataType = XdmfArrayType::Int64();
                    }
                    else {
                      dataType = XdmfArrayType::Int32();
                    }
                  }
                  else if (typeMap["DataType"].compare("String") == 0) {
                    dataType = XdmfArrayType::String();
                  }
                  else if (typeMap["DataType"].compare("Char") == 0) {
                    dataType = XdmfArrayType::Int8();
                  }
                  else if (typeMap["DataType"].compare("Short") == 0) {
                    dataType = XdmfArrayType::Int16();
                  }
                  else if (typeMap["DataType"].compare("UChar") == 0) {
                    dataType = XdmfArrayType::UInt8();
                  }
                  else if (typeMap["DataType"].compare("UShort") == 0) {
                    dataType = XdmfArrayType::UInt16();
                  }
                  else if (typeMap["DataType"].compare("UInt") == 0) {
                    dataType = XdmfArrayType::UInt32();
                  }
                  else {
                    dataType = XdmfArrayType::Uninitialized();
                  }

318
                  // if xpointer grab item at that location
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
                  if (childXPointer) {
                    xmlXPathContextPtr context = mXPathContext;

                    if(childhref) {
                      xmlDocPtr document;
                      xmlChar * filePath = xmlBuildURI(childhref, mDocument->URL);
                      std::map<std::string, xmlDocPtr>::const_iterator iter =
                        mDocuments.find((char*)filePath);
                      if(iter == mDocuments.end()) {
                        document = xmlReadFile((char*)filePath, NULL, 0);
                        mDocuments.insert(std::make_pair((char*)document->URL, document));
                      }
                      else {
                        document = iter->second;
                      }
                      context = xmlXPtrNewContext(document, NULL, NULL);
                    }

                    if(childXPointer) {
                      xmlXPathObjectPtr result = xmlXPtrEval(childXPointer, context);
                      if(result && !xmlXPathNodeSetIsEmpty(result->nodesetval)) {
                        for(int i=0; i<result->nodesetval->nodeNr; ++i) {
341 342
                          // there should only be one item being returned here
                          // place into a new vector
343 344 345
                          std::vector<shared_ptr<XdmfItem> > pointedItems;
                          this->readSingleNode(result->nodesetval->nodeTab[i], pointedItems);
                          try {
346 347
                            // try to cast it as an array
                            childArray = shared_dynamic_cast<XdmfArray>(pointedItems[0]);
348
                          }
349 350
                          catch (...) {
                            // if that doesn't work throw an error
351
                            try {
352
                              // because we should only be working with arrays
353
                              XdmfError::message(XdmfError::FATAL,
354
                                                 "Error: Variable not Equivalent to an Array");
355 356 357 358
                            }
                            catch (XdmfError e) {
                              throw e;
                            }
359 360 361 362 363 364 365 366 367 368
                          }
                        }
                      }
                      xmlXPathFreeObject(result);
                    }

                    if(childhref) {
                      xmlXPathFreeContext(context);
                    }
                  }
369
                  // if hdf5 create controllers and attach it
370
                  else if (childhdf5.compare("") != 0) {
371
                    // parse the hdf5 controllers
372
                    std::vector<std::string> controllerParts;
373
                    // split the content based on "|" characters
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
                    size_t barSplit = 0;
                    std::string splitString(childhdf5);
                    std::string subcontent;

                    while (barSplit != std::string::npos) {
                      barSplit = 0;
                      barSplit = splitString.find_first_of("|", barSplit);
                      if (barSplit == std::string::npos) {
                        subcontent = splitString;
                      }
                      else {
                        subcontent = splitString.substr(0, barSplit);
                        splitString = splitString.substr(barSplit+1);
                        barSplit++;
                      }
                      controllerParts.push_back(subcontent);
                    }

392
                    // insert those controllers into the childArray
393
                    int hdf5step = 2;
394
                    for (unsigned int i = 0; i < controllerParts.size(); i = i + hdf5step) {
395 396
                      size_t colonLocation = controllerParts[i].find(":");
                      if(colonLocation == std::string::npos) {
397 398 399 400 401 402 403 404 405
                        try {
                          XdmfError::message(XdmfError::FATAL,
                                             "':' not found in function variable content in "
                                             "read -- double check an HDF5 "
                                             "data set is specified for the file");
                        }
                        catch (XdmfError e) {
                          throw e;
                        }
406 407 408 409 410 411
                      }

                      std::string hdf5Path = controllerParts[i].substr(0, colonLocation);
                      std::string dataSetPath = controllerParts[i].substr(colonLocation+1);
                      std::vector<unsigned int> contentDims;

412
                      if (i + 1 < controllerParts.size()){
413
                        // this is the string that contains the dimensions
414 415 416 417 418 419
                        boost::tokenizer<> dimtokens(controllerParts[i + 1]);
                        for(boost::tokenizer<>::const_iterator iter = dimtokens.begin();
                            iter != dimtokens.end();
                            ++iter) {
                          contentDims.push_back(atoi((*iter).c_str()));
                        }
420
                        hdf5step = 2;// if this works then the dimension content should be skipped over
421
                      }
422 423 424 425
                      else {
                        // if it fails then it means that the next content is not a dimension string
                        // in this case an error should be thrown, formatting error
                        // because there is no base array to pull dimensions from
426 427 428 429 430 431 432
                        try {
                          XdmfError::message(XdmfError::FATAL,
                                             "Error: Improper HDF5 Format");
                        }
                        catch (XdmfError e) {
                          throw e;
                        }
433 434 435 436 437 438 439 440 441 442 443
                      }

                      childArray->insert(XdmfHDF5Controller::New(hdf5Path,
                                                                 dataSetPath,
                                                                 dataType,
                                                                 std::vector<unsigned int>(contentDims.size(), 0),
                                                                 std::vector<unsigned int>(contentDims.size(), 1),
                                                                 contentDims,
                                                                 contentDims));
                    }
                  }
444
                  // if xml parse strait to insert
445
                  else if (dataString.compare("") != 0) {
446
                    // parse the data into tokens
447 448 449 450 451 452 453 454 455
                    childArray->initialize(dataType, 0);
                    unsigned int index = 0;
                    boost::char_separator<char> sep(" \t\n");
                    boost::tokenizer<boost::char_separator<char> > tokens(dataString, sep);
                    if(dataType == XdmfArrayType::String()) {
                      for(boost::tokenizer<boost::char_separator<char> >::const_iterator
                          iter = tokens.begin();
                          iter != tokens.end();
                          ++iter, ++index) {
456
                        // insert those tokens into the childArray
457 458 459 460 461 462 463 464
                        childArray->insert(index, *iter);
                      }
                    }
                    else {
                      for(boost::tokenizer<boost::char_separator<char> >::const_iterator
                          iter = tokens.begin();
                          iter != tokens.end();
                          ++iter, ++index) {
465
                        // insert those tokens into the childArray
466 467 468 469 470
                        childArray->insert(index, atof((*iter).c_str()));
                      }
                    }
                  }

471
                  // parse the value into the array
472 473
                  if (childKey.compare("") != 0){
                    if (variableCollection.find(childKey) != variableCollection.end()) {
474 475 476 477 478 479 480
                      try {
                        XdmfError::message(XdmfError::WARNING,
                                           "Warning: Variable Redefined");
                      }
                      catch (XdmfError e) {
                        throw e;
                      }
481 482 483 484 485
                    }
                    childArray->read();
                    variableCollection[childKey] = childArray;
                  }
                  else {
486 487 488 489 490 491 492
                    try {
                      XdmfError::message(XdmfError::WARNING,
                                         "Warning: Value Unpaired to Key");
                    }
                    catch (XdmfError e) {
                      throw e;
                    }
493 494 495 496 497 498 499
                  }
                }
                childVariable = childVariable->next;
              }
            }
            childNode = childNode->next;
          }
500 501 502 503 504 505 506
          shared_ptr<XdmfArray> parsedArray = shared_ptr<XdmfArray>();
          try {
            parsedArray = XdmfArray::evaluateExpression(expressionToParse, variableCollection);
          }
          catch (XdmfError e) {
            throw e;
          }
507
          // the properties and children aren't really needed to generate the object, but the factory still requires them.
508 509 510 511
          std::map<std::string, std::string> newArrayProperties;
          std::vector<shared_ptr<XdmfItem> > newArrayChildren;
          shared_ptr<XdmfArray> returnArray = XdmfArray::New();

512 513
          if (arraySubType.compare("") == 0) {
            // if no type is specified an array is generated
514 515 516
            arraySubType = "DataItem";
          }

517 518
          // this should generate an item that corresponds to the tag provided, the casting ensures that it is a subtype of array
          // using a factory to be able to build things outside of core
519 520 521 522 523
          returnArray = shared_dynamic_cast<XdmfArray>(mItemFactory->createItem(
                                                       arraySubType,
                                                       newArrayProperties,
                                                       newArrayChildren));

524 525
          if (!returnArray) {
            // if the specified tag fails to generate an item then reclass as an array
526 527 528 529 530 531 532 533 534 535
            arraySubType = "DataItem";
            returnArray = shared_dynamic_cast<XdmfArray>(mItemFactory->createItem(
                                                         arraySubType,
                                                         newArrayProperties,
                                                         newArrayChildren));
          }

          returnArray->insert(0, parsedArray, 0, parsedArray->getSize());
          myItems.push_back(returnArray);
        }
536 537
        else {
          // Normal reading
538 539 540 541 542 543
          try {
            this->readSingleNode(currNode, myItems);
          }
          catch (XdmfError e) {
            throw e;
          }
544 545 546 547 548 549 550 551 552 553 554 555 556 557
        }
      }
      currNode = currNode->next;
    }
    return myItems;
  }

  /**
   * Reads a single xmlNode into an XdmfItem object in memory. The constructed
   * XdmfItem is added to myItems and an entry is added mapping the xmlNodePtr
   * to the new XdmfItem in the mXPathMap.
   */
  void
  readSingleNode(const xmlNodePtr currNode,
558
                 std::vector<shared_ptr<XdmfItem> > & myItems)
559
  {
560
    // check to see if the node is already in the Xpath
561
    std::map<xmlNodePtr, shared_ptr<XdmfItem> >::const_iterator iter =
562
      mXPathMap.find(currNode);
563 564
    // if it is grab it from the previously stored items
    if(iter != mXPathMap.end()) {
565 566
      myItems.push_back(iter->second);
    }
567 568
    else {
      // otherwise, generate it from the node
569
      std::map<std::string, std::string> itemProperties;
570 571

      xmlNodePtr childNode = currNode->children;
572
      if (XdmfArray::ItemTag.compare((char *)currNode->name) == 0) {
573
	unsigned int childContentIndex = 0;
574 575 576 577 578 579 580 581
        while(childNode != NULL) {
          if(childNode->type == XML_TEXT_NODE && childNode->content) {
            const char * content = (char*)childNode->content;
            
            // determine if content is whitespace
            bool whitespace = true;
            
            const char * contentPtr = content;
582
            // step through to end of pointer
583
            while(contentPtr != NULL) {
584
              // if not a whitespace character, break
585 586 587 588 589 590 591
              if(!isspace(*contentPtr++)) {
                whitespace = false;
                break;
              }
            }
            
            if(!whitespace) {
592 593 594 595
              if (childContentIndex == 0) {
                itemProperties.insert(std::make_pair("XMLDir", mXMLDir));
              }

596
              // split the content based on "|" characters
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
              size_t barSplit = 0;
              std::string splitString(content);
              std::string subcontent;
              while (barSplit != std::string::npos) {
		barSplit = 0;
                barSplit = splitString.find_first_of("|", barSplit);
                if (barSplit == std::string::npos) {
                  subcontent = splitString;
                }
                else {
                  subcontent = splitString.substr(0, barSplit);
                  splitString = splitString.substr(barSplit+1);
                  barSplit++;
                }
                std::stringstream contentString;
                contentString << "Content" << childContentIndex;
                itemProperties.insert(std::make_pair(contentString.str(), subcontent));
		childContentIndex++;
              }
616 617
            }
          }
618
          childNode = childNode->next;
619
        }
620
      }
621 622
    
 
623 624
      xmlAttrPtr currAttribute = currNode->properties;
      while(currAttribute != NULL) {
625 626
        itemProperties.insert(std::make_pair((char *)currAttribute->name,
                                             (char *)currAttribute->children->content));
627 628
        currAttribute = currAttribute->next;
      }
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
      try {
        const std::vector<shared_ptr<XdmfItem> > childItems =
          this->read(currNode->children);
        shared_ptr<XdmfItem> newItem = 
          mItemFactory->createItem((const char *)currNode->name,
                                   itemProperties,
                                   childItems);
      
        if(newItem == NULL) {
          try {
            XdmfError::message(XdmfError::FATAL, 
                               "mItemFactory failed to createItem in "
                               "XdmfCoreReader::XdmfCoreReaderImpl::readSingleNode");
          }
          catch (XdmfError e) {
            throw e;
          }
        }
        newItem->populateItem(itemProperties, childItems, mCoreReader);
        myItems.push_back(newItem);
        mXPathMap.insert(std::make_pair(currNode, newItem));
      }
      catch (XdmfError e) {
        throw e;
653 654 655 656 657 658
      }
    }
  }

  void
  readPathObjects(const std::string & xPath,
659
                  std::vector<shared_ptr<XdmfItem> > & myItems)
660 661 662 663 664
  {
    xmlXPathObjectPtr xPathObject =
      xmlXPathEvalExpression((xmlChar*)xPath.c_str(), mXPathContext);
    if(xPathObject && xPathObject->nodesetval) {
      for(int i=0; i<xPathObject->nodesetval->nodeNr; ++i) {
665 666 667 668 669 670
        try {
          this->readSingleNode(xPathObject->nodesetval->nodeTab[i], myItems);
        }
        catch (XdmfError e) {
          throw e;
        }
671 672 673 674 675 676
      }
    }
    xmlXPathFreeObject(xPathObject);
  }

  xmlDocPtr mDocument;
677
  std::map<std::string, xmlDocPtr> mDocuments;
678
  const XdmfCoreReader * const mCoreReader;
679
  const shared_ptr<const XdmfCoreItemFactory> mItemFactory;
680 681
  std::string mXMLDir;
  xmlXPathContextPtr mXPathContext;
682
  std::map<xmlNodePtr, shared_ptr<XdmfItem> > mXPathMap;
683 684
};

685
XdmfCoreReader::XdmfCoreReader(const shared_ptr<const XdmfCoreItemFactory> itemFactory) :
686
  mImpl(new XdmfCoreReaderImpl(itemFactory, this))
687 688 689 690 691
{
}

XdmfCoreReader::~XdmfCoreReader()
{
692
  delete mImpl;
693 694
}

695 696 697
shared_ptr<XdmfItem >
XdmfCoreReader::parse(const std::string & lightData) const
{
698 699 700 701 702 703
  try {
    mImpl->parse(lightData);
  }
  catch (XdmfError e) {
    throw e;
  }
704
  const xmlNodePtr currNode = xmlDocGetRootElement(mImpl->mDocument);
705
  std::vector<shared_ptr<XdmfItem> > toReturn;
706 707 708 709 710 711 712 713 714
  try {
    if(mImpl->mItemFactory->createItem((const char*)currNode->name,
                                       std::map<std::string, std::string>(),
                                       std::vector<shared_ptr<XdmfItem> >()) == NULL) {
      toReturn = mImpl->read(currNode->children);
    }
    else {
      toReturn = mImpl->read(currNode);
    }
715
  }
716 717
  catch (XdmfError e) {
    throw e;
718
  }
719 720 721 722
  mImpl->closeFile();
  return(toReturn[0]);
}

723
std::vector<shared_ptr<XdmfItem> >
724
XdmfCoreReader::readItems(const std::string & filePath) const
725
{
726 727 728 729 730 731 732 733 734 735 736 737
  try {
    mImpl->openFile(filePath);
    const xmlNodePtr currNode = xmlDocGetRootElement(mImpl->mDocument);
    const std::vector<shared_ptr<XdmfItem> > toReturn =
      mImpl->read(currNode->children);
    mImpl->closeFile();
    return toReturn;
  }
  catch (XdmfError e) {
    throw e;
  }

738 739
}

740
shared_ptr<XdmfItem>
741
XdmfCoreReader::read(const std::string & filePath) const
742
{
743 744 745 746 747 748 749 750 751
  try {
    const std::vector<shared_ptr<XdmfItem> > toReturn = readItems(filePath);
    if (toReturn.size() == 0) {
      return(shared_ptr<XdmfItem>());
    }
    return(toReturn[0]);
  }
  catch (XdmfError e) {
    throw e;
752
  }
753
}
754

755
std::vector<shared_ptr<XdmfItem> >
756 757
XdmfCoreReader::read(const std::string & filePath,
                     const std::string & xPath) const
758
{
759 760 761 762 763 764 765 766 767
  try {
    mImpl->openFile(filePath);
    std::vector<shared_ptr<XdmfItem> > toReturn = this->readPathObjects(xPath);
    mImpl->closeFile();
    return toReturn;
  }
  catch (XdmfError e) {
    throw e;
  }
768
}
769

770
std::vector<shared_ptr<XdmfItem> >
771
XdmfCoreReader::readPathObjects(const std::string & xPath) const
772
{
773
  std::vector<shared_ptr<XdmfItem> > toReturn;
774 775 776 777 778 779
  try {
    mImpl->readPathObjects(xPath, toReturn);
  }
  catch (XdmfError e) {
    throw e;
  }
780
  return toReturn;
781 782
}