ConstraintTypes::PlaylistDuration::PlaylistDuration( QDomElement& xmlelem, ConstraintNode* p )
        : Constraint( p )
        , m_duration( 0 )
        , m_comparison( CompareNumEquals )
        , m_strictness( 1.0 )
{
    QDomAttr a;

    a = xmlelem.attributeNode( "duration" );
    if ( !a.isNull() ) {
        m_duration = a.value().toInt();
    } else {
        // Accommodate schema change when PlaylistLength became PlaylistDuration
        a = xmlelem.attributeNode( "length" );
        if ( !a.isNull() )
            m_duration = a.value().toInt();
    }


    a = xmlelem.attributeNode( "comparison" );
    if ( !a.isNull() )
        m_comparison = a.value().toInt();

    a = xmlelem.attributeNode( "strictness" );
    if ( !a.isNull() )
        m_strictness = a.value().toDouble();
}
void
Pattern::xmlAddTransition(QDomElement _element)
{
    // a transition must have a message tag
    QDomAttr attrMessage = _element.attributeNode("message");
    if (attrMessage.isNull() ||
            attrMessage.value().isEmpty()) {
        throw BehaviourEngine::
        EMalformedPolicy(CORBA::string_dup("Transition without message."));
    }
    std::string message = attrMessage.value().latin1();

    // a transition must have a target tag
    QDomAttr attrPattern = _element.attributeNode("target");
    if (attrPattern.isNull() ||
            attrPattern.value().isEmpty()) {
        throw BehaviourEngine::
        EMalformedPolicy(CORBA::string_dup("Transition without target."));
    }
    std::string target = attrPattern.value().latin1();

    // internal transitions are only possible within some policy
    if (parent_ == NULL)
        throw BehaviourEngine::
        EMalformedPolicy(CORBA::string_dup("Internal transition at top level."));

    parent_->transitions_.insert(std::make_pair(std::make_pair(getName(),
                                 message),
                                 target));
}
Exemple #3
0
void LevelLoader::loadLine(QDomElement lineNode)
{
    // Reading the line number
    QDomAttr attribute = lineNode.attributeNode(QStringLiteral("Number"));
    QDomElement attributeNode = lineNode.firstChildElement(QStringLiteral("Number"));
    if (!attribute.isNull()) {
        m_lineNumber = attribute.value().toInt();
    } else if (!attributeNode.isNull()) {
        m_lineNumber = attributeNode.text().toInt();
    } else {
        // Standard line numbering: load next line
        m_lineNumber++;
    }

    // Reading the brick information
    attribute = lineNode.attributeNode(QStringLiteral("Bricks"));
    attributeNode = lineNode.firstChildElement(QStringLiteral("Bricks"));
    QString line;
    if (!attribute.isNull()) {
        line = attribute.value();
    } else if (!attributeNode.isNull()) {
        line = attributeNode.text();
    } else {
        line = lineNode.text();
    }

    if (line.size() > WIDTH) {
        qCritical() << "Invalid levelset " << m_levelname << ": too many bricks in line "
                    << m_lineNumber << endl;
    }

    emit newLine(line, m_lineNumber);
}
ConstraintTypes::PlaylistLength::PlaylistLength( QDomElement& xmlelem, ConstraintNode* p )
        : Constraint( p )
        , m_length( 30 )
        , m_comparison( CompareNumEquals )
        , m_strictness( 1.0 )
{
    QDomAttr a;

    a = xmlelem.attributeNode( "length" );
    if ( !a.isNull() ) {
        m_length = a.value().toInt();
        /* after 2.3.2, what was the PlaylistLength constraint became the
         * PlaylistDuration constraint, so this works around the instance when
         * a user loads an XML file generated with the old code -- sth*/
        if ( m_length > 1000 )
            m_length /= 240000;
    }

    a = xmlelem.attributeNode( "comparison" );
    if ( !a.isNull() )
        m_comparison = a.value().toInt();

    a = xmlelem.attributeNode( "strictness" );
    if ( !a.isNull() )
        m_strictness = a.value().toDouble();
}
ConstraintTypes::PlaylistFileSize::PlaylistFileSize( QDomElement& xmlelem, ConstraintNode* p )
        : Constraint( p )
        , m_size( 700 )
        , m_unit( 1 )
        , m_comparison( CompareNumEquals )
        , m_strictness( 1.0 )
{
    QDomAttr a;

    a = xmlelem.attributeNode( "size" );
    if ( !a.isNull() )
        m_size = a.value().toInt();

    a = xmlelem.attributeNode( "unit" );
    if ( !a.isNull() )
        m_unit = a.value().toInt();

    a = xmlelem.attributeNode( "comparison" );
    if ( !a.isNull() )
        m_comparison = a.value().toInt();

    a = xmlelem.attributeNode( "strictness" );
    if ( !a.isNull() )
        m_strictness = a.value().toDouble();
}
  void
  operator <<= (Miro::SensorGroupIDL& group, const QDomNode& node)
  {
    if (!node.isNull()) {

      // set sensor defaults
      Miro::SensorPositionIDL sensor;
      sensor.masked = false;
      QDomNamedNodeMap map = node.attributes();
      QDomNode n;
      n = map.namedItem("height");
      if (!n.isNull()) {
	QDomAttr attr = n.toAttr();
	if (!attr.isNull()) 
	  sensor.height = attr.value().toInt();
      }
      n = map.namedItem("distance");
      if (!n.isNull()) {
	QDomAttr attr = n.toAttr();
	if (!attr.isNull()) 
	  sensor.distance =attr.value().toInt();
      }
      n = map.namedItem("alpha");
      if (!n.isNull()) {
	QDomAttr attr = n.toAttr();
	if (!attr.isNull()) 
	  sensor.alpha = deg2Rad(attr.value().toDouble());
      }
      n = map.namedItem("beta");
      if (!n.isNull()) {
	QDomAttr attr = n.toAttr();
	if (!attr.isNull()) 
	  sensor.beta = deg2Rad(attr.value().toDouble());
      }
      n = map.namedItem("gamma");
      if (!n.isNull()) {
	QDomAttr attr = n.toAttr();
	if (!attr.isNull()) 
	  sensor.gamma = deg2Rad(attr.value().toDouble());
      }
      QDomNode n1 = node.firstChild();
      while(!n1.isNull() ) {
	if (n1.nodeName() == "description") {
	  group.description <<= n1;
	}
	else if (n1.nodeName() == "sensor") {
	  group.sensor.length(group.sensor.length() + 1);
	  group.sensor[group.sensor.length() - 1] = sensor;
	  group.sensor[group.sensor.length() - 1] <<= n1;
	}
	n1 = n1.nextSibling();
      }
    }
  }
Exemple #7
0
void LevelLoader::loadGift(QDomElement giftNode)
{
    bool nodeTextRead = false;
    // Reading the brick type
    QDomAttr attribute = giftNode.attributeNode(QStringLiteral("Type"));
    QDomElement attributeNode = giftNode.firstChildElement(QStringLiteral("Type"));
    QString giftType;
    if (!attribute.isNull()) {
        giftType = attribute.value();
    } else if (!attributeNode.isNull()) {
        giftType = attributeNode.text();
        nodeTextRead = true;
    } else {
        giftType = giftNode.text();
        nodeTextRead = true;
    }

    // Reading number of gifts to be distributed. If not specified one gift is placed.
    attribute = giftNode.attributeNode(QStringLiteral("Count"));
    attributeNode = giftNode.firstChildElement(QStringLiteral("Count"));
    int times = 1;
    bool ok = true;
    if (!attribute.isNull()) {
        times = attribute.value().toInt(&ok);
    } else if (!attributeNode.isNull()) {
        times = attributeNode.text().toInt(&ok);
        nodeTextRead = true;
    } else if (!nodeTextRead) {
        times = giftNode.text().toInt(&ok);
        if (!ok) {
            times = 1;
        }
    }

    // If only one brick to be placed: see if position is given
    QString position;
    if (times == 1) {
        attribute = giftNode.attributeNode(QStringLiteral("Position"));
        attributeNode = giftNode.firstChildElement(QStringLiteral("Position"));
        if (!attribute.isNull()) {
            position = attribute.value();
        } else if (!attributeNode.isNull()) {
            position = attributeNode.text();
            nodeTextRead = true;
        } else if (!nodeTextRead && giftNode.text().contains(QLatin1Char(','))) {
            position = giftNode.text();
            nodeTextRead = true;
        }
    }

    emit newGift(giftType, times, position);
}
BorderDrawerInterface * BorderDrawersLoader::getDrawerFromSvg(QDomElement & drawerElement)
{
    QMap<QString,QString> properties;
    QDomNamedNodeMap attributes = drawerElement.attributes();
    for (int j = attributes.count()-1; j >= 0; --j)
    {
        QDomAttr attr = attributes.item(j).toAttr();
        if (attr.isNull())
            continue;
        properties.insert(attr.name(), attr.value());
    }
    QString drawerName = properties.take("name");
    if (!instance()->registeredDrawers().contains(drawerName))
        return 0;
    BorderDrawerInterface * drawer = getDrawerByName(drawerName);
    const QMetaObject * meta = drawer->metaObject();
    int count = meta->propertyCount();
    for (int i = 0; i < count; ++i)
    {
        QMetaProperty p = meta->property(i);
        QString value = properties.take(p.name());
        if (value.isEmpty())
            continue;
        p.write(drawer, QVariant(QByteArray::fromBase64(value.toAscii())));
    }
    return drawer;
}
bool ItDocument::scanNode(QDomNode node)
{
    ItElement* itElement;
    QDomElement e = node.toElement();
    //qDebug() << "New element";
    if (!e.isNull()) {
        //QDomElement* element = static_cast<QDomElement*>(&node);
        //QDomElement element = QDomElement (node);
        QDomAttr a = e.attributeNode("id");
        QString id = "";
        if (!a.isNull() && a.namespaceURI()==idNamespaceURI) {
            id =  e.attribute("id","");
        }
        //if (!a.isNull() && a.namespaceURI()!=idNamespaceURI) {qDebug()<<"URI: "<<a.namespaceURI(); }
        //qDebug() << "Adding id:" << id;
        if (id != "") {
            if (index.contains(id)) {
                errorMessage = QObject::tr("Duplicate id '%1' for element '%2'.").arg(id, e.tagName());
                return false;
            }
            itElement = new ItElement(e);
            index[id] = itElement;
        }
        QDomNodeList children = e.childNodes();
        for (unsigned int i=0; i<children.length(); ++i) {
            if (!scanNode(children.at(i)))
                return false;
        }
    }
    return true;
}
Exemple #10
0
void NewsSite::parseAtom(QDomDocument domDoc)
{
    QDomNodeList entries = domDoc.elementsByTagName("entry");

    for (unsigned int i = 0; i < (unsigned) entries.count(); i++)
    {
        QDomNode itemNode = entries.item(i);
        QString title =  ReplaceHtmlChar(itemNode.namedItem("title").toElement()
                                         .text().simplified());

        QDomNode summNode = itemNode.namedItem("summary");
        QString description = QString::null;
        if (!summNode.isNull())
        {
            description = ReplaceHtmlChar(
                summNode.toElement().text().simplified());
        }

        QDomNode linkNode = itemNode.namedItem("link");
        QString url = QString::null;
        if (!linkNode.isNull())
        {
            QDomAttr linkHref = linkNode.toElement().attributeNode("href");
            if (!linkHref.isNull())
                url = linkHref.value();
        }

        insertNewsArticle(NewsArticle(title, description, url));
    }
}
    bool operator()(QDomNode node) {
	QDomElement elem = node.toElement();
	QDomAttr attr = elem.attributeNode("id");
	if(!attr.isNull() && attr.value() == m_value) {
	    return true;
	}
	return false;
    }
Exemple #12
0
void LevelLoader::loadLevel(QList< Brick* >& bricks)
{   
    // Selecting the correct level
    m_level++;
    
    if( m_levelset == 0 ){
        qDebug() << "Error: No levelset specified" << endl;
        return;
    }
    
    QDomElement levels = m_levelset->documentElement();
    QDomNode node = levels.firstChild();
    for( int i = 1; i < m_level; i++ ){
        node = node.nextSibling();
    }
    // --
    
    // Load level information
    if( node.isNull() || node.toElement().tagName() != "Level" ){
        // Level not found or no more levels
        return;
    }
    
    QDomAttr attribute;
    QDomElement level = node.toElement();
    if( level.isNull() ){
        qDebug() << "Invalid Levelset " << m_levelname << ": Can't read level information";
    }
    attribute = level.attributeNode("Name");
    QString levelName;
    if( !attribute.isNull() ){
        levelName = level.attributeNode("Name").value();
    }
    node = node.firstChild();
    // --
    
    // Load bricks and gifts
    m_lineNumber = 0;
    while( !node.isNull() ){
        QDomElement info = node.toElement();
        if( info.isNull() ){ qDebug() << "Invalid levelset " << m_levelname << ": Can't read level information."; }
            
        if( info.tagName() == "Line" ){
            // Load one line of bricks
            loadLine( info, bricks );
        } else if( info.tagName() == "Gift" ){
            // Load one gift type
            loadGift( info, bricks );
        } else {
            qDebug() << "Invalid tag name " << info.tagName() << " has occured in level "
                     << levelName << " in levelset " << m_levelname << endl;
        }
        
        node = node.nextSibling();
    }
}
Exemple #13
0
void LevelLoader::loadLine(QDomElement lineNode, QList< Brick* >& bricks)
{
    // Reading the line number
    QDomAttr attribute = lineNode.attributeNode("Number");
    QDomElement attributeNode = lineNode.firstChildElement("Number");
    if( !attribute.isNull() ){
        m_lineNumber = attribute.value().toInt();
    } else if( !attributeNode.isNull() ) {
        m_lineNumber = attributeNode.text().toInt();
    } else {
        // Standard line numbering: load next line
        m_lineNumber++;
    }
    
    // Reading the brick information
    attribute = lineNode.attributeNode("Bricks");
    attributeNode = lineNode.firstChildElement("Bricks");
    QString line;
    if( !attribute.isNull() ){
        line = attribute.value();
    } else if( !attributeNode.isNull() ) {
        line = attributeNode.text();
    } else {
        line = lineNode.text();
    }

    if( line.size() > WIDTH ){
        qDebug() << "Invalid levelset " << m_levelname << ": too many bricks in line "
                 << m_lineNumber << endl;
    }
    
    // Convert line information to bricks
    for( int x = 0; x < line.size(); x++ ){
        char charType = line[x].toLatin1();
        if (charType != '-') {
            bricks.append( new Brick(m_game, getTypeFromChar(charType), x+1, m_lineNumber) );
        }
    }
}
Exemple #14
0
KXMLGUIClient::ActionPropertiesMap KXMLGUIClient::extractActionProperties( const QDomDocument &doc )
{
  ActionPropertiesMap properties;

  QDomElement actionPropElement = doc.documentElement().namedItem( "ActionProperties" ).toElement();

  if ( actionPropElement.isNull() )
    return properties;

  QDomNode n = actionPropElement.firstChild();
  while(!n.isNull())
  {
    QDomElement e = n.toElement();
    n = n.nextSibling(); // Advance now so that we can safely delete e
    if ( e.isNull() )
      continue;

    if ( e.tagName().lower() != "action" )
      continue;

    QString actionName = e.attribute( "name" );

    if ( actionName.isEmpty() )
      continue;

    QMap<QString, QMap<QString, QString> >::Iterator propIt = properties.find( actionName );
    if ( propIt == properties.end() )
      propIt = properties.insert( actionName, QMap<QString, QString>() );

    const QDomNamedNodeMap attributes = e.attributes();
    const uint attributeslength = attributes.length();

    for ( uint i = 0; i < attributeslength; ++i )
    {
      const QDomAttr attr = attributes.item( i ).toAttr();

      if ( attr.isNull() )
        continue;

      const QString name = attr.name();

      if ( name == "name" || name.isEmpty() )
        continue;

      (*propIt)[ name ] = attr.value();
    }

  }

  return properties;
}
  void
  DifferentialMotionParameters::operator <<= (const QDomNode& _node)
  {
    Super::operator<<=(_node);

    QDomNode n = _node.firstChild();
    while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {            // the node was really an element.
	if (e.tagName()=="parameter") {
	  QDomAttr parameterName = e.attributeNode("name");
	  QString name;
	  QString value;

	  if (!parameterName.isNull()) {
	    name = parameterName.value();
	  }
	  else {
	    throw Exception("Parameter tag without name.");
	  }

	  QDomNode n2 = n.firstChild();
	  while (!n2.isNull()) {
	    QDomText t = n2.toText(); // try to convert the node to a text
	    if(!t.isNull() ) {        // the node was really a text element.
	      value = t.data();
	      break;
	    }
	    n2 = n2.nextSibling();
	  }
	  if (n2.isNull())
	    throw Exception("Parameter " + std::string(name) + "without value.");
	  
	  if (name == "MinLTranslation")
	    minLTranslation = value.toInt();
	  else if (name == "MaxLTranslation")
	    maxLTranslation = value.toInt();
	  else if (name == "MinRTranslation")
	    minRTranslation = value.toInt();
	  else if (name == "MaxRTranslation")
	    maxRTranslation = value.toInt();
	  else if (name == "WheelBase")
	    wheelBase = value.toInt();
	}
      }
      n = n.nextSibling();
    }
  }
Exemple #16
0
void PdfElement::setAttributes(const QDomNamedNodeMap attr, const QString cdata) {
	_attributes.clear();
	if (cdata != NULL && !cdata.isEmpty()) {
		extractExpressions(const_cast<QString*>(&cdata));
		_attributes.insert("cdata", cdata);
	}
	QString val;
	for (uint i = 0; i < attr.length(); i++) {
		QDomAttr a = attr.item(i).toAttr();
		if (!a.isNull()) {
			if (a.name().toLower() == "nth") {
				_onlyOnLast = a.value().toLower() == "last";
				_onlyOnFirst = a.value().toLower() == "first";
				_onlyOnNth = _onlyOnLast || _onlyOnFirst ? 1 : a.value().toInt();
			}
			val = a.value();
			extractExpressions(const_cast<QString*>(&val));
			_attributes.insert(a.name().toLower(), val);
		}
	}
}
Exemple #17
0
void LevelLoader::loadGift(QDomElement giftNode, QList< Brick* >& bricks)
{
    // Build list of bricks without a gift
    QList<Brick *> bricksLeft = bricks;
    QMutableListIterator<Brick *> i(bricksLeft);
    while (i.hasNext()) {
        Brick *brick = i.next();
        if (brick->identifier() == "UnbreakableBrick" || brick->hasGift() ){
            i.remove();
        }
    }

    bool nodeTextRead = false;
    // Reading the brick type
    QDomAttr attribute = giftNode.attributeNode("Type");
    QDomElement attributeNode = giftNode.firstChildElement("Type");
    QString giftType;
    if( !attribute.isNull() ){
        giftType = attribute.value();
    } else if( !attributeNode.isNull() ){
        giftType = attributeNode.text();
        nodeTextRead = true;
    } else {
        giftType = giftNode.text();
        nodeTextRead = true;
    }

    // Reading number of gifts to be distributed. If not specified one gift is placed.
    attribute = giftNode.attributeNode("Count");
    attributeNode = giftNode.firstChildElement("Count");
    int times = 1;
    bool ok = true;
    if( !attribute.isNull() ){
        times = attribute.value().toInt( &ok );
    } else if( !attributeNode.isNull() ){
        times = attributeNode.text().toInt( &ok );
        nodeTextRead = true;
    } else if( !nodeTextRead ){
        times = giftNode.text().toInt( &ok );
        if( !ok ){ times = 1; }
    }
    
    if( bricksLeft.count() < times ){
        qDebug() << "Invalid levelset " << m_levelname << ": In Level " << m_level
                 << " are too many gifts of type " << giftType << endl;
    }
    
    // If only one brick to be placed: see if position is given
    QPoint position;
    if( times == 1 ){
        attribute = giftNode.attributeNode("Position");
        attributeNode = giftNode.firstChildElement("Position");
        if( !attribute.isNull() ){
            position = positionFromString( attribute.value() );
        } else if( !attributeNode.isNull() ){
            position = positionFromString( attributeNode.text() );
            nodeTextRead = true;
        } else if( !nodeTextRead && giftNode.text().contains(',') ){
            position = positionFromString( giftNode.text() );
            nodeTextRead = true;
        }
    }
        
    if( !position.isNull() ){
        // Put gift at given position
        Brick *giftBrick = brickAt( position, bricks ); 
        if( giftBrick == 0 ){
            qDebug() << "Invalid levelset " << m_levelname << ": Can't place gift at position ("
                     << position.x() << "," << position.y() << "). There is no brick.\n";
        } else {
            if( giftBrick->hasGift() ){
                // Brick already has a gift -> move this gift to a random position
                int index = qrand() % bricksLeft.count();
                bricksLeft.at(index)->setGift( giftBrick->gift() );
            }
            Gift *newgift = new Gift(giftType);
            newgift->hide();
            giftBrick->setGift(newgift);
        }
    } else {
        // Distribute gifts randomly
        for( int i = 0; i < times; i++ ){
            Gift *gift = new Gift(giftType);
            gift->hide();
            
            int index = qrand() % bricksLeft.count();
            bricksLeft.at(index)->setGift(gift);
            bricksLeft.removeAt(index);
        }
    }
}
Exemple #18
0
void updateTimeEntryFromXml(const QDomElement& timeEntryElement,
                            TimeEntry* timeEntryOut) {
  Q_ASSERT(timeEntryOut);

  for (QDomElement elem(timeEntryElement.firstChildElement()); !elem.isNull();
       elem = elem.nextSiblingElement()) {
    if (elem.tagName() == "id") {
      timeEntryOut->id = elem.text().toInt();
      continue;
    }

    if (elem.tagName() == "project") {
      QDomAttr idAttr = elem.attributeNode("id");
      if (!idAttr.isNull())
        timeEntryOut->projectId = idAttr.value().toInt();

      QDomAttr nameAttr = elem.attributeNode("name");
      if (!nameAttr.isNull())
        timeEntryOut->projectName = nameAttr.value();
    }

    if (elem.tagName() == "issue") {
      QDomAttr idAttr = elem.attributeNode("id");
      if (!idAttr.isNull())
        timeEntryOut->issueId = idAttr.value().toInt();

      QDomAttr nameAttr = elem.attributeNode("name");
      if (!nameAttr.isNull())
        timeEntryOut->issueName = nameAttr.value();
    }

    if (elem.tagName() == "user") {
      QDomAttr idAttr = elem.attributeNode("id");
      if (!idAttr.isNull())
        timeEntryOut->userId = idAttr.value().toInt();

      QDomAttr nameAttr = elem.attributeNode("name");
      if (!nameAttr.isNull())
        timeEntryOut->userName = nameAttr.value();
    }

    if (elem.tagName() == "activity") {
      QDomAttr idAttr = elem.attributeNode("id");
      if (!idAttr.isNull())
        timeEntryOut->activityId = idAttr.value().toInt();

      QDomAttr nameAttr = elem.attributeNode("name");
      if (!nameAttr.isNull())
        timeEntryOut->activityName = nameAttr.value();
    }

    if (elem.tagName() == "hours") {
      timeEntryOut->hours = elem.text().toFloat();
      continue;
    }

    if (elem.tagName() == "comments") {
      timeEntryOut->comments = elem.text();
      continue;
    }

    if (elem.tagName() == "spent_on") {
      timeEntryOut->spentOn = QDate::fromString(elem.text());
      continue;
    }

    if (elem.tagName() == "created_on") {
      timeEntryOut->createdOn = QDateTime::fromString(elem.text());
      continue;
    }

    if (elem.tagName() == "updated_on") {
      timeEntryOut->updatedOn = QDateTime::fromString(elem.text());
      continue;
    }
  }
}
Exemple #19
0
CConfiguration::CConfiguration(QWidget*       canvasWidget,
                               const QString& configFile)
   : m_CanvasWidget(canvasWidget),
     m_DisplaySizeX(0),
     m_DisplaySizeY(0)
{
   m_Nodes.setAutoDelete(true);

   QDomDocument doc("ScenarioSetup");
   QFile file(configFile);
   if(!file.open(QIODevice::ReadOnly)) {
      throw ELoadFileException();
   }

   QString errorMessage;
   int errorLine;
   if(!doc.setContent(&file , true , &errorMessage, &errorLine)) {
      file.close();
      throw EXMLSyntaxException(errorMessage, errorLine);
   }
   file.close();

   QDomNode currentNode = doc.documentElement().firstChild();
   while(!currentNode.isNull()) {
      if(QDomNode::ElementNode == currentNode.nodeType()) {
         if(currentNode.toElement().tagName() == QString(g_RefreshTimeTag)) {
            m_RefreshTime = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ListenPortTag)) {
            m_ListenPort = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ResolutionXTag)) {
            m_DisplaySizeX = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ResolutionYTag)) {
            m_DisplaySizeY = currentNode.toElement().text().toInt();
         }
         else if(currentNode.toElement().tagName() == QString(g_ProtocolColorTag)) {
            QDomAttr Attribute = currentNode.toElement().attributeNode(QString(g_ProtocolColorIDTag));
            if(!Attribute.isNull()) {
               m_ColorMap[Attribute.value().toInt()] = currentNode.toElement().text();
            }
         }
         else if(currentNode.toElement().tagName() == QString(g_BackgroundImageTag)) {
            m_BackgroundImageName = currentNode.toElement().text();
         }
         else if(currentNode.toElement().tagName() == QString(g_CaptionTag)) {
            m_Caption = currentNode.toElement().text();
         }
         else if((currentNode.toElement().tagName() == QString(g_NodeTag)) ||
                 (currentNode.toElement().tagName() == QString(g_RSPNodeTag))) {
            CNode* node = createNode(currentNode.toElement());
            m_Nodes.append(node);
            m_NodesMap[node->getUniqueID()] = node;
         }
         else {
            QMessageBox::critical(0, "Error!", "Found unknown tag in config file: " +
                                  currentNode.toElement().tagName());
         }
      }
      currentNode = currentNode.nextSibling();
   }

   m_NetworkListener = new CNetworkListener(m_ListenPort, m_NodesMap);
}
  void
  ActionPattern::xmlInit(const QDomNode& _node, const ActionPatternMap& _apMap) 
  {
    ArbiterRepository * ar = ArbiterRepository::instance();
    BehaviourRepository * br = BehaviourRepository::instance();

    // first pass
    // retrieve arbiter

    // we need it to register the behaviours there

    QDomNode n = _node.firstChild();
    while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {            // the node was really an element.

	QDomAttr attribute = e.attributeNode("name");

	// retrieve arbiter
	if (e.tagName()=="arbiter") {
	  if (arbiter_ == NULL) {
	    if (!attribute.isNull() && !attribute.value().isEmpty()) {
	      string name(attribute.value());
	      Arbiter* a;
	      if ((a = ar->getArbiter(name)) != 0) {
		ArbiterParameters * params = a->getParametersInstance();
		arbiter(a, params);
		
	      } 
	      else {
		std::string error("Arbiter not registered: " + name);
		throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	      }
	    } 
	    else {
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Arbiter without name."));
	    }
	  }
	  else {
	   throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Multiple arbiters specified."));
	  }
	}
	// syntax checking 
	else if (e.tagName() != "behaviour" && e.tagName() != "transition") {
	  std::string error("Unknown tag name: " + string(e.tagName()));
	  throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	}
      }
      n = n.nextSibling();
    }

    // There has to be exact one arbiter
    if (arbiter_ == NULL) {
      std::string error("ActionPattern without an arbiter: " + actionPatternName_);
      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
    }
    
    // second pass 
    // retrieve behaviours and transitions
    
    n = _node.firstChild();
    while( !n.isNull() ) {
      QDomElement e = n.toElement(); // try to convert the node to an element.
      if( !e.isNull() ) {            // the node was really an element.

	QDomAttr attribute = e.attributeNode("name");

	// retrieve behaviours
	if (e.tagName() == "behaviour") {
	  if (!attribute.isNull() && !attribute.value().isEmpty()) {
	    string name(attribute.value());

	    Behaviour * behaviour;
	    BehaviourParameters * parameters;
	    if ((behaviour = br->getBehaviour(name)) != 0) {
	      parameters = behaviour->getParametersInstance();

	      KeyValueList params;
	      params <<= n;

	      *parameters <<= params;
	      addBehaviour(behaviour, parameters);
	    } 
	    else {
	      std::string error("Behaviour not registered: " + name);
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	    }
	  } 
	  else {
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Behaviour without name."));		
	  }
	}

	// retrieve transitions
	else if (e.tagName() == "transition") {
	  QDomAttr attrMessage = e.attributeNode("message");
	  string message;

	  if (!attrMessage.isNull() && !attrMessage.value().isEmpty()) {
	    message = string(attrMessage.value());
	  } 
	  else {
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without message."));
	  }
	  
	  QDomAttr attrPattern = e.attributeNode("target");
	  if (!attrPattern.isNull() && !attrPattern.value().isEmpty()) {
	    string patternname = string(attrPattern.value());
	    ActionPatternMap::const_iterator iter = _apMap.find(patternname);

	    if (iter != _apMap.end())
	      addTransition(message, iter->second);
	    else {
	      std::string error("ActionPattern for transition not registered: " + 
				message + " --> " + patternname + ".");
	      throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup(error.c_str()));
	    }
	  }
	  else
	    throw BehaviourEngine::EMalformedPolicy(CORBA::string_dup("Transition without target."));
	}
      }
      n = n.nextSibling();
    }
  }
Exemple #21
0
void AtlantikNetwork::processNode(QDomNode n)
{
	QDomAttr a;

	for ( ; !n.isNull() ; n = n.nextSibling() )
	{
		QDomElement e = n.toElement();
		if(!e.isNull())
		{
			if (e.tagName() == "server")
			{
				a = e.attributeNode( QString("version") );
				if ( !a.isNull() )
					m_serverVersion = a.value();

				emit receivedHandshake();
			}
			else if (e.tagName() == "msg")
			{
				a = e.attributeNode(QString("type"));
				if (!a.isNull())
				{
					if (a.value() == "error")
						emit msgError(e.attributeNode(QString("value")).value());
					else if (a.value() == "info")
						emit msgInfo(e.attributeNode(QString("value")).value());
					else if (a.value() == "chat")
						emit msgChat(e.attributeNode(QString("author")).value(), e.attributeNode(QString("value")).value());
				}
			}
			else if (e.tagName() == "display")
			{
				int estateId = -1;

				a = e.attributeNode(QString("estateid"));
				if (!a.isNull())
				{
					estateId = a.value().toInt();
					Estate *estate;
					estate = m_atlanticCore->findEstate(a.value().toInt());

					emit displayDetails(e.attributeNode(QString("text")).value(), e.attributeNode(QString("cleartext")).value().toInt(), e.attributeNode(QString("clearbuttons")).value().toInt(), estate);

					bool hasButtons = false;
					for( QDomNode nButtons = n.firstChild() ; !nButtons.isNull() ; nButtons = nButtons.nextSibling() )
					{
						QDomElement eButton = nButtons.toElement();
						if (!eButton.isNull() && eButton.tagName() == "button")
						{
							emit addCommandButton(eButton.attributeNode(QString("command")).value(), eButton.attributeNode(QString("caption")).value(), eButton.attributeNode(QString("enabled")).value().toInt());
							hasButtons = true;
						}
					}

					if (!hasButtons)
						emit addCloseButton();
				}
			}
			else if (e.tagName() == "client")
			{
				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
					m_playerId = a.value().toInt();

				a = e.attributeNode(QString("cookie"));
				if (!a.isNull())
					emit clientCookie(a.value());
			}
			else if (e.tagName() == "configupdate")
			{
				int configId = -1;
				a = e.attributeNode(QString("configid"));
				if (!a.isNull())
				{
					configId = a.value().toInt();
					ConfigOption *configOption;
					if (!(configOption = m_atlanticCore->findConfigOption(configId)))
						configOption = m_atlanticCore->newConfigOption( configId );

					a = e.attributeNode(QString("name"));
					if (configOption && !a.isNull())
						configOption->setName(a.value());

					a = e.attributeNode(QString("description"));
					if (configOption && !a.isNull())
						configOption->setDescription(a.value());

					a = e.attributeNode(QString("edit"));
					if (configOption && !a.isNull())
						configOption->setEdit(a.value().toInt());

					a = e.attributeNode(QString("value"));
					if (configOption && !a.isNull())
						configOption->setValue(a.value());

					if (configOption)
						configOption->update();
				}

				int gameId = -1;
				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					gameId = a.value().toInt();
					for( QDomNode nOptions = n.firstChild() ; !nOptions.isNull() ; nOptions = nOptions.nextSibling() )
					{
						QDomElement eOption = nOptions.toElement();
						if (!eOption.isNull() && eOption.tagName() == "option")
							emit gameOption(eOption.attributeNode(QString("title")).value(), eOption.attributeNode(QString("type")).value(), eOption.attributeNode(QString("value")).value(), eOption.attributeNode(QString("edit")).value(), eOption.attributeNode(QString("command")).value());
					}
					emit endConfigUpdate();
				}
			}
			else if (e.tagName() == "deletegame")
			{
				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					int gameId = a.value().toInt();

					Game *game = m_atlanticCore->findGame(gameId);
					if (game)
						m_atlanticCore->removeGame(game);
				}
			}
			else if (e.tagName() == "gameupdate")
			{
				int gameId = -1;

				a = e.attributeNode(QString("gameid"));
				if (!a.isNull())
				{
					gameId = a.value().toInt();

					Player *playerSelf = m_atlanticCore->playerSelf();
					if ( playerSelf && playerSelf->game() )
						kdDebug() << "gameupdate for " << QString::number(gameId) << " with playerSelf in game " << QString::number(playerSelf->game()->id()) << endl;
					else
						kdDebug() << "gameupdate for " << QString::number(gameId) << endl;


					Game *game = 0;
					if (gameId == -1)
					{
						a = e.attributeNode(QString("gametype"));
						if ( !a.isNull() && !(game = m_atlanticCore->findGame(a.value())) )
							game = m_atlanticCore->newGame(gameId, a.value());
					}
					else if (!(game = m_atlanticCore->findGame(gameId)))
						game = m_atlanticCore->newGame(gameId);

					a = e.attributeNode(QString("canbejoined"));
					if (game && !a.isNull())
						game->setCanBeJoined(a.value().toInt());

					a = e.attributeNode(QString("description"));
					if (game && !a.isNull())
						game->setDescription(a.value());

					a = e.attributeNode(QString("name"));
					if (game && !a.isNull())
						game->setName(a.value());

					a = e.attributeNode(QString("players"));
					if (game && !a.isNull())
						game->setPlayers(a.value().toInt());

					a = e.attributeNode(QString("master"));
					if (game && !a.isNull())
					{
						// Ensure setMaster succeeds by creating player if necessary
						Player *player = m_atlanticCore->findPlayer( a.value().toInt() );
						if ( !player )
							player = m_atlanticCore->newPlayer( a.value().toInt() );
						game->setMaster( player );
					}

					QString status = e.attributeNode(QString("status")).value();
					if ( m_serverVersion.left(4) == "0.9." || (playerSelf && playerSelf->game() == game) )
					{
						if (status == "config")
							emit gameConfig();
						else if (status == "init")
							emit gameInit();
						else if (status == "run")
							emit gameRun();
						else if (status == "end")
							emit gameEnd();
					}

					if (game)
						game->update();
				}
			}
			else if (e.tagName() == "deleteplayer")
			{
				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
				{
					int playerId = a.value().toInt();

					Player *player = m_atlanticCore->findPlayer(playerId);
					if (player)
						m_atlanticCore->removePlayer(player);
				}
			}
			else if (e.tagName() == "playerupdate")
			{
				int playerId = -1;

				a = e.attributeNode(QString("playerid"));
				if (!a.isNull())
				{
					playerId = a.value().toInt();

					Player *player;
					if (!(player = m_atlanticCore->findPlayer(playerId)))
						player = m_atlanticCore->newPlayer( playerId, (m_playerId == playerId) );

					// Update player name
					a = e.attributeNode(QString("name"));
					if (player && !a.isNull())
						player->setName(a.value());

					// Update player game
					a = e.attributeNode(QString("game"));
					if (player && !a.isNull())
					{
						int gameId = a.value().toInt();
						if (gameId == -1)
							player->setGame( 0 );
						else
						{
							// Ensure setGame succeeds by creating game if necessary
							Game *game = m_atlanticCore->findGame(a.value().toInt());
							if (!game)
								game = m_atlanticCore->newGame(a.value().toInt()); // 
							player->setGame( game );
						}
					}

					// Update player host
					a = e.attributeNode(QString("host"));
					if (player && !a.isNull())
						player->setHost(a.value());

					// Update player image/token
					a = e.attributeNode(QString("image"));
					if (player && !a.isNull())
						player->setImage(a.value());

					// Update player money
					a = e.attributeNode(QString("money"));
					if (player && !a.isNull())
						player->setMoney(a.value().toInt());

					a = e.attributeNode(QString("bankrupt"));
					if (player && !a.isNull())
						player->setBankrupt(a.value().toInt());

					a = e.attributeNode(QString("hasdebt"));
					if (player && !a.isNull())
						player->setHasDebt(a.value().toInt());

					a = e.attributeNode(QString("hasturn"));
					if (player && !a.isNull())
						player->setHasTurn(a.value().toInt());

					// Update whether player can roll
					a = e.attributeNode(QString("can_roll"));
					if (player && !a.isNull())
						player->setCanRoll(a.value().toInt());

					// Update whether player can buy
					a = e.attributeNode(QString("can_buyestate"));
					if (player && !a.isNull())
						player->setCanBuy(a.value().toInt());

					// Update whether player can auction
					a = e.attributeNode(QString("canauction"));
					if (player && !a.isNull())
						player->setCanAuction(a.value().toInt());

					// Update whether player can use a card
					a = e.attributeNode(QString("canusecard"));
					if (player && !a.isNull())
						player->setCanUseCard(a.value().toInt());

					// Update whether player is jailed
					a = e.attributeNode(QString("jailed"));
					if (player && !a.isNull())
					{
						player->setInJail(a.value().toInt());
						// TODO: emit signal with player ptr so board can setText and display something
					}

					// Update player location
					a = e.attributeNode(QString("location"));
					if (!a.isNull())
					{
						m_playerLocationMap[player] = a.value().toInt();

						bool directMove = false;

						Estate *estate = m_atlanticCore->findEstate(a.value().toInt());

						a = e.attributeNode(QString("directmove"));
						if (!a.isNull())
							directMove = a.value().toInt();

						if (player && estate)
						{
							if (directMove)
								player->setLocation(estate);
							else
								player->setDestination(estate);
						}
					}

					if (player)
						player->update();
				}
			}
			else if (e.tagName() == "estategroupupdate")
			{
				a = e.attributeNode(QString("groupid"));
				if (!a.isNull())
				{
					int groupId = a.value().toInt();

					EstateGroup *estateGroup = 0;
					bool b_newEstateGroup = false;
					
					if (!(estateGroup = m_atlanticCore->findEstateGroup(groupId)))
					{
						// Create EstateGroup object
						estateGroup = m_atlanticCore->newEstateGroup(a.value().toInt());
						b_newEstateGroup = true;
					}

					a = e.attributeNode(QString("name"));
					if (estateGroup && !a.isNull())
						estateGroup->setName(a.value());

					// Emit signal so GUI implementations can create view(s)
					// TODO:  port to atlanticcore and create view there
					if (estateGroup)
					{
						if (b_newEstateGroup)
							emit newEstateGroup(estateGroup);
						estateGroup->update();
					}
				}
			}
			else if (e.tagName() == "estateupdate")
			{
				int estateId = -1;

				a = e.attributeNode(QString("estateid"));
				if (!a.isNull())
				{
					estateId = a.value().toInt();
					
					Estate *estate = 0;
					bool b_newEstate = false;

					// FIXME: allow any estateId, GUI should not use it to determin its geometry
					if (estateId >= 0 && estateId < 100 && !(estate = m_atlanticCore->findEstate(a.value().toInt())))
					{
						// Create estate object
						estate = m_atlanticCore->newEstate(estateId);
						b_newEstate = true;

						QObject::connect(estate, SIGNAL(estateToggleMortgage(Estate *)), this, SLOT(estateToggleMortgage(Estate *)));
						QObject::connect(estate, SIGNAL(estateHouseBuy(Estate *)), this, SLOT(estateHouseBuy(Estate *)));
						QObject::connect(estate, SIGNAL(estateHouseSell(Estate *)), this, SLOT(estateHouseSell(Estate *)));
						QObject::connect(estate, SIGNAL(newTrade(Player *)), this, SLOT(newTrade(Player *)));

						// Players without estate should get one
						Player *player = 0;
						QPtrList<Player> playerList = m_atlanticCore->players();
						for (QPtrListIterator<Player> it(playerList); (player = *it) ; ++it)
							if (m_playerLocationMap[player] == estate->id())
								player->setLocation(estate);
					}

					a = e.attributeNode(QString("name"));
					if (estate && !a.isNull())
						estate->setName(a.value());

					a = e.attributeNode(QString("color"));
					if (estate && !a.isNull() && !a.value().isEmpty())
						estate->setColor(a.value());

					a = e.attributeNode(QString("bgcolor"));
					if (estate && !a.isNull())
						estate->setBgColor(a.value());

					a = e.attributeNode(QString("owner"));
					Player *player = m_atlanticCore->findPlayer(a.value().toInt());
					if (estate && !a.isNull())
						estate->setOwner(player);

					a = e.attributeNode(QString("houses"));
					if (estate && !a.isNull())
						estate->setHouses(a.value().toInt());

					a = e.attributeNode(QString("mortgaged"));
					if (estate && !a.isNull())
						estate->setIsMortgaged(a.value().toInt());

					a = e.attributeNode(QString("group"));
					if (!a.isNull())
					{
						EstateGroup *estateGroup = m_atlanticCore->findEstateGroup(a.value().toInt());
						if (estate)
							estate->setEstateGroup(estateGroup);
					}

					a = e.attributeNode(QString("can_toggle_mortgage"));
					if (estate && !a.isNull())
						estate->setCanToggleMortgage(a.value().toInt());

					a = e.attributeNode(QString("can_be_owned"));
					if (estate && !a.isNull())
						estate->setCanBeOwned(a.value().toInt());

					a = e.attributeNode(QString("can_buy_houses"));
					if (estate && !a.isNull())
						estate->setCanBuyHouses(a.value().toInt());

					a = e.attributeNode(QString("can_sell_houses"));
					if (estate && !a.isNull())
						estate->setCanSellHouses(a.value().toInt());

					a = e.attributeNode(QString("price"));
					if (estate && !a.isNull())
						estate->setPrice(a.value().toInt());

					a = e.attributeNode(QString("houseprice"));
        				if (estate && !a.isNull())
                				estate->setHousePrice(a.value().toInt());

        				a = e.attributeNode(QString("sellhouseprice"));
        				if (estate && !a.isNull())
                				estate->setHouseSellPrice(a.value().toInt());
						
					a = e.attributeNode(QString("mortgageprice"));
        				if (estate && !a.isNull())
                				estate->setMortgagePrice(a.value().toInt());

        				a = e.attributeNode(QString("unmortgageprice"));
        				if (estate && !a.isNull())
                				estate->setUnmortgagePrice(a.value().toInt());
						
					a = e.attributeNode(QString("money"));
					if (estate && !a.isNull())
						estate->setMoney(a.value().toInt());

					// Emit signal so GUI implementations can create view(s)
					// TODO:  port to atlanticcore and create view there
					if (estate)
					{
						if (b_newEstate)
							emit newEstate(estate);
						estate->update();
					}
				}
			}
Exemple #22
0
void Layer7::LoadSlot(QNetworkReply *reply) {

    switch (op) {

    case lsoStart:

        emit UpdateSignal("Loading started...");
        Logger::ins.Header() << "Loading registry data from " << http.Url() << "data/ started...\r\n";
        http.Propfind(http.Url() + "data/");
        op = lsoListDomains;

        break;

    case lsoListDomains:

        if (reply->error() == QNetworkReply::NoError) {

            QString replyString(reply->readAll());
            sl::log << "lsoListDomains: " << SQ(replyString) << sl::end;

            Propfinds elements = http.ParsePropfindReply(replyString);
            for (Propfinds::iterator e = elements.begin(); e != elements.end(); ++e)
                if (e->href != http.Url()) {
                    domains.push_back(GtDomain(SQ(e->href), SQ(e->name)));
                    Logger::ins.Info() << "Service domain: " << e->name << "\r\n";
                    emit UpdateSignal("Service Domain: " + e->name);
                }

            if (SelectFirstDomain()) {

                loaded = true;

                // check if all domains match domains from the db

                for (unsigned int d = 0; d < domains.size(); ++d)
                    if (!sdoms.contains(QS(domains[d].name))) {
                        loaded = false;
                        Logger::ins.Error() << "Repository does not contain service domain named " << QS(domains[d].name) << "\r\n";
                        emit DoneSignal("Repository does not contain service domain named " + QS(domains[d].name));
                    }

                if (loaded) {
                    op = lsoListServices;
                    http.Propfind(QS(SelectedDomain().href) + "web/");
                }
            }
        }
        else
            emit UpdateSignal(reply->errorString());

        break;

    case lsoListServices:

        if (reply->error() == QNetworkReply::NoError) {

            QString replyString(reply->readAll());
            sl::log << "lsoListServices: " << SQ(replyString) << sl::end;

            Propfinds elements = http.ParsePropfindReply(replyString);
            for (Propfinds::iterator e = elements.begin(); e != elements.end(); ++e)
                if (e->href != http.Url() && e->name != "OLD" && e->name != "REMOVED") {

                    endpoints.push_back(GtEndpoint(item++ * 100 + REPO_TB_IDX, SelectedDomain().name, SQ(e->href), SQ(e->name)));
                    Logger::ins.Info() << "Service: " << e->name << "\r\n";
                    emit UpdateSignal("Service: " + e->name);
                }
        }
        else
            emit UpdateSignal(reply->errorString());

        if (SelectNextDomain())
            http.Propfind(QS(SelectedDomain().href) + "web/");
        else if (SelectFirstEndpoint()) {
            Logger::ins.Info() << "Parsing index files...\r\n";
            emit UpdateSignal("Parsing index files...");
            op = lsoGetIndexXml;
            Logger::ins.Info() << "Parsing " << QS(SelectedEndpoint().urlRegistryFolder) << "index.xml...\r\n";
            http.Get(QS(SelectedEndpoint().urlRegistryFolder) + "index.xml");
        }

        break;

    case lsoGetIndexXml:

        if (reply->error() == QNetworkReply::NoError) {

            QString replyString(reply->readAll());
            sl::log << "lsoGetIndexXml: " << SQ(replyString) << sl::end;

            QDomDocument doc;
            doc.setContent(replyString);

            for (QDomElement r = doc.firstChildElement(); !r.isNull(); r = r.nextSiblingElement()) {

                if (r.nodeName() == "service") {

                    for (QDomElement e = r.firstChildElement(); !e.isNull(); e = e.nextSiblingElement()) {

                        if (e.nodeName() == "files") {

                            for (QDomElement f = e.firstChildElement(); !f.isNull(); f = f.nextSiblingElement()) {

                                QDomAttr r = f.attributeNode("root"), t = f.attributeNode("type");
                                if (!r.isNull() && r.nodeValue() == "true" && !t.isNull() && t.value() == "WSDL")
                                    SelectedEndpoint().urlWSDL = SQ(f.text());
                            }
                        }
                        else if (e.nodeName() == "name")
                            SelectedEndpoint().intGivenName = SQ(e.text());
                        else if (e.nodeName() == "version")
                            SelectedEndpoint().intGivenVersion = SQ(e.text());
                        else if (e.nodeName() == "policyVersion")
                            SelectedEndpoint().policyVersion = SQ(e.text());
                        else if (e.nodeName() == "enabled")
                            SelectedEndpoint().enabled = SQ(e.text());
                        else if (e.nodeName() == "soap")
                            SelectedEndpoint().soap = SQ(e.text());
                        else if (e.nodeName() == "resolutionPath")
                            SelectedEndpoint().resolutionPath = SQ(e.text());
                        else if (e.nodeName() == "id")
                            SelectedEndpoint().intGivenId = SQ(e.text());
                        else if (e.nodeName() == "protectedEndpoint")
                            SelectedEndpoint().protectedEndpoint = SQ(e.text());
                    }

                    break;
                }
            }

            if (SelectedEndpoint().urlWSDL == "") {
                Logger::ins.Warning() << "WSDL file url not found for endpoint '" << QS(SelectedEndpoint().intGivenName) << "'\r\n";
                emit UpdateSignal("WSDL file url not found for endpoint '" + QS(SelectedEndpoint().intGivenName) + "'");
                SelectedEndpoint().serviceName = SelectedEndpoint().intGivenName;
            }

            if (SelectedEndpoint().protectedEndpoint == "") {
                Logger::ins.Warning() << "Ignoring non-protected endpoint '" << QS(SelectedEndpoint().intGivenName) << "'\r\n";
                emit UpdateSignal("Ignoring non-protected endpoint '" + QS(SelectedEndpoint().intGivenName) + "'");
                RemoveSelectedEndpoint();
            }
        }
        else {
            Logger::ins.Error() << reply->errorString() << "\r\n";
            emit UpdateSignal(reply->errorString());
        }

        if (SelectNextEndpoint()) {
            Logger::ins.Info() << "Parsing " << QS(SelectedEndpoint().urlRegistryFolder) << "index.xml...\r\n";
            http.Get(QS(SelectedEndpoint().urlRegistryFolder) + "index.xml");
        }
        else if (SelectFirstEndpoint()) {
            Logger::ins.Info() << "Parsing WSDL files...\r\n";
            emit UpdateSignal("Parsing WSDL files...");
            op = lsoGetWsdl;
            Logger::ins.Info() << "Parsing " << QS(SelectedEndpoint().urlRegistryFolder + SelectedEndpoint().urlWSDL) << "\r\n";
            http.Get(QS(SelectedEndpoint().urlRegistryFolder + SelectedEndpoint().urlWSDL));
        }

        break;

    case lsoGetWsdl:

        if (reply->error() == QNetworkReply::NoError) {

            QString replyString(reply->readAll());
            sl::log << "lsoGetWsdl: " << SQ(replyString) << sl::end;

            QDomDocument doc;
            doc.setContent(replyString);

            for (QDomElement r = doc.firstChildElement(); !r.isNull(); r = r.nextSiblingElement()) {
                if (r.nodeName() == "definitions" || r.nodeName() == "wsdl:definitions") {

                    QDomAttr n = r.attributeNode("targetNamespace");
                    if (!n.isNull())
                        SelectedEndpoint().targetNamespace = SQ(n.nodeValue());

                    n = r.attributeNode("name");
                    if (!n.isNull())
                        SelectedEndpoint().definitionName = SQ(n.nodeValue());

                    // find all service names

                    std::vector<std::string> serviceNames;
                    for (QDomElement e = r.firstChildElement(); !e.isNull(); e = e.nextSiblingElement()) {

                        if (e.nodeName() == "service" || e.nodeName() == "wsdl:service") {
                            QDomAttr a = e.attributeNode("name");
                            if (!a.isNull())
                                serviceNames.push_back(SQ(a.nodeValue()));
                        }
                    }

                    // assign service name

                    if (serviceNames.size() == 1)
                        SelectedEndpoint().serviceName = serviceNames[0];
                    else if (serviceNames.size() > 1) {

                        // search service node name with best fit to protected endpoint string

                        std::map<int, std::string> m;
                        for (std::vector<std::string>::iterator s = serviceNames.begin(); s != serviceNames.end(); ++s)
                            m.insert(std::pair<int, std::string>(LevenshteinDistance(SelectedEndpoint().protectedEndpoint, *s, true), *s));

                        SelectedEndpoint().serviceName = m.begin()->second;
                    }
                    else {
                        Logger::ins.Warning() << "Service name not found for endpoint '" << QS(SelectedEndpoint().intGivenName) + "'\r\n";
                        emit UpdateSignal("Service name not found for endpoint '" + QS(SelectedEndpoint().intGivenName) + "'");
                        SelectedEndpoint().serviceName = SelectedEndpoint().intGivenName;
                    }

                    break;
                }
            }
        }
        else {
            Logger::ins.Error() << reply->errorString() << "\r\n";
            emit UpdateSignal(reply->errorString());
        }

        if (SelectNextEndpoint()) {
            Logger::ins.Info() << "Parsing " << QS(SelectedEndpoint().urlRegistryFolder + SelectedEndpoint().urlWSDL) << "\r\n";
            http.Get(QS(SelectedEndpoint().urlRegistryFolder + SelectedEndpoint().urlWSDL));
        }
        else {
            Logger::ins.Info() << "Finished loading registry.\r\n";
            emit DoneSignal("Finished loading.");
        }

        break;

    default:
        ;
    }
}
Exemple #23
0
void NewsSite::parseRSS(QDomDocument domDoc)
{
    QMutexLocker locker(&m_lock);

    QDomNode channelNode = domDoc.documentElement().namedItem("channel");

    m_desc = channelNode.namedItem("description")
        .toElement().text().simplified();

    QDomNode imageNode = channelNode.namedItem("image");
    if (!imageNode.isNull())
        m_imageURL = imageNode.namedItem("url").toElement().text().simplified();

    QDomNodeList items = domDoc.elementsByTagName("item");

    for (unsigned int i = 0; i < (unsigned) items.count(); i++)
    {
        QDomNode itemNode = items.item(i);
        QString title = ReplaceHtmlChar(itemNode.namedItem("title")
                                        .toElement().text().simplified());

        QDomNode descNode = itemNode.namedItem("description");
        QString description = QString::null;
        if (!descNode.isNull())
        {
            description = descNode.toElement().text().simplified();
            description = ReplaceHtmlChar(description);
        }

        QDomNode linkNode = itemNode.namedItem("link");
        QString url = QString::null;
        if (!linkNode.isNull())
            url = linkNode.toElement().text().simplified();

        QDomNode enclosureNode = itemNode.namedItem("enclosure");
        QString enclosure = QString::null;
        QString enclosure_type = QString::null;
        QString thumbnail = QString::null;
        if (!enclosureNode.isNull())
        {
            QDomAttr enclosureURL = enclosureNode.toElement()
                .attributeNode("url");

            if (!enclosureURL.isNull())
                enclosure  = enclosureURL.value();

            QDomAttr enclosureType = enclosureNode.toElement()
                .attributeNode("type");
            if (!enclosureType.isNull()) 
            {
                enclosure_type  = enclosureType.value();

                if (enclosure_type == "image/jpeg")
                {
                    thumbnail = enclosure;
                    enclosure = QString::null;
                }

                // fix for broken feeds that don't add the enclosure type
                if (enclosure_type == "" || enclosure_type.isNull())
                {
                    QStringList imageExtensions = QStringList() << ".jpg" << ".jpeg" << ".png" << ".gif";
                    for (int x = 0; x < imageExtensions.count(); x++)
                    {
                        if (enclosure.toLower().endsWith(imageExtensions[x]))
                        {
                            thumbnail = enclosure;
                            enclosure = QString::null;
                            break;
                        }
                    }
                }
            }
        }

        //////////////////////////////////////////////////////////////
        // From this point forward, we process RSS 2.0 media tags.
        // Please put all other tag processing before this comment.
        // See http://www.rssboard.org/media-rss for details
        //////////////////////////////////////////////////////////////

        // Some media: tags can be enclosed in a media:group item.
        // If this item is present, use it to find the media tags,
        // otherwise, proceed.
        QDomNode mediaGroup = itemNode.namedItem("media:group");
        if (!mediaGroup.isNull())
            itemNode = mediaGroup;

        QDomNode thumbNode = itemNode.namedItem("media:thumbnail");
        if (!thumbNode.isNull())
        {
            QDomAttr thumburl = thumbNode.toElement().attributeNode("url");
            if (!thumburl.isNull())
                thumbnail = thumburl.value();
        }

        QDomNode playerNode = itemNode.namedItem("media:player");
        QString mediaurl = QString::null;
        if (!playerNode.isNull())
        {
            QDomAttr mediaURL = playerNode.toElement().attributeNode("url");
            if (!mediaURL.isNull())
                mediaurl = mediaURL.value();
        }

        // If present, the media:description superscedes the RSS description
        descNode = itemNode.namedItem("media:description");
        if (!descNode.isNull())
            description = descNode.toElement().text().simplified();

        // parse any media:content items looking for any images or videos
        QDomElement e = itemNode.toElement();
        QDomNodeList mediaNodes = e.elementsByTagName("media:content");
        for (int x = 0; x < mediaNodes.count(); x++)
        {
            QString medium;
            QString type;
            QString url;

            QDomElement mediaElement = mediaNodes.at(x).toElement();

            if (mediaElement.isNull())
                continue;

            if (mediaElement.hasAttribute("medium"))
                medium = mediaElement.attributeNode("medium").value();

            if (mediaElement.hasAttribute("type"))
                type = mediaElement.attributeNode("type").value();

            if (mediaElement.hasAttribute("url"))
                url = mediaElement.attributeNode("url").value();

            LOG(VB_GENERAL, LOG_DEBUG,
                QString("parseRSS found media:content: medium: %1, type: %2, url: %3")
                        .arg(medium).arg(type).arg(url));

            // if this is an image use it as the thumbnail if we haven't found one yet
            if (thumbnail.isEmpty() && (medium == "image" || isImage(type)))
                thumbnail = url;

            // if this is a video use it as the enclosure if we haven't found one yet
            if (enclosure.isEmpty() && (medium == "video" || isVideo(type)))
                enclosure = url;
        }

        insertNewsArticle(NewsArticle(title, description, url,
                                      thumbnail, mediaurl, enclosure));
    }
}