Esempio n. 1
0
/**
 * Return the confidence with with this algorithm can load the file
 * @param descriptor A descriptor for the file
 * @returns An integer specifying the confidence level. 0 indicates it will not
 * be used
 */
int LoadSpice2D::confidence(Kernel::FileDescriptor &descriptor) const {
  if (descriptor.extension() != ".xml")
    return 0;

  std::istream &is = descriptor.data();
  int confidence(0);

  { // start of inner scope
    Poco::XML::InputSource src(is);
    // Set up the DOM parser and parse xml file
    DOMParser pParser;
    Poco::AutoPtr<Document> pDoc;
    try {
      pDoc = pParser.parse(&src);
    } catch (Poco::Exception &e) {
      throw Kernel::Exception::FileError("Unable to parse File (" +
                                             descriptor.filename() + ")",
                                         e.displayText());

    } catch (...) {
      throw Kernel::Exception::FileError("Unable to parse File:",
                                         descriptor.filename());
    }
    // Get pointer to root element
    Element *pRootElem = pDoc->documentElement();
    if (pRootElem) {
      if (pRootElem->tagName() == "SPICErack") {
        confidence = 80;
      }
    }
  } // end of inner scope

  return confidence;
}
Esempio n. 2
0
/**checks the file by opening it and reading few lines 
 *  @param filePath :: name of the file inluding its path
 *  @return an integer value how much this algorithm can load the file 
 */
    int LoadSpice2D::fileCheck(const std::string& filePath)
    {      
      // Set up the DOM parser and parse xml file
      DOMParser pParser;
      Document* pDoc;
      try
      {
        pDoc = pParser.parse(filePath);
      } catch (...)
      {
        throw Kernel::Exception::FileError("Unable to parse File:", filePath);
      }

      int confidence(0);
      // Get pointer to root element
      Element* pRootElem = pDoc->documentElement();
      if(pRootElem)
      {
        if(pRootElem->tagName().compare("SPICErack") == 0)
        {
          confidence = 80;
        }
      }
      pDoc->release();
      return confidence;
    }
Esempio n. 3
0
void LoadParameterFile::execManually(bool useString, std::string filename, std::string parameterXML,  Mantid::API::ExperimentInfo_sptr localWorkspace)
{
  // TODO: Refactor to remove the need for the const cast (ticket #8521)
  Instrument_sptr instrument = boost::const_pointer_cast<Instrument>(localWorkspace->getInstrument()->baseInstrument());

  // Set up the DOM parser and parse xml file
  DOMParser pParser;
  AutoPtr<Document> pDoc;

  if(useString){
    try
    {
      pDoc = pParser.parseString(parameterXML);
    }
    catch(Poco::Exception& exc)
    {
      throw Kernel::Exception::FileError (exc.displayText() + ". Unable to parse parameter XML string","ParameterXML");
    }
    catch(...)
    {
      throw Kernel::Exception::FileError("Unable to parse parameter XML string","ParameterXML");
    }
  } 
  else
  {
    try
    {
      pDoc = pParser.parse(filename);
    }
    catch(Poco::Exception& exc)
    {
      throw Kernel::Exception::FileError(exc.displayText() + ". Unable to parse File:", filename);
    }
    catch(...)
    {
      throw Kernel::Exception::FileError("Unable to parse File:" , filename);
    }
  }

  // Get pointer to root element
  Element* pRootElem = pDoc->documentElement();
  if ( !pRootElem->hasChildNodes() )
  {
    throw Kernel::Exception::InstrumentDefinitionError("No root element in XML Parameter file", filename);
  }

  // 
  InstrumentDefinitionParser loadInstr;
  loadInstr.setComponentLinks(instrument, pRootElem);

  // populate parameter map of workspace 
  localWorkspace->populateInstrumentParameters();

}
Esempio n. 4
0
/**
 * Takes a stream that is assumed to contain a single complete material
 * definition,
 * reads the definition and produces a new Material object. If many definitions
 * are present then the first one is read
 * @param istr A reference to a stream
 * @return A new Material object
 */
Material MaterialXMLParser::parse(std::istream &istr) const {
  using namespace Poco::XML;
  typedef AutoPtr<Document> DocumentPtr;

  InputSource src(istr);
  DOMParser parser;
  // Do not use auto here or anywhereas the Poco API returns raw pointers
  // but in some circumstances requires AutoPtrs to manage the memory
  DocumentPtr doc;
  try {
    doc = parser.parse(&src);
  } catch (SAXParseException &exc) {
    std::ostringstream os;
    os << "MaterialXMLReader::read() - Error parsing stream as XML: "
       << exc.what();
    throw std::invalid_argument(os.str());
  }

  Element *rootElement = doc->documentElement();

  // Iterating is apparently much faster than getElementsByTagName
  NodeIterator nodeIter(rootElement, NodeFilter::SHOW_ELEMENT);
  Node *node = nodeIter.nextNode();
  Material matr;
  bool found(false);
  while (node) {
    if (node->nodeName() == MATERIAL_TAG) {
      matr = parse(static_cast<Element *>(node));
      found = true;
      break;
    }
    node = nodeIter.nextNode();
  }
  if (!found) {
    throw std::invalid_argument(
        "MaterialXMLReader::read() - No material tags found.");
  }
  return matr;
}
Esempio n. 5
0
/** Executes the algorithm
 *
 *  @throw Exception::FileError If the grouping file cannot be opened or read successfully
 *  @throw runtime_error If unable to run one of the Child Algorithms successfully
 */
void CreateDummyCalFile::exec()
{
    // Get the input workspace
    MatrixWorkspace_const_sptr inputW = getProperty("InputWorkspace");
    if (!inputW)
        throw std::invalid_argument("No InputWorkspace");

    //Get some stuff from the input workspace
    Instrument_const_sptr inst = inputW->getInstrument();
    std::string instname = inst->getName();

    // Check that the instrument is in store
    // Get only the first 3 letters
    std::string instshort=instname;
    std::transform(instshort.begin(),instshort.end(),instshort.begin(),toupper);
    instshort=instshort+"_Definition.xml";
    // Determine the search directory for XML instrument definition files (IDFs)
    std::string directoryName = Kernel::ConfigService::Instance().getInstrumentDirectory();

    // Set up the DOM parser and parse xml file
    DOMParser pParser;
    Document* pDoc;
    try
    {
        pDoc = pParser.parse(directoryName+instshort);
    }
    catch(...)
    {
        g_log.error("Unable to parse file " + m_filename);
        throw Kernel::Exception::FileError("Unable to parse File:" , m_filename);
    }
    // Get pointer to root element
    Element* pRootElem = pDoc->documentElement();
    if ( !pRootElem->hasChildNodes() )
    {
        g_log.error("XML file: " + m_filename + "contains no root element.");
        throw Kernel::Exception::InstrumentDefinitionError("No root element in XML instrument file", m_filename);
    }

    // Handle used in the singleton constructor for instrument file should append the value
    // of the last-modified tag inside the file to determine if it is already in memory so that
    // changes to the instrument file will cause file to be reloaded.
    auto temp = instshort + pRootElem->getAttribute("last-modified");// Generate the mangled name by hand (old-style)

    // If instrument not in store, insult the user
    if (!API::InstrumentDataService::Instance().doesExist(temp))
    {
        Mantid::Geometry::IDFObject idf(directoryName+instshort);
        temp = idf.getMangledName(); // new style.
        if (!API::InstrumentDataService::Instance().doesExist(temp))
        {
            g_log.error("Instrument "+instshort+" is not present in data store.");
            throw std::runtime_error("Instrument "+instshort+" is not present in data store.");
        }
    }

    // Get the names of groups
    groups=instname;

    // Split the names of the group and insert in a vector, throw if group empty
    std::vector<std::string> vgroups;
    boost::split( vgroups, instname, boost::algorithm::detail::is_any_ofF<char>(",/*"));
    if (vgroups.empty())
    {
        g_log.error("Could not determine group names. Group names should be separated by / or ,");
        throw std::runtime_error("Could not determine group names. Group names should be separated by / or ,");
    }

    // Assign incremental number to each group
    std::map<std::string,int> group_map;
    int index=0;
    for (std::vector<std::string>::const_iterator it=vgroups.begin(); it!=vgroups.end(); ++it)
        group_map[(*it)]=++index;

    // Not needed anymore
    vgroups.clear();

    // Find Detectors that belong to groups
    typedef boost::shared_ptr<const Geometry::ICompAssembly> sptr_ICompAss;
    typedef boost::shared_ptr<const Geometry::IComponent> sptr_IComp;
    typedef boost::shared_ptr<const Geometry::IDetector> sptr_IDet;
    std::queue< std::pair<sptr_ICompAss,int> > assemblies;
    sptr_ICompAss current=boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(inst);
    sptr_IDet currentDet;
    sptr_IComp currentIComp;
    sptr_ICompAss currentchild;

    int top_group, child_group;

    if (current.get())
    {
        top_group=group_map[current->getName()]; // Return 0 if not in map
        assemblies.push(std::make_pair(current,top_group));
    }

    std::string filename=getProperty("CalFilename");

    // Plan to overwrite file, so do not check if it exists
    bool overwrite=false;

    int number=0;
    Progress prog(this,0.0,0.8,assemblies.size());
    while(!assemblies.empty()) //Travel the tree from the instrument point
    {
        current=assemblies.front().first;
        top_group=assemblies.front().second;
        assemblies.pop();
        int nchilds=current->nelements();
        if (nchilds!=0)
        {
            for (int i=0; i<nchilds; ++i)
            {
                currentIComp=(*(current.get()))[i]; // Get child
                currentDet=boost::dynamic_pointer_cast<const Geometry::IDetector>(currentIComp);
                if (currentDet.get())// Is detector
                {
                    if (overwrite) // Map will contains udet as the key
                        instrcalib[currentDet->getID()]=std::make_pair(number++,top_group);
                    else          // Map will contains the entry number as the key
                        instrcalib[number++]=std::make_pair(currentDet->getID(),top_group);
                }
                else // Is an assembly, push in the queue
                {
                    currentchild=boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(currentIComp);
                    if (currentchild.get())
                    {
                        child_group=group_map[currentchild->getName()];
                        if (child_group==0)
                            child_group=top_group;
                        assemblies.push(std::make_pair(currentchild,child_group));
                    }
                }
            }
        }
        prog.report();
    }
    // Write the results in a file
    saveGroupingFile(filename,overwrite);
    progress(0.2);
    return;
}
Esempio n. 6
0
/*****************************************************************************
 * Open:
 *****************************************************************************/
static int Open(vlc_object_t *p_obj)
{
    demux_t *p_demux = (demux_t*) p_obj;

    if(!p_demux->s->psz_url)
        return VLC_EGENERIC;

    std::string mimeType;

    char *psz_mime = stream_ContentType(p_demux->s);
    if(psz_mime)
    {
        mimeType = std::string(psz_mime);
        free(psz_mime);
    }

    PlaylistManager *p_manager = NULL;

    char *psz_logic = var_InheritString(p_obj, "adaptive-logic");
    AbstractAdaptationLogic::LogicType logic = AbstractAdaptationLogic::Default;
    if( psz_logic )
    {
        for(size_t i=0;i<ARRAY_SIZE(pi_logics); i++)
        {
            if(!strcmp(psz_logic, ppsz_logics_values[i]))
            {
                logic = pi_logics[i];
                break;
            }
        }
        free( psz_logic );
    }

    std::string playlisturl(p_demux->s->psz_url);

    bool dashmime = DASHManager::mimeMatched(mimeType);
    bool smoothmime = SmoothManager::mimeMatched(mimeType);

    if(!dashmime && !smoothmime && HLSManager::isHTTPLiveStreaming(p_demux->s))
    {
        M3U8Parser parser;
        M3U8 *p_playlist = parser.parse(VLC_OBJECT(p_demux),p_demux->s, playlisturl);
        if(!p_playlist)
        {
            msg_Err( p_demux, "Could not parse playlist" );
            return VLC_EGENERIC;
        }

        p_manager = new (std::nothrow) HLSManager(p_demux, p_playlist,
                                                  new (std::nothrow) HLSStreamFactory, logic);
    }
    else
    {
        /* Handle XML Based ones */
        DOMParser xmlParser; /* Share that xml reader */
        if(dashmime)
        {
            p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
        }
        else if(smoothmime)
        {
            p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
        }
        else
        {
            /* We need to probe content */
            const uint8_t *p_peek;
            const ssize_t i_peek = vlc_stream_Peek(p_demux->s, &p_peek, 2048);
            if(i_peek > 0)
            {
                stream_t *peekstream = vlc_stream_MemoryNew(p_demux, const_cast<uint8_t *>(p_peek), (size_t)i_peek, true);
                if(peekstream)
                {
                    if(xmlParser.reset(peekstream) && xmlParser.parse(false))
                    {
                        if(DASHManager::isDASH(xmlParser.getRootNode()))
                        {
                            p_manager = HandleDash(p_demux, xmlParser, playlisturl, logic);
                        }
                        else if(SmoothManager::isSmoothStreaming(xmlParser.getRootNode()))
                        {
                            p_manager = HandleSmooth(p_demux, xmlParser, playlisturl, logic);
                        }
                    }
                    vlc_stream_Delete(peekstream);
                }
            }
        }
    }

    if(!p_manager || !p_manager->start())
    {
        delete p_manager;
        return VLC_EGENERIC;
    }

    p_demux->p_sys         = reinterpret_cast<demux_sys_t *>(p_manager);
    p_demux->pf_demux      = p_manager->demux_callback;
    p_demux->pf_control    = p_manager->control_callback;

    msg_Dbg(p_obj,"opening playlist file (%s)", p_demux->psz_location);

    return VLC_SUCCESS;
}
Esempio n. 7
0
bool S21RLDLNAConfigParser::Parse(const char* configFilePath)
{
	std::ifstream configFile(configFilePath);

	if (configFile.is_open())
	{
		try
		{
			InputSource src(configFile);
			DOMParser parser;
			AutoPtr<Document> pDoc = parser.parse(&src);

			Element* root = pDoc->documentElement();

			if (root->tagName() != PREFERENCE_STREAMING21)
			{
				return false;
			}

			Element* msElement = root->getChildElement(PREFERENCE_MEDIASERVER);
			if (!msElement)
			{
				return false;
			}

			Element* cdElement = msElement->getChildElement(PREFERENCE_CONTENT_DIRECTORY);
			if (!cdElement)
			{
				return false;
			}

			m_ChannelList.clear();
			m_DirectoryList.clear();

			Element* clElement = cdElement->getChildElement(PREFERENCE_CHANNEL_LIST);

			if (clElement)
			{
				AutoPtr<NodeList> cElementList = clElement->getElementsByTagName(PREFERENCE_CHANNEL);
				unsigned long length = cElementList->length();

				for (unsigned long i = 0; i < length; i++)
				{
					Element* cElement = static_cast<Element*>(cElementList->item(i));

					if (cElement)
					{
						Element* cnameElement = cElement->getChildElement(PREFERENCE_NAME);
						Element* srcElement = cElement->getChildElement(PREFERENCE_SOURCE);

						if (cnameElement && srcElement)
						{
							Channel channel;

							channel.m_Name = cnameElement->firstChild()->getNodeValue();
							channel.m_Source = srcElement->firstChild()->getNodeValue();

							if (channel.m_Source.find("http://") == string::npos &&
							        channel.m_Source.find("rtsp://") == string::npos)
							{
								channel.m_Source = "sdp:/" + channel.m_Source;
							}

							Element* archElement = cElement->getChildElement(PREFERENCE_ARCHIVE);
							if (archElement)
							{
								channel.m_Archive = "arch:/" + archElement->firstChild()->getNodeValue();
							}

							Element* castElement = cElement->getChildElement(PREFERENCE_CASTING_URI);

							if (castElement)
							{
								channel.m_CastingURI = castElement->firstChild()->getNodeValue();

								Element* servElement = cElement->getChildElement(PREFERENCE_SERVING_ADDRESS);
								if (servElement)
								{
									channel.m_ServingAddress = servElement->firstChild()->getNodeValue();
								}
							}

							m_ChannelList.push_back(channel);
						}
					}
				}
			}

			Element* dlElement = cdElement->getChildElement(PREFERENCE_DIRECTORY_LIST);

			if (dlElement)
			{
				AutoPtr<NodeList> dElementList = dlElement->getElementsByTagName(PREFERENCE_DIRECTORY);
				unsigned long length = dElementList->length();

				for (unsigned long i = 0; i < length; i++)
				{
					Element* dElement = static_cast<Element*>(dElementList->item(i));

					if (dElement)
					{
						Element* protElement = dElement->getChildElement(PREFERENCE_PROTOCOL);
						Element* dnameElement = dElement->getChildElement(PREFERENCE_NAME);
						Element* pathElement = dElement->getChildElement(PREFERENCE_PATH);

						if (protElement && dnameElement && pathElement)
						{
							Directory dir;

							dir.m_Name = dnameElement->firstChild()->getNodeValue();
							dir.m_Path = pathElement->firstChild()->getNodeValue();
							
							if (protElement->firstChild()->getNodeValue().compare("rtsp") == 0)
							{
								dir.m_Protocol = RTSP;
							}
							else
							{
								dir.m_Protocol = HTTP;
							}

							m_DirectoryList.push_back(dir);
						}
					}
				}
			}

			return true;
		}
		catch (Exception& exc)
		{
			std::cerr << exc.displayText() << std::endl;
		}
	}

	return false;
}
Esempio n. 8
0
/**
 * Loads grouping from the XML file specified.
 *
 * @param filename :: XML filename to load grouping information from
 * @param        g :: Struct to store grouping information to
 */
void loadGroupingFromXML(const std::string& filename, Grouping& g)
{
  // Set up the DOM parser and parse xml file
  DOMParser pParser;
  Poco::AutoPtr<Document> pDoc;
  try
  {
    pDoc = pParser.parse(filename);
  }
  catch(...)
  {
    throw Mantid::Kernel::Exception::FileError("Unable to parse File" , filename);
  }

  // Get pointer to root element
  Element* pRootElem = pDoc->documentElement();
  if (!pRootElem->hasChildNodes())
    throw Mantid::Kernel::Exception::FileError("No root element in XML grouping file" , filename);

  // Parse information for groups
  Poco::AutoPtr<NodeList> groups = pRootElem->getElementsByTagName("group");
  if (groups->length() == 0)
    throw Mantid::Kernel::Exception::FileError("No groups specified in XML grouping file" , filename);

  // Resize vectors
  g.groupNames.resize(groups->length());
  g.groups.resize(groups->length());

  for (size_t ig = 0; ig < groups->length(); ig++)
  {
    Element* pGroupElem = static_cast<Element*>(groups->item(static_cast<long>(ig)));

    if (!pGroupElem->hasAttribute("name"))
      throw Mantid::Kernel::Exception::FileError("Group element without name" , filename);

    g.groupNames[ig] = pGroupElem->getAttribute("name");

    Element* idlistElement = pGroupElem->getChildElement("ids");
    if (!idlistElement)
      throw Mantid::Kernel::Exception::FileError("Group element without <ids>" , filename);

    g.groups[ig] = idlistElement->getAttribute("val");
  }
  

  // Parse information for pairs
  Poco::AutoPtr<NodeList> pairs = pRootElem->getElementsByTagName("pair");

  // Resize vectors
  g.pairNames.resize(pairs->length());
  g.pairs.resize(pairs->length());
  g.pairAlphas.resize(pairs->length());

  for (size_t ip = 0; ip < pairs->length(); ip++)
  {
    Element* pPairElem = static_cast<Element*>(pairs->item(static_cast<long>(ip)));

    if ( !pPairElem->hasAttribute("name") )
      throw Mantid::Kernel::Exception::FileError("Pair element without name" , filename);

    g.pairNames[ip] = pPairElem->getAttribute("name");

    size_t fwdGroupId, bwdGroupId; // Ids of forward/backward groups

    // Try to get id of the first group
    if (Element* fwdElement = pPairElem->getChildElement("forward-group"))
    {
      if(!fwdElement->hasAttribute("val"))
        throw Mantid::Kernel::Exception::FileError("Pair forward-group without <val>" , filename);
      
      // Find the group with the given name
      auto it = std::find(g.groupNames.begin(), g.groupNames.end(), fwdElement->getAttribute("val"));

      if(it == g.groupNames.end())
        throw Mantid::Kernel::Exception::FileError("Pair forward-group name not recognized" , filename);

      // Get index of the iterator
      fwdGroupId = it - g.groupNames.begin();
    }
    else
    {
      throw Mantid::Kernel::Exception::FileError("Pair element without <forward-group>" , filename);
    }

    // Try to get id of the second group
    if(Element* bwdElement = pPairElem->getChildElement("backward-group"))
    {
      if(!bwdElement->hasAttribute("val"))
        throw Mantid::Kernel::Exception::FileError("Pair backward-group without <val>" , filename);

      // Find the group with the given name
      auto it = std::find(g.groupNames.begin(), g.groupNames.end(), bwdElement->getAttribute("val"));

      if(it == g.groupNames.end())
        throw Mantid::Kernel::Exception::FileError("Pair backward-group name not recognized" , filename);

      // Get index of the iterator
      bwdGroupId = it - g.groupNames.begin();
    }
    else
    {
      throw Mantid::Kernel::Exception::FileError("Pair element without <backward-group>" , filename);
    }

    g.pairs[ip] = std::make_pair(fwdGroupId, bwdGroupId);

    // Try to get alpha element
    if (Element* aElement = pPairElem->getChildElement("alpha"))
    {
      if (!aElement->hasAttribute("val") )
        throw Mantid::Kernel::Exception::FileError("Pair alpha element with no <val>" , filename);
     
      try // ... to convert value to double
      {
        g.pairAlphas[ip] = boost::lexical_cast<double>(aElement->getAttribute("val"));
      }
      catch(boost::bad_lexical_cast&)
      {
        throw Mantid::Kernel::Exception::FileError("Pair alpha value is not a number" , filename);
      }   
    }
    // If alpha element not there, default it to 1.0
    else 
    {
      g.pairAlphas[ip] = 1.0;
    }

  }

  // Try to get description
  if (pRootElem->hasAttribute("description"))
  {
    g.description = pRootElem->getAttribute("description");
  }

  // Try to get default group/pair name
  if(Element* defaultElement = pRootElem->getChildElement("default"))
  {
    if(!defaultElement->hasAttribute("name"))
      throw Mantid::Kernel::Exception::FileError("Default element with no <name>" , filename);
    
    g.defaultName = defaultElement->getAttribute("name");
  }
}
Esempio n. 9
0
/**
 * load XML grouping file. It is assumed that tables and combo box cleared before this method is called
 */
void loadGroupingXMLtoTable(Ui::MuonAnalysis& m_uiForm, const std::string& filename)
{
  // Set up the DOM parser and parse xml file
  DOMParser pParser;
  Document* pDoc;
  try
  {
    pDoc = pParser.parse(filename);
  }
  catch(...)
  {
    throw Mantid::Kernel::Exception::FileError("Unable to parse File:" , filename);
  }
  // Get pointer to root element
  Element* pRootElem = pDoc->documentElement();
  if ( !pRootElem->hasChildNodes() )
  {
    throw Mantid::Kernel::Exception::FileError("No root element in XML grouping file:" , filename);
  }  

  NodeList* pNL_group = pRootElem->getElementsByTagName("group");
  if ( pNL_group->length() == 0 )
  {
    throw Mantid::Kernel::Exception::FileError("XML group file contains no group elements:" , filename);
  }


  // add content to group table

  QStringList allGroupNames;  // used to populate combo boxes 
  int numberGroups = static_cast<int>(pNL_group->length());
  for (int iGroup = 0; iGroup < numberGroups; iGroup++)
  {
    Element* pGroupElem = static_cast<Element*>(pNL_group->item(iGroup));

    if ( !pGroupElem->hasAttribute("name") )
      throw Mantid::Kernel::Exception::FileError("Group element without name" , filename);
    std::string gName = pGroupElem->getAttribute("name");


    Element* idlistElement = pGroupElem->getChildElement("ids");
    if (idlistElement)
    {
      std::string ids = idlistElement->getAttribute("val");

      // add info to table
      m_uiForm.groupTable->setItem(iGroup, 0, new QTableWidgetItem(gName.c_str()) );
      m_uiForm.groupTable->setItem(iGroup,1, new QTableWidgetItem(ids.c_str()) );
      allGroupNames.push_back( m_uiForm.groupTable->item(static_cast<int>(iGroup),0)->text() );
    }
    else
    {
      throw Mantid::Kernel::Exception::FileError("XML group file contains no <ids> elements:" , filename);
    }   
  }
  pNL_group->release();
  

  // populate pair table combo boxes

  int rowNum = m_uiForm.pairTable->rowCount();
  for (int i = 0; i < rowNum; i++)
  {
    QComboBox* qw1 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,1));
    QComboBox* qw2 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(i,2));

    for (int ii = 0; ii < allGroupNames.size(); ii++)
    {

      qw1->addItem( allGroupNames[ii] );
      qw2->addItem( allGroupNames[ii] );
    }
    
    if ( qw2->count() > 1 )
      qw2->setCurrentIndex(1);
  }




  // add content to pair table

  QStringList allPairNames;  
  NodeList* pNL_pair = pRootElem->getElementsByTagName("pair");
  int nPairs = static_cast<int>(pNL_pair->length());
  if ( pNL_pair->length() > 0 )
  {
    for (int iPair = 0; iPair < nPairs; iPair++)
    {
      Element* pGroupElem = static_cast<Element*>(pNL_pair->item(iPair));

      if ( !pGroupElem->hasAttribute("name") )
        throw Mantid::Kernel::Exception::FileError("pair element without name" , filename);
      std::string gName = pGroupElem->getAttribute("name");
      m_uiForm.pairTable->setItem(iPair,0, new QTableWidgetItem(gName.c_str()) );
      allPairNames.push_back(gName.c_str());

      Element* fwElement = pGroupElem->getChildElement("forward-group");
      if (fwElement)
      {
        std::string ids = fwElement->getAttribute("val");
        QComboBox* qw1 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(iPair,1));
        int comboIndex = qw1->findText(ids.c_str());
        if ( comboIndex < 0 )
          throw Mantid::Kernel::Exception::FileError("XML pair group contains forward-group with unrecognised group name" , filename);
        qw1->setCurrentIndex(comboIndex);
      }
      else
      {
        throw Mantid::Kernel::Exception::FileError("XML pair group contains no <forward-group> elements:" , filename);
      }   

      Element* bwElement = pGroupElem->getChildElement("backward-group");
      if (bwElement)
      {
        std::string ids = bwElement->getAttribute("val");
        QComboBox* qw2 = static_cast<QComboBox*>(m_uiForm.pairTable->cellWidget(iPair,2));
        int comboIndex = qw2->findText(ids.c_str());
        if ( comboIndex < 0 )
          throw Mantid::Kernel::Exception::FileError("XML pair group contains backward-group with unrecognised group name" , filename);
        qw2->setCurrentIndex(comboIndex);
      }
      else
      {
        throw Mantid::Kernel::Exception::FileError("XML pair group contains no <backward-group> elements:" , filename);
      }

      Element* element = pGroupElem->getChildElement("alpha");
      if (element)
      {
        if ( element->hasAttribute("val") )
        {
          m_uiForm.pairTable->setItem(iPair,3, new QTableWidgetItem(element->getAttribute("val").c_str()));
        }
        else
          throw Mantid::Kernel::Exception::FileError("XML pair group contains an <alpha> element with no 'val' attribute:" , filename);
      }
      // if alpha element not there for now just default it to 1.0
      else 
      {
        m_uiForm.pairTable->setItem(iPair,3, new QTableWidgetItem(1.0));
      }

    }
  }
  pNL_pair->release(); 


  // populate front combobox

  //m_uiForm.frontGroupGroupPairComboBox->addItems(allGroupNames);
  //m_uiForm.frontGroupGroupPairComboBox->addItems(allPairNames);


  if ( pRootElem->hasAttribute("description") )
  {
    m_uiForm.groupDescription->setText(pRootElem->getAttribute("description").c_str());
  }
  else
  {
    m_uiForm.groupDescription->setText("");
  }

  // reads default choice 

  Element* element = pRootElem->getChildElement("default");
  if (element)
  {
    if ( element->hasAttribute("name") )
    {
      setGroupGroupPair(m_uiForm, element->getAttribute("name"));
    }
  }


  pDoc->release();
}
Esempio n. 10
0
    /// Overwrites Algorithm exec method
    void LoadSpice2D::exec()
    {
      std::string fileName = getPropertyValue("Filename");

      const double wavelength_input = getProperty("Wavelength");
      const double wavelength_spread_input = getProperty("WavelengthSpread");

      // Set up the DOM parser and parse xml file
      DOMParser pParser;
      Document* pDoc;
      try
      {
        pDoc = pParser.parse(fileName);
      } catch (...)
      {
        throw Kernel::Exception::FileError("Unable to parse File:", fileName);
      }
      // Get pointer to root element
      Element* pRootElem = pDoc->documentElement();
      if (!pRootElem->hasChildNodes())
      {
        throw Kernel::Exception::NotFoundError("No root element in Spice XML file", fileName);
      }

      // Read in start time
      const std::string start_time = pRootElem->getAttribute("start_time");

      Element* sasEntryElem = pRootElem->getChildElement("Header");
      throwException(sasEntryElem, "Header", fileName);

      // Read in scan title
      Element* element = sasEntryElem->getChildElement("Scan_Title");
      throwException(element, "Scan_Title", fileName);
      std::string wsTitle = element->innerText();

      // Read in instrument name
      element = sasEntryElem->getChildElement("Instrument");
      throwException(element, "Instrument", fileName);
      std::string instrument = element->innerText();

      // Read sample thickness
      double sample_thickness = 0;
      from_element<double>(sample_thickness, sasEntryElem, "Sample_Thickness", fileName);

      double source_apert = 0.0;
      from_element<double>(source_apert, sasEntryElem, "source_aperture_size", fileName);

      double sample_apert = 0.0;
      from_element<double>(sample_apert, sasEntryElem, "sample_aperture_size", fileName);

      double source_distance = 0.0;
      from_element<double>(source_distance, sasEntryElem, "source_distance", fileName);

      // Read in wavelength and wavelength spread
      double wavelength = 0;
      double dwavelength = 0;
      if ( isEmpty(wavelength_input) ) {
        from_element<double>(wavelength, sasEntryElem, "wavelength", fileName);
        from_element<double>(dwavelength, sasEntryElem, "wavelength_spread", fileName);
      }
      else
      {
        wavelength = wavelength_input;
        dwavelength = wavelength_spread_input;
      }

      // Read in positions
      sasEntryElem = pRootElem->getChildElement("Motor_Positions");
      throwException(sasEntryElem, "Motor_Positions", fileName);

      // Read in the number of guides
      int nguides = 0;
      from_element<int>(nguides, sasEntryElem, "nguides", fileName);

      // Read in sample-detector distance in mm
      double distance = 0;
      from_element<double>(distance, sasEntryElem, "sample_det_dist", fileName);
      distance *= 1000.0;

      // Read in beam trap positions
      double highest_trap = 0;
      double trap_pos = 0;

      from_element<double>(trap_pos, sasEntryElem, "trap_y_25mm", fileName);
      double beam_trap_diam = 25.4;

      from_element<double>(highest_trap, sasEntryElem, "trap_y_101mm", fileName);
      if (trap_pos>highest_trap)
      {
        highest_trap = trap_pos;
        beam_trap_diam = 101.6;
      }

      from_element<double>(trap_pos, sasEntryElem, "trap_y_50mm", fileName);
      if (trap_pos>highest_trap)
      {
        highest_trap = trap_pos;
        beam_trap_diam = 50.8;
      }

      from_element<double>(trap_pos, sasEntryElem, "trap_y_76mm", fileName);
      if (trap_pos>highest_trap)
      {
        highest_trap = trap_pos;
        beam_trap_diam = 76.2;
      }

      // Read in counters
      sasEntryElem = pRootElem->getChildElement("Counters");
      throwException(sasEntryElem, "Counters", fileName);

      double countingTime = 0;
      from_element<double>(countingTime, sasEntryElem, "time", fileName);
      double monitorCounts = 0;
      from_element<double>(monitorCounts, sasEntryElem, "monitor", fileName);

      // Read in the data image
      Element* sasDataElem = pRootElem->getChildElement("Data");
      throwException(sasDataElem, "Data", fileName);

      // Read in the data buffer
      element = sasDataElem->getChildElement("Detector");
      throwException(element, "Detector", fileName);
      std::string data_str = element->innerText();

      // Read in the detector dimensions from the Detector tag
      int numberXPixels = 0;
      int numberYPixels = 0;
      std::string data_type = element->getAttribute("type");
      boost::regex b_re_sig("INT\\d+\\[(\\d+),(\\d+)\\]");
      if (boost::regex_match(data_type, b_re_sig))
      {
        boost::match_results<std::string::const_iterator> match;
        boost::regex_search(data_type, match, b_re_sig);
        // match[0] is the full string
        Kernel::Strings::convert(match[1], numberXPixels);
        Kernel::Strings::convert(match[2], numberYPixels);
      }
      if (numberXPixels==0 || numberYPixels==0)
        g_log.notice() << "Could not read in the number of pixels!" << std::endl;

      // We no longer read from the meta data because that data is wrong
      //from_element<int>(numberXPixels, sasEntryElem, "Number_of_X_Pixels", fileName);
      //from_element<int>(numberYPixels, sasEntryElem, "Number_of_Y_Pixels", fileName);

      // Store sample-detector distance
      declareProperty("SampleDetectorDistance", distance, Kernel::Direction::Output);

      // Create the output workspace

      // Number of bins: we use a single dummy TOF bin
      int nBins = 1;
      // Number of detectors: should be pulled from the geometry description. Use detector pixels for now.
      // The number of spectram also includes the monitor and the timer.
      int numSpectra = numberXPixels*numberYPixels + LoadSpice2D::nMonitors;

      DataObjects::Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(
          API::WorkspaceFactory::Instance().create("Workspace2D", numSpectra, nBins+1, nBins));
      ws->setTitle(wsTitle);
      ws->getAxis(0)->unit() = Kernel::UnitFactory::Instance().create("Wavelength");
      ws->setYUnit("");
      API::Workspace_sptr workspace = boost::static_pointer_cast<API::Workspace>(ws);
      setProperty("OutputWorkspace", workspace);

      // Parse out each pixel. Pixels can be separated by white space, a tab, or an end-of-line character
      Poco::StringTokenizer pixels(data_str, " \n\t", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
      Poco::StringTokenizer::Iterator pixel = pixels.begin();

      // Check that we don't keep within the size of the workspace
      size_t pixelcount = pixels.count();
      if( pixelcount != static_cast<size_t>(numberXPixels*numberYPixels) )
      {
        throw Kernel::Exception::FileError("Inconsistent data set: "
            "There were more data pixels found than declared in the Spice XML meta-data.", fileName);
      }
      if( numSpectra == 0 )
      {
        throw Kernel::Exception::FileError("Empty data set: the data file has no pixel data.", fileName);
      }

      // Go through all detectors/channels
      int ipixel = 0;

      // Store monitor count
      store_value(ws, ipixel++, monitorCounts, monitorCounts>0 ? sqrt(monitorCounts) : 0.0,
          wavelength, dwavelength);

      // Store counting time
      store_value(ws, ipixel++, countingTime, 0.0, wavelength, dwavelength);

      // Store detector pixels
      while (pixel != pixels.end())
      {
        //int ix = ipixel%npixelsx;
        //int iy = (int)ipixel/npixelsx;

        // Get the count value and assign it to the right bin
        double count = 0.0;
        from_string<double>(count, *pixel, std::dec);

        // Data uncertainties, computed according to the HFIR/IGOR reduction code
        // The following is what I would suggest instead...
        // error = count > 0 ? sqrt((double)count) : 0.0;
        double error = sqrt( 0.5 + fabs( count - 0.5 ));

        store_value(ws, ipixel, count, error, wavelength, dwavelength);

        // Set the spectrum number
        ws->getAxis(1)->setValue(ipixel, ipixel);

        ++pixel;
        ipixel++;
      }

      // run load instrument
      runLoadInstrument(instrument, ws);
      runLoadMappingTable(ws, numberXPixels, numberYPixels);

      // Set the run properties
      ws->mutableRun().addProperty("sample-detector-distance", distance, "mm", true);
      ws->mutableRun().addProperty("beam-trap-diameter", beam_trap_diam, "mm", true);
      ws->mutableRun().addProperty("number-of-guides", nguides, true);
      ws->mutableRun().addProperty("source-sample-distance", source_distance, "mm", true);
      ws->mutableRun().addProperty("source-aperture-diameter", source_apert, "mm", true);
      ws->mutableRun().addProperty("sample-aperture-diameter", sample_apert, "mm", true);
      ws->mutableRun().addProperty("sample-thickness", sample_thickness, "cm", true);
      ws->mutableRun().addProperty("wavelength", wavelength, "Angstrom", true);
      ws->mutableRun().addProperty("wavelength-spread", dwavelength, "Angstrom", true);
      ws->mutableRun().addProperty("timer", countingTime, "sec", true);
      ws->mutableRun().addProperty("monitor", monitorCounts, "", true);
      ws->mutableRun().addProperty("start_time", start_time, "", true);
      ws->mutableRun().addProperty("run_start", start_time, "", true);

      // Move the detector to the right position
      API::IAlgorithm_sptr mover = createChildAlgorithm("MoveInstrumentComponent");

      // Finding the name of the detector object.
      std::string detID = ws->getInstrument()->getStringParameter("detector-name")[0];

      g_log.information("Moving "+detID);
      try
      {
        mover->setProperty<API::MatrixWorkspace_sptr> ("Workspace", ws);
        mover->setProperty("ComponentName", detID);
        mover->setProperty("Z", distance/1000.0);
        mover->execute();
      } catch (std::invalid_argument& e)
      {
        g_log.error("Invalid argument to MoveInstrumentComponent Child Algorithm");
        g_log.error(e.what());
      } catch (std::runtime_error& e)
      {
        g_log.error("Unable to successfully run MoveInstrumentComponent Child Algorithm");
        g_log.error(e.what());
      }

      // Release the XML document memory
      pDoc->release();
    }
Esempio n. 11
0
//**********************************************************************************************************************
bool cSettings::LoadFromFile (const string& fileName)
{
    ifstream settingsFile(fileName.c_str());

    msAlertCode = acOk;

    if (!settingsFile.is_open())
    {
        cout << "Cannot open \"" << fileName << "\" for reading." << endl;
        return false;
    }

    InputSource settingsSrc(settingsFile);

    // attempt to parse the settings file
    try
    {
        mSettingsDoc = mSettingsParser.parse(&settingsSrc);

        mSettingsRoot = mSettingsDoc->documentElement();

        // check that the settings root element's name is "settings"
        if (mSettingsRoot->nodeName() != "settings")
        {
            cout << fileName << " must contain a <settings> element as its root element." << endl;
            return false;
        }

        Element* el = mSettingsRoot->getChildElement("logfile");
        if ((!el) || (!el->hasAttribute("location")))
        {
            cout << "WARNING: No log file location specified in settings file. Using \"./qrap.log\"." << endl;
            msLogFileName = "./qrap.log";
        } else
        {
            msLogFileName = el->getAttribute("location");
        }

        QRAP_INFO("-----------Begin debug logging-----------");
        // check the database element
        el = mSettingsRoot->getChildElement("database");
        if ((!el) || (!el->hasAttribute("host")) || (!el->hasAttribute("name")))
        {
            QRAP_FATAL_CODE(fileName+" must contain a <database> element with connection parameters.", acInternalError);
            return false;
        }

#ifndef QRAP_SERVER_EDITION
        // check that the synchronisation server details are in
        el = mSettingsRoot->getChildElement("syncserver");
        if ((!el) || (!el->hasAttribute("host")) || (!el->hasAttribute("port")))
        {
            QRAP_FATAL_CODE(fileName+" must contain a <syncserver> element with connection parameters.", acInternalError);
            return false;
        }
#endif

        // check the structure element
        el = mSettingsRoot->getChildElement("structure");
        if ((!el) || (!el->hasAttribute("location")))
        {
            QRAP_FATAL_CODE(fileName+" must contain a reference to a structure XML file.", acInternalError);
            return false;
        }

        // open up the structure file
        string   structFileName = el->getAttribute("location");
        ifstream structFile(structFileName.c_str());

        // check that the file's open
        if (!structFile.is_open())
        {
            QRAP_FATAL_CODE("Cannot open \""+structFileName+"\" for reading.", acFileOpenRead);
            return false;
        }

        // create an input source
        InputSource       structSrc(structFile);
        DOMParser         structParser;
        AutoPtr<Document> structDoc = structParser.parse(&structSrc);
        Element*          structRoot = structDoc->documentElement();

        // check that the structure file contains a <structure> element
        if ((!structRoot) || (structRoot->nodeName() != "structure"))
        {
            QRAP_FATAL_CODE(structFileName+" must contain a <structure> root element.", acParse);
            return false;
        }

        // get the "table" children
        ElementsByTagNameList* tables = dynamic_cast<ElementsByTagNameList*>(structRoot->getElementsByTagName("table"));
        ElementsByTagNameList* fields, *views;
        int                 i, tableCount, j, k, fieldCount, viewCount;
        unsigned	refPos;
        Element*            curTable, *curField, *curView;
        string              tableName, fieldName, temp, viewName, viewAs;

        tableCount = tables->length();
        if (!tableCount)
        {
            QRAP_FATAL_CODE(structFileName+" must contain a database structure with at least one <table> tag.", acParse);
            return false;
        }

        // run through the tables
        for (i=0; i<tableCount; i++)
        {
            // get the current table
            curTable = dynamic_cast<Element*>(tables->item(i));
            // skip the table if it doesn't have a name
            if (!curTable->hasAttribute("name"))
            {
                char *text = new char[33];
                gcvt(i,8,text);
                string error = "Table found in structure file without name. Entry ";
                error+= text;
                QRAP_WARN(text);
                delete [] text;
                continue;
            }

            // get the table's name
            tableName = curTable->getAttribute("name");

            // get this table's views
            views = dynamic_cast<ElementsByTagNameList*>(curTable->getElementsByTagName("view"));

            // if there are any views
            if (views && (views->length() > 0))
            {
                // run through the views
                viewCount = views->length();
                for (j=0; j<viewCount; j++)
                {
                    curView = dynamic_cast<Element*>(views->item(j));
                    // check that the view has a name
                    if (!curView->hasAttribute("name"))
                    {
                        QRAP_WARN("View found in table \""+tableName+"\" with no name. Skipping.");
                        continue;
                    }
                    viewName = curView->getAttribute("name");
                    // check that the view has an "as" clause
                    if (!curView->hasAttribute("as"))
                    {
                        QRAP_WARN("View \""+tableName+"."+viewName+"\" has no \"as\" clause. Skipping.");
                        continue;
                    }
                    // get the "as" clause
                    mStructure[tableName].mViews[viewName].mAs = curView->getAttribute("as");
                    // get any extra field labels from the view
                    fields = dynamic_cast<ElementsByTagNameList*>(curView->getElementsByTagName("field"));
                    if (fields && (fields->length() > 0))
                    {
                        // save the extra field labels
                        fieldCount = fields->length();
                        for (k=0; k<fieldCount; k++)
                        {
                            curField = dynamic_cast<Element*>(fields->item(k));
                            // check that the field has both "name" and "label" attributes
                            if (!curField->hasAttribute("name") || !curField->hasAttribute("label"))
                            {
                                QRAP_WARN("Fields in a view must have both a name and label. Skipping entry.");
                                continue;
                            }
                            // add the field to the view
                            fieldName = curField->getAttribute("name");
                            mStructure[tableName].mViews[viewName].mFieldLabels[fieldName] = curField->getAttribute("label");
                        }
                    }
                }
            }

            // get the fields
            fields = dynamic_cast<ElementsByTagNameList*>(curTable->getElementsByTagName("field"));

            if ((!fields) || (fields->length() == 0))
            {
                QRAP_WARN("Empty table \""+tableName+"\" found in structure file.");
                continue;
            }
            // get the number of fields in this table
            fieldCount = fields->length();
            // set up this table
            mStructure[tableName].mLabel = curTable->getAttribute("label");
            mStructure[tableName].mDescription = curTable->getAttribute("description");
            mStructure[tableName].mFooter = curTable->getAttribute("footer");
            // if the table is explicitly invisible, set it to invisible
            mStructure[tableName].mVisible = (curTable->getAttribute("visible") == "false") ? false : true;
            mStructure[tableName].mCreateOrder = i;
            // if the table is explicitly set as full download
            mStructure[tableName].mFullDownload = (curTable->getAttribute("fulldownload") == "true") ? true : false;
            // if the table is explicitly set as having a custom sequence
            mStructure[tableName].mCustomSequence = (curTable->getAttribute("customsequence") == "true") ? true : false;

            // run through the fields
            for (j=0; j<fieldCount; j++)
            {
                curField = dynamic_cast<Element*>(fields->item(j));

                if (!curField->hasAttribute("name"))
                {
                    QRAP_WARN("Field found in table \""+tableName+"\" with no name. Skipping it.");
                    continue;
                }

                fieldName = curField->getAttribute("name");

                if (!curField->hasAttribute("type"))
                {
                    QRAP_WARN("Field \""+fieldName+"\" in table \""+tableName+"\" has no type. Skipping.");
                    continue;
                }

                // set up the field
                mStructure[tableName].mFields[fieldName].mType = curField->getAttribute("type");
                mStructure[tableName].mFields[fieldName].mLabel = curField->getAttribute("label");
                mStructure[tableName].mFields[fieldName].mDescription = curField->getAttribute("description");
                // set the visibility flag if it is explicitly set
                mStructure[tableName].mFields[fieldName].mVisible = (curField->getAttribute("visible") == "false") ? false : true;
                // set the read-only flag if it is explicitly set
                mStructure[tableName].mFields[fieldName].mReadOnly = (curField->getAttribute("readonly") == "true") ? true : false;
                mStructure[tableName].mFields[fieldName].mUi = curField->getAttribute("ui");
                mStructure[tableName].mFields[fieldName].mOrder = j;

                // check if this field is a foreign key reference...
                temp = mStructure[tableName].mFields[fieldName].mType;
                refPos = temp.find("references");
                // if this key is a reference to a foreign key
                if (refPos < temp.length())
                {
                    mStructure[tableName].mFields[fieldName].mIsForeign = true;
                    // find the first non-whitespace character after the "references" keyword (length 10 characters)
                    refPos = FindNonWhitespace(temp, refPos+10);
                    mStructure[tableName].mFields[fieldName].mForeignTable = ExtractKeyword(temp, refPos);
                    // if there is no foreign table
                    if (mStructure[tableName].mFields[fieldName].mForeignTable.length() == 0)
                    {
                        QRAP_FATAL_CODE("Invalid data type specified in \""+tableName+"."+fieldName+"\". Reference must be to a table's primary key.", acParse);
                        return false;
                    }
                }

                // is this field a file link?
                mStructure[tableName].mFields[fieldName].mIsFileLink = (curField->getAttribute("filelink") == "true") ? true : false;
                // is this field specific to the server?
                mStructure[tableName].mFields[fieldName].mServerOnly = (curField->getAttribute("serveronly") == "true") ? true : false;
                // is this field specific to the client?
                mStructure[tableName].mFields[fieldName].mClientOnly = (curField->getAttribute("clientonly") == "true") ? true : false;
                // is this field a PostGIS field?
                mStructure[tableName].mFields[fieldName].mPostGis = (curField->getAttribute("postgis") == "true") ? true : false;
                // does this field contain a unit type? default: utNone
                temp = StrToLower(curField->getAttribute("unittype"));
                if (temp == "power")
                    mStructure[tableName].mFields[fieldName].mUnitType = utPower;
                else if (temp == "sensitivity")
                    mStructure[tableName].mFields[fieldName].mUnitType = utSensitivity;
                else if (temp == "eirp")
                    mStructure[tableName].mFields[fieldName].mUnitType = utEirp;
                else if (temp == "height")
                    mStructure[tableName].mFields[fieldName].mUnitType = utHeight;
                else if (temp == "dbell")
                    mStructure[tableName].mFields[fieldName].mUnitType = utLossGain;
                else if (temp == "dbell")
                    mStructure[tableName].mFields[fieldName].mUnitType = utLossGain;
                else if (temp == "megahertz")
                    mStructure[tableName].mFields[fieldName].mUnitType = utMegaHertz;
                else if (temp == "kilohertz")
                    mStructure[tableName].mFields[fieldName].mUnitType = utkiloHertz;
                else if (temp == "degrees")
                    mStructure[tableName].mFields[fieldName].mUnitType = utAngle;
                else if (temp == "distance")
                    mStructure[tableName].mFields[fieldName].mUnitType = utDistance;
            }
        }

    } catch (Exception& e)
    {
        QRAP_FATAL_CODE("XML error: "+e.displayText(), acFileOpenRead);
    }
    if (msAlertCode != acOk)
        return false;

    return true;
}
Esempio n. 12
0
template< typename TCtx, typename Tnode> unsigned
sample_dom( char* fname) {

  TCtx* ctxp;

  printf( "XML C++ DOM sample\n");

  printf( "Initializing context\n");

  try
  {
    ctxp = new TCtx();
  }
  catch (XmlException& e)
  {
    unsigned ecode = e.getCode();

    printf( "Failed to initialize XML context, error %u\n", ecode);
    return ecode;
  }

  printf("Initializing Tools Factory\n");

  Factory< TCtx, Tnode>* fp;

  try 
  {
    fp = new Factory< TCtx, Tnode>( ctxp);
  }
  catch (FactoryException& fe)
  {
    unsigned ecode = fe.getCode();

    printf( "Failed to create factory, error %u\n", ecode);
    return ecode;
  }

  printf("Creating DOM parser\n");

  DOMParser< TCtx, Tnode>* parserp;

  try 
  {
    parserp = fp->createDOMParser( DOMParCXml, NULL);
  }
  catch (FactoryException& fe1)
  {
    unsigned ecode = fe1.getCode();

    printf( "Failed to create parser, error %u\n", ecode);
    return ecode;
  }

  printf( "Create file source\n");

  FileSource* isrcp = new FileSource( (oratext*)fname);

  printf("Parsing '%s' ...\n", fname);

  try
  {
    DocumentRef< Tnode>* docrefp = parserp->parse( isrcp);
    if (docrefp == NULL)
    {
      printf( "NULL document\n");
      return 1;
    }
    Tnode* np = docrefp->getDocumentElement();
    if (np == NULL)
    {
      printf( "Empty document\n");
      return 1;
    }
    ElementRef< Tnode> elref( (*docrefp), np);

    printf("Dump the DOM tree\n");

    dumpTree< Tnode>( elref);

    printf("Delete the DOM tree\n");

    docrefp->markToDelete();

    delete docrefp;

    printf("Finished\n");

  }
  catch (ParserException& pe)
  {
    unsigned ecode = pe.getCode();

    printf( "Failed to parse the document, error %u\n", ecode);
    return ecode;
  }
  return 0;
}
Esempio n. 13
0
int main(int argc, char **argv)
{
  bool verbose = false;
#if 0
  DOMParser::ValSchemes    gValScheme             = DOMParser::Val_Auto;
  bool                     gDoNamespaces          = true;
  bool                     gDoSchema              = true;
  bool                     gSchemaFullChecking    = false;
  bool                     gDoCreate              = false;
#endif

  MFileOperations f;
  char path[1024];

  f.expandPath(path, "MESA_TARGET", "runtime");
  ::strcat(path, "/IHE-syslog-audit-message-4.xsd");
  char* schemaDef = path;

  int detailLevel = 1;
  MString tmp;

  while (--argc > 0 && (*++argv)[0] == '-') {
    switch (*(argv[0] + 1)) {
    case 'l':
      argc--; argv++;
      if (argc < 1)
	usage();
      tmp = *argv;
      detailLevel = tmp.intData();
      break;
    case 's':
      argc--; argv++;
      if (argc < 1)
	usage();
      schemaDef = *argv;
      break;
    case 'v':
      verbose = true;
      break;
    default:
      break;
    }
  }

  if (argc < 1)
    usage();

  // Initialize the XML4C2 system
  try {
    XMLPlatformUtils::Initialize();
  }
  catch (const XMLException& e) {
    cout << "Unable to initialize Xerces-c software"
	 << DOMString(e.getMessage()) << endl;
    return 1;
  }


  DOMParser *parser = new DOMParser;
  parser->setValidationScheme(DOMParser::Val_Auto);
  parser->setDoNamespaces(true);
  parser->setDoSchema(true);
  parser->setValidationSchemaFullChecking(true);
  if (schemaDef != "") {
    parser->setExternalNoNamespaceSchemaLocation(schemaDef);
  }

  DOMTreeErrorReporter *errReporter = new DOMTreeErrorReporter();
  parser->setErrorHandler(errReporter);
  parser->setCreateEntityReferenceNodes(false);
  parser->setToCreateXMLDeclTypeNode(true);

  bool errorFlag = false;

  try {
    parser->parse(*argv);
    int count = parser->getErrorCount();
    if (count > 0) {
      errorFlag = true;
      return 1;
    }
  }
  catch (const XMLException& e) {
    cout << "Parsing error: " << DOMString(e.getMessage()) << endl;
    return 1;
  }
  catch (const DOM_DOMException& e) {
   cout << "DOM Error: " << e.code << endl;
   return 1;
  }

  catch (...) {
    cout << "Unspecified error" << endl;
    return 1;
  }

  DOM_Document doc = parser->getDocument();

  unsigned int elementCount = doc.getElementsByTagName("*").getLength();

  cout << "element count: " << elementCount << endl;

  return 0;
}
Esempio n. 14
-1
int main (int argC,  char *argV[]) 
{

    MemoryMonitor *staticMemMonitor = new MemoryMonitor();

    // Initialize the XML4C system
    try
    {
        XMLPlatformUtils::Initialize(XMLUni::fgXercescDefaultLocale, 0, 0, staticMemMonitor);
    }
    catch (const XMLException& toCatch)
    {
         char *msg = XMLString::transcode(toCatch.getMessage());
         XERCES_STD_QUALIFIER cerr << "Error during initialization! :\n"
              << msg << XERCES_STD_QUALIFIER endl;
         XMLString::release(&msg);
         return 1;
    }

    // Check command line and extract arguments.
    if (argC < 2)
    {
        usage();
        return 1;
    }

    const char*                xmlFile = 0;
    AbstractDOMParser::ValSchemes domBuilderValScheme = AbstractDOMParser::Val_Auto;
    bool                       doNamespaces       = false;
    bool                       doSchema           = false;
    bool                       schemaFullChecking = false;
    bool                       doList = false;
    bool                       errorOccurred = false;
    int                        numReps =1;

    int argInd;
    for (argInd = 1; argInd < argC; argInd++)
    {
        // Break out on first parm not starting with a dash
        if (argV[argInd][0] != '-')
            break;

        // Watch for special case help request
        if (!strcmp(argV[argInd], "-?"))
        {
            usage();
            return 2;
        }
         else if (!strncmp(argV[argInd], "-v=", 3)
              ||  !strncmp(argV[argInd], "-V=", 3))
        {
            const char* const parm = &argV[argInd][3];

            if (!strcmp(parm, "never"))
                domBuilderValScheme = AbstractDOMParser::Val_Never;
            else if (!strcmp(parm, "auto"))
                domBuilderValScheme = AbstractDOMParser::Val_Auto;
            else if (!strcmp(parm, "always"))
                domBuilderValScheme = AbstractDOMParser::Val_Always;
            else
            {
                XERCES_STD_QUALIFIER cerr << "Unknown -v= value: " << parm << XERCES_STD_QUALIFIER endl;
                return 2;
            }
        }
         else if (!strcmp(argV[argInd], "-n")
              ||  !strcmp(argV[argInd], "-N"))
        {
            doNamespaces = true;
        }
         else if (!strcmp(argV[argInd], "-s")
              ||  !strcmp(argV[argInd], "-S"))
        {
            doSchema = true;
        }
         else if (!strcmp(argV[argInd], "-f")
              ||  !strcmp(argV[argInd], "-F"))
        {
            schemaFullChecking = true;
        }
         else if (!strcmp(argV[argInd], "-l")
              ||  !strcmp(argV[argInd], "-L"))
        {
            doList = true;
        }
         else if (!strncmp(argV[argInd], "-r=", 3)
              ||  !strncmp(argV[argInd], "-R=", 3))
        {
            const char* const numStr = &argV[argInd][3];
            XMLCh* numXStr = XMLString::transcode(numStr);
            numReps = XMLString::parseInt(numXStr);
            XMLString::release(&numXStr);
        }
         else
        {
            XERCES_STD_QUALIFIER cerr << "Unknown option '" << argV[argInd]
                 << "', ignoring it\n" << XERCES_STD_QUALIFIER endl;
        }
    }

    //
    //  There should be only one and only one parameter left, and that
    //  should be the file name.
    //
    if (argInd != argC - 1)
    {
        usage();
        return 1;
    }

    // Instantiate the DOM domBuilder with its memory manager.
    MemoryMonitor *domBuilderMemMonitor = new MemoryMonitor();
    static const XMLCh gLS[] = { chLatin_L, chLatin_S, chNull };
    DOMImplementation *impl = DOMImplementationRegistry::getDOMImplementation(gLS);
    DOMBuilder        *domBuilder = ((DOMImplementationLS*)impl)->createDOMBuilder(DOMImplementationLS::MODE_SYNCHRONOUS, 0, domBuilderMemMonitor);
    DOMBuilderHandler domBuilderHandler;
    domBuilder->setErrorHandler(&domBuilderHandler);

    // Instantiate the SAX2 domBuilder with its memory manager.
    MemoryMonitor *sax2MemMonitor = new MemoryMonitor();
    SAX2XMLReader *sax2parser = XMLReaderFactory::createXMLReader(sax2MemMonitor);
    SAXErrorHandler saxErrorHandler;
    sax2parser->setErrorHandler(&saxErrorHandler);

    // Instantiate the deprecated DOM parser with its memory manager.
    MemoryMonitor *depDOMMemMonitor = new MemoryMonitor();
    DOMParser *depDOMParser = new (depDOMMemMonitor)DOMParser(0, depDOMMemMonitor);
    depDOMParser->setErrorHandler(&saxErrorHandler);

    // Instantiate the SAX 1 parser with its memory manager.
    MemoryMonitor *sax1MemMonitor = new MemoryMonitor();
    SAXParser *saxParser = new (sax1MemMonitor) SAXParser(0, sax1MemMonitor);
    saxParser->setErrorHandler(&saxErrorHandler);

    // set features 
    domBuilder->setFeature(XMLUni::fgDOMNamespaces, doNamespaces);
    sax2parser->setFeature(XMLUni::fgSAX2CoreNameSpaces, doNamespaces);
    depDOMParser->setDoNamespaces(doNamespaces);
    saxParser->setDoNamespaces(doNamespaces);

    domBuilder->setFeature(XMLUni::fgXercesSchema, doSchema);
    sax2parser->setFeature(XMLUni::fgXercesSchema, doSchema);
    depDOMParser->setDoSchema(doSchema);
    saxParser->setDoSchema(doSchema);

    domBuilder->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    sax2parser->setFeature(XMLUni::fgXercesSchemaFullChecking, schemaFullChecking);
    depDOMParser->setValidationSchemaFullChecking(schemaFullChecking);
    saxParser->setValidationSchemaFullChecking(schemaFullChecking);

    if (domBuilderValScheme == AbstractDOMParser::Val_Auto)
    {
        domBuilder->setFeature(XMLUni::fgDOMValidateIfSchema, true);
        sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        sax2parser->setFeature(XMLUni::fgXercesDynamic, true);
        depDOMParser->setValidationScheme(DOMParser::Val_Auto);
        saxParser->setValidationScheme(SAXParser::Val_Auto);
    }
    else if (domBuilderValScheme == AbstractDOMParser::Val_Never)
    {
        domBuilder->setFeature(XMLUni::fgDOMValidation, false);
        sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, false);
        depDOMParser->setValidationScheme(DOMParser::Val_Never);
        saxParser->setValidationScheme(SAXParser::Val_Never);
    }
    else if (domBuilderValScheme == AbstractDOMParser::Val_Always)
    {
        domBuilder->setFeature(XMLUni::fgDOMValidation, true);
        sax2parser->setFeature(XMLUni::fgSAX2CoreValidation, true);
        sax2parser->setFeature(XMLUni::fgXercesDynamic, false);
        depDOMParser->setValidationScheme(DOMParser::Val_Always);
        saxParser->setValidationScheme(SAXParser::Val_Always);
    }

    // enable datatype normalization - default is off
    domBuilder->setFeature(XMLUni::fgDOMDatatypeNormalization, true);

    XERCES_STD_QUALIFIER ifstream fin;
    bool more = true;

    // the input is a list file
    if (doList)
        fin.open(argV[argInd]);

    if (fin.fail()) {
        XERCES_STD_QUALIFIER cerr <<"Cannot open the list file: " << argV[argInd] << XERCES_STD_QUALIFIER endl;
        return 2;
    }

    while (more)
    {
        char fURI[1000];
        //initialize the array to zeros
        memset(fURI,0,sizeof(fURI));

        if (doList) {
            if (! fin.eof() ) {
                fin.getline (fURI, sizeof(fURI));
                if (!*fURI)
                    continue;
                else {
                    xmlFile = fURI;
                    XERCES_STD_QUALIFIER cerr << "==Parsing== " << xmlFile << XERCES_STD_QUALIFIER endl;
                }
            }
            else
                break;
        }
        else {
            xmlFile = argV[argInd];
            more = false;
        }

        // parse numReps times (in case we need it for some reason)
        for (int i=0; i<numReps; i++)
        {

            XERCES_CPP_NAMESPACE_QUALIFIER DOMDocument *doc = 0;

            try
            {
                // reset document pool
                domBuilder->resetDocumentPool();

                doc = domBuilder->parseURI(xmlFile);
                sax2parser->parse(xmlFile);
                depDOMParser->parse(xmlFile);
                saxParser->parse(xmlFile);
            }
            catch (const OutOfMemoryException&)
            {
                XERCES_STD_QUALIFIER cerr << "OutOfMemoryException during parsing: '" << xmlFile << "'\n" << XERCES_STD_QUALIFIER endl;;
                continue;
            }
            catch (const XMLException& toCatch)
            {
                char *msg = XMLString::transcode(toCatch.getMessage()); 
                XERCES_STD_QUALIFIER cerr << "\nError during parsing: '" << xmlFile << "'\n"
                    << "Exception message is:  \n"
                    << msg << "\n" << XERCES_STD_QUALIFIER endl;
                XMLString::release(&msg);
                continue;
            }
            catch (const DOMException& toCatch)
            {
                const unsigned int maxChars = 2047;
                XMLCh errText[maxChars + 1];

                XERCES_STD_QUALIFIER cerr << "\nDOM Error during parsing: '" << xmlFile << "'\n"
                    << "DOMException code is:  " << toCatch.code << XERCES_STD_QUALIFIER endl;

                if (DOMImplementation::loadDOMExceptionMsg(toCatch.code, errText, maxChars))
                {
                    char * msg = XMLString::transcode(errText); 
                    XERCES_STD_QUALIFIER cerr << "Message is: " << msg << XERCES_STD_QUALIFIER endl;

                    continue;
                }
            }
            catch (...)
            {
                XERCES_STD_QUALIFIER cerr << "\nUnexpected exception during parsing: '" << xmlFile << "'\n";
                continue;
            }

        }
    }

    //
    //  Delete the domBuilder itself.  Must be done prior to calling Terminate, below.
    //
    domBuilder->release();
    delete sax2parser;
    delete depDOMParser;
    delete saxParser;

    XERCES_STD_QUALIFIER cout << "At destruction, domBuilderMemMonitor has " << domBuilderMemMonitor->getTotalMemory() << " bytes." << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "At destruction, sax2MemMonitor has " << sax2MemMonitor->getTotalMemory() << " bytes." << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "At destruction, depDOMMemMonitor has " << depDOMMemMonitor->getTotalMemory() << " bytes." << XERCES_STD_QUALIFIER endl;
    XERCES_STD_QUALIFIER cout << "At destruction, sax1MemMonitor has " << sax1MemMonitor->getTotalMemory() << " bytes." << XERCES_STD_QUALIFIER endl;
    delete domBuilderMemMonitor;
    delete sax2MemMonitor;
    delete depDOMMemMonitor;
    delete sax1MemMonitor;

    XMLPlatformUtils::Terminate();
    XERCES_STD_QUALIFIER cout << "At destruction, staticMemMonitor has " << staticMemMonitor->getTotalMemory() << " bytes." << XERCES_STD_QUALIFIER endl;
    delete staticMemMonitor;
    return 0;
}