Ejemplo n.º 1
1
QgsFeatureRenderer* QgsFeatureRenderer::loadSld( const QDomNode &node, QgsWkbTypes::GeometryType geomType, QString &errorMessage )
{
  QDomElement element = node.toElement();
  if ( element.isNull() )
    return nullptr;

  // get the UserStyle element
  QDomElement userStyleElem = element.firstChildElement( "UserStyle" );
  if ( userStyleElem.isNull() )
  {
    // UserStyle element not found, nothing will be rendered
    errorMessage = "Info: UserStyle element not found.";
    return nullptr;
  }

  // get the FeatureTypeStyle element
  QDomElement featTypeStyleElem = userStyleElem.firstChildElement( "FeatureTypeStyle" );
  if ( featTypeStyleElem.isNull() )
  {
    errorMessage = "Info: FeatureTypeStyle element not found.";
    return nullptr;
  }

  // use the RuleRenderer when more rules are present or the rule
  // has filters or min/max scale denominators set,
  // otherwise use the SingleSymbol renderer
  bool needRuleRenderer = false;
  int ruleCount = 0;

  QDomElement ruleElem = featTypeStyleElem.firstChildElement( "Rule" );
  while ( !ruleElem.isNull() )
  {
    ruleCount++;

    // more rules present, use the RuleRenderer
    if ( ruleCount > 1 )
    {
      QgsDebugMsg( "more Rule elements found: need a RuleRenderer" );
      needRuleRenderer = true;
      break;
    }

    QDomElement ruleChildElem = ruleElem.firstChildElement();
    while ( !ruleChildElem.isNull() )
    {
      // rule has filter or min/max scale denominator, use the RuleRenderer
      if ( ruleChildElem.localName() == "Filter" ||
           ruleChildElem.localName() == "MinScaleDenominator" ||
           ruleChildElem.localName() == "MaxScaleDenominator" )
      {
        QgsDebugMsg( "Filter or Min/MaxScaleDenominator element found: need a RuleRenderer" );
        needRuleRenderer = true;
        break;
      }

      ruleChildElem = ruleChildElem.nextSiblingElement();
    }

    if ( needRuleRenderer )
    {
      break;
    }

    ruleElem = ruleElem.nextSiblingElement( "Rule" );
  }

  QString rendererType;
  if ( needRuleRenderer )
  {
    rendererType = "RuleRenderer";
  }
  else
  {
    rendererType = "singleSymbol";
  }
  QgsDebugMsg( QString( "Instantiating a '%1' renderer..." ).arg( rendererType ) );

  // create the renderer and return it
  QgsRendererAbstractMetadata* m = QgsRendererRegistry::instance()->rendererMetadata( rendererType );
  if ( !m )
  {
    errorMessage = QString( "Error: Unable to get metadata for '%1' renderer." ).arg( rendererType );
    return nullptr;
  }

  QgsFeatureRenderer* r = m->createRendererFromSld( featTypeStyleElem, geomType );
  return r;
}
Ejemplo n.º 2
0
Archivo: Tv.cpp Proyecto: juriad/tvp
void Tv::addSubElement( QDomElement &element) {
  if(element.localName().compare("Programme", Qt::CaseInsensitive)==0) {
    Programme *cn = Programme::fromElement(element);
    addProgramme(cn);
    return;
  }
  if(element.localName().compare("Channel", Qt::CaseInsensitive)==0) {
    Channel *cn = Channel::fromElement(element);
    addChannel(cn);
    return;
  }
}
Ejemplo n.º 3
0
void Rating::addSubElement( QDomElement &element) {
  if(element.localName().compare("Icon", Qt::CaseInsensitive)==0) {
    Icon *cn = Icon::fromElement(element);
    addIcon(cn);
    return;
  }
  if(element.localName().compare("Value", Qt::CaseInsensitive)==0) {
    Value *cn = Value::fromElement(element);
    addValue(cn);
    return;
  }
}
Ejemplo n.º 4
0
QList<QDomElement> Entry::unhandledElements() const
{
    // TODO: do not hardcode this list here
    QList<ElementType> handled;
    handled.append(ElementType(QLatin1String("author"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("contributor"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("category"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("id"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("link"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("rights"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("source"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("published"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("updated"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("summary"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("title"), atom1Namespace()));
    handled.append(ElementType(QLatin1String("content"), atom1Namespace()));
    
    QList<QDomElement> notHandled;
    
    QDomNodeList children = element().childNodes();
    for (int i = 0; i < children.size(); ++i)
    {
        QDomElement el = children.at(i).toElement();
        if (!el.isNull() 
             && !handled.contains(ElementType(el.localName(), el.namespaceURI())))
        {
            notHandled.append(el);
        }
    }
    
    return notHandled;
}
Ejemplo n.º 5
0
void Reader::loadAnnotations(const QDomElement& annotations)
{
	QDomNodeList nodes = annotations.childNodes();
	for(int n=0;n<nodes.count();++n) {
		QDomElement e = nodes.at(n).toElement();
		if(e.isNull())
			continue;
		if(e.namespaceURI()==DP_NAMESPACE && e.localName()=="a") {
			_commands.append(MessagePtr(new protocol::AnnotationCreate(
				0,
				++_annotationid,
				e.attribute("x").toInt(),
				e.attribute("y").toInt(),
				e.attribute("w").toInt(),
				e.attribute("h").toInt()
			)));
			_commands.append(MessagePtr(new protocol::AnnotationEdit(
				_annotationid,
				e.attribute("bg").mid(1).toUInt(0,16),
				e.text()
			)));
		} else {
			qWarning() << "unhandled annotations (DP ext.) element:" << e.tagName();
		}
	}
}
Ejemplo n.º 6
0
void XSchemaSequence::scanForElements(QDomElement &element, void * /*context*/)
{
    QString name = element.localName();
    if(element.prefix() == _root->namespacePrefix()) {
        if(name == IO_XSD_ANNOTATION) {
            readHandleAnnotation(element);
            return;
        } else if(name == IO_XSD_TAGELEMENT) {
            readHandleObject(element, new XSchemaElement(this, _root));
            return ;
        } else if(name == IO_XSD_GROUP) {
            readHandleObject(element, new XSchemaGroup(this, _root));
            return ;
        } else if(name == IO_XSD_CHOICE) {
            readHandleObject(element, new XSchemaChoice(this, _root));
            return ;
        } else if(name == IO_XSD_SEQUENCE) {
            readHandleObject(element, new XSchemaSequence(this, _root));
            return ;
        } else if(name == IO_XSD_ANY) {
            readHandleObject(element, new XSchemaAny(this, _root));
            return ;
        }
    }
    raiseError(this, element, true);
}
Ejemplo n.º 7
0
QList<QDomElement> Item::unhandledElements() const
{
    // TODO: do not hardcode this list here
    QList<ElementType> handled;
    handled.append(ElementType(QLatin1String("title")));
    handled.append(ElementType(QLatin1String("link")));
    handled.append(ElementType(QLatin1String("description")));
    handled.append(ElementType(QLatin1String("pubDate")));
    handled.append(ElementType(QLatin1String("expirationDate")));
    handled.append(ElementType(QLatin1String("rating")));
    handled.append(ElementType(QLatin1String("source")));
    handled.append(ElementType(QLatin1String("guid")));
    handled.append(ElementType(QLatin1String("comments")));
    handled.append(ElementType(QLatin1String("author")));
    handled.append(ElementType(QLatin1String("date"), dublinCoreNamespace()));
    
    QList<QDomElement> notHandled;
    
    QDomNodeList children = element().childNodes();
    for (int i = 0; i < children.size(); ++i)
    {
        QDomElement el = children.at(i).toElement();
        if (!el.isNull() 
             && !handled.contains(ElementType(el.localName(), el.namespaceURI())))
        {
            notHandled.append(el);
        }
    }
    
    return notHandled;
}
Ejemplo n.º 8
0
void Subtitles::addSubElement( QDomElement &element) {
  if(element.localName().compare("Language", Qt::CaseInsensitive)==0) {
    Language *cn = Language::fromElement(element);
    addLanguage(cn);
    return;
  }
}
Ejemplo n.º 9
0
bool KoStyleStack::isUserStyle( const QDomElement& e, const QString& family ) const
{
    if ( e.attributeNS( m_styleNSURI, "family", QString::null ) != family )
        return false;
    const QDomElement parent = e.parentNode().toElement();
    //kdDebug(30003) << k_funcinfo << "tagName=" << e.tagName() << " parent-tagName=" << parent.tagName() << endl;
    return parent.localName() == "styles" /*&& parent.namespaceURI() == KoXmlNS::office*/;
}
Ejemplo n.º 10
0
bool KPrTextDocument::loadSpanTag( const QDomElement& tag, KoOasisContext& context,
                                  KoTextParag* parag, uint pos,
                                  QString& textData, KoTextCustomItem* & customItem )
{
    const QString localName( tag.localName() );
    const bool isTextNS = tag.namespaceURI() == KoXmlNS::text;
    kdDebug( 32500 ) << "KPrTextDocument::loadSpanTag: " << localName << endl;

    if ( isTextNS )
    {
        if ( localName == "a" )
        {
            QString href( tag.attributeNS( KoXmlNS::xlink, "href", QString::null ) );
            if ( href.startsWith( "#" ) )
            {
                context.styleStack().save();
                // We have a reference to a bookmark (### TODO)
                // As we do not support it now, treat it as a <span> without formatting
                parag->loadOasisSpan( tag, context, pos ); // recurse
                context.styleStack().restore();
            }
            else
            {
                // The text is contained in a <span> inside the <a> element. In theory
                // we could have multiple spans there, but OO ensures that there is always only one,
                // splitting the hyperlink if necessary (at format changes).
                // Note that we ignore the formatting of the span.
                QDomElement spanElem = KoDom::namedItemNS( tag, KoXmlNS::text, "span" );
                QString text;
                if ( spanElem.isNull() )
                    text = tag.text();
                if ( spanElem.isNull() )
                    text = tag.text();
                else {
                    // The save/restore of the stack is done by the caller (KoTextParag::loadOasisSpan)
                    // This allows to use the span's format for the variable.
                    //kdDebug(32500) << "filling stack with " << spanElem.attributeNS( KoXmlNS::text, "style-name", QString::null ) << endl;
                    context.fillStyleStack( spanElem, KoXmlNS::text, "style-name", "text" );
                    text = spanElem.text();
                }
                textData = KoTextObject::customItemChar(); // hyperlink placeholder
                // unused tag.attributeNS( KoXmlNS::office, "name", QString::null )
                KoVariableCollection& coll = context.variableCollection();
                customItem = new KoLinkVariable( this, text, href,
                        coll.formatCollection()->format( "STRING" ),
                        &coll );
            }
            return true;
        }
    }
    else // non "text:" tags
    {
        kdDebug()<<"Extension found tagName : "<< localName <<endl;
    }
    return false;
}
Ejemplo n.º 11
0
/**
 * \brief obtain direct child elements of a certain kind.  unlike
 *        elementsByTagNameNS, this function does not descend beyond the first
 *        level of children.
 * \param e parent element
 * \param nsURI namespace of the elements to find
 * \param localName local name of the elements to find
 * \return the node list of found elements (empty list if none are found)
 */
XDomNodeList childElementsByTagNameNS(const QDomElement &e, const QString &nsURI, const QString &localName)
{
	XDomNodeList out;
	for(QDomNode n = e.firstChild(); !n.isNull(); n = n.nextSibling()) {
		if(!n.isElement())
			continue;
		QDomElement i = n.toElement();
		if(i.namespaceURI() == nsURI && i.localName() == localName)
			out.append(i);
	}
	return out;
}
Ejemplo n.º 12
0
void XSchemaSimpleTypeUnion::scanForElements(QDomElement &element, void * /*context*/)
{
    QString name = element.localName();
    if(element.prefix() == _root->namespacePrefix()) {
        if(name == IO_XSD_ANNOTATION) {
            readHandleAnnotation(element);
        } else if(name == IO_XSD_SIMPLETYPE) {
            readHandleObject(element, new XSchemaElement(this, _root));
        } else {
            raiseError(this, element, true);
        }
    } else {
        raiseError(this, element, true);
    }
}
Ejemplo n.º 13
0
// stripExtraNS
//
// This function removes namespace information from various nodes for
// display purposes only (the element is pretty much useless for processing
// after this).  We do this because QXml is a bit overzealous about outputting
// redundant namespaces.
static QDomElement stripExtraNS(const QDomElement &e)
{
	// find closest parent with a namespace
	QDomNode par = e.parentNode();
	while(!par.isNull() && par.namespaceURI().isNull())
		par = par.parentNode();
	bool noShowNS = false;
	if(!par.isNull() && par.namespaceURI() == e.namespaceURI())
		noShowNS = true;

	// build qName (prefix:localName)
	QString qName;
	if(!e.prefix().isEmpty())
		qName = e.prefix() + ':' + e.localName();
	else
		qName = e.tagName();

	QDomElement i;
	int x;
	if(noShowNS)
		i = e.ownerDocument().createElement(qName);
	else
		i = e.ownerDocument().createElementNS(e.namespaceURI(), qName);

	// copy attributes
	QDomNamedNodeMap al = e.attributes();
	for(x = 0; x < al.count(); ++x) {
		QDomAttr a = al.item(x).cloneNode().toAttr();

		// don't show xml namespace
		if(a.namespaceURI() == NS_XML)
			i.setAttribute(QString("xml:") + a.name(), a.value());
		else
			i.setAttributeNodeNS(a);
	}

	// copy children
	QDomNodeList nl = e.childNodes();
	for(x = 0; x < nl.count(); ++x) {
		QDomNode n = nl.item(x);
		if(n.isElement())
			i.appendChild(stripExtraNS(n.toElement()));
		else
			i.appendChild(n.cloneNode());
	}
	return i;
}
Ejemplo n.º 14
0
void XSchemaSimpleTypeRestriction::scanForElements(QDomElement &element, void *context)
{
    XScanContext *theContext = (XScanContext*) context;
    QString name = element.localName();
    QString value = element.attribute(IO_FACET_ATTR_VALUE, "");
    if(element.prefix() == _root->namespacePrefix()) {
        if(name == IO_XSD_ANNOTATION) {
            readHandleAnnotation(element);
        } else if(name == IO_XSD_SIMPLETYPE) {
            if(theContext->childFound) {
                raiseError(this, element, true);
            }
            theContext->childFound = true;
            readHandleObject(element, new XSchemaElement(this, _root));
            /*} else if( scanForFacets( name, value, _facets ) ) { TODO: fare poi
                  // nothing TODO: delete*/
        } else if(name == IO_XSD_MINEXCLUSIVE) {
            _facets._minExclusive = value;
        } else if(name == IO_XSD_MININCLUSIVE) {
            _facets._minInclusive = value;
        } else if(name == IO_XSD_MAXEXCLUSIVE) {
            _facets._maxExclusive = value;
        } else if(name == IO_XSD_MAXINCLUSIVE) {
            _facets._maxInclusive = value;
        } else if(name == IO_XSD_TOTALDIGITS) {
            _facets._totalDigits = value;
        } else if(name == IO_XSD_FRACTIONDIGITS) {
            _facets._fractionDigits = value;
        } else if(name == IO_XSD_LENGTH) {
            _facets._length = value;
        } else if(name == IO_XSD_MINLENGTH) {
            _facets._minLength = value;
        } else if(name == IO_XSD_MAXLENGTH) {
            _facets._maxLength = value;
        } else if(name == IO_XSD_ENUMERATION) {   // TODO: WRONG!!!!
            _facets._enumeration.append(value);
        } else if(name == IO_XSD_WHITESPACE) {  // TODO: WRONG!!!!
            _facets._whiteSpace = value;
        } else if(name == IO_XSD_PATTERN) {
            _facets._pattern = value;
        } else {
            raiseError(this, element, true);
        }
    } else {
        raiseError(this, element, true);
    }
}
Ejemplo n.º 15
0
 XmlConfig getUserDefines() const
 {
     XmlConfig cfg;
     QDomElement root = domDocument.documentElement();
     QDomElement child;
     if (!root.isNull()) {
         child = root.firstChildElement();
         while (!child.isNull()) {
             std::string name = (const char*)child.localName().toAscii();
             std::string value = (const char*)child.text().toUtf8();
             if (std::find(filter.begin(), filter.end(), name) != filter.end())
                 cfg[name] = value;
             child = child.nextSiblingElement();
         }
     }
     return cfg;
 }
Ejemplo n.º 16
0
QDomElement ElementWrapper::firstElementByTagNameNS(const QString& nsURI, const QString& localName) const
{
    if (isNull())
        return QDomElement();
    
    for (QDomNode n = d->element.firstChild(); !n.isNull(); n = n.nextSibling())
    {
        if (n.isElement())
        {
            QDomElement e = n.toElement();
            if (e.localName() == localName && e.namespaceURI() == nsURI)
                return e;
        }
    }
    
    return QDomElement();
}
Ejemplo n.º 17
0
QList<QDomElement> ElementWrapper::elementsByTagNameNS(const QString& nsURI, const QString& localName) const
{
    if (isNull())
        return QList<QDomElement>();
    
    QList<QDomElement> elements;
    for (QDomNode n = d->element.firstChild(); !n.isNull(); n = n.nextSibling())
    {
        if (n.isElement())
        {
            QDomElement e = n.toElement();
            if (e.localName() == localName && e.namespaceURI() == nsURI)
                elements.append(e);
        }
    }
    return elements;
}
Ejemplo n.º 18
0
bool KoDocumentInfoUserMetadata::loadOasis( const QDomNode& metaDoc )
{
    QDomNode n = metaDoc.firstChild();
    for ( ; !n.isNull(); n = n.nextSibling() )
    {
        if (n.isElement())
        {
            QDomElement e = n.toElement();
            if ( e.namespaceURI() == KoXmlNS::meta && e.localName() == "user-defined" && !e.text().isEmpty() )
            {
                QString name = e.attributeNS( KoXmlNS::meta, "name", QString::null );
                if ( !m_reserved.contains( name ) )
                    m_metaList[ name ] = e.text();
            }
        }
    }
    return true;
}
Ejemplo n.º 19
0
bool KoDocumentInfoAuthor::loadOasis( const QDomNode& metaDoc )
{
    QDomElement e = KoDom::namedItemNS( metaDoc, KoXmlNS::dc, "creator" );
    if ( !e.isNull() && !e.text().isEmpty() )
        m_fullName = e.text();
    QDomNode n = metaDoc.firstChild();
    for ( ; !n.isNull(); n = n.nextSibling() )
    {
        if (n.isElement())
        {
            QDomElement e = n.toElement();
            if ( e.namespaceURI() == KoXmlNS::meta && e.localName() == "user-defined" && !e.text().isEmpty() )
            {
                QString name = e.attributeNS( KoXmlNS::meta, "name", QString::null );
                if ( name == "initial" )
                    m_initial = e.text();
                else if ( name == "author-title" )
                    m_title = e.text();
                else if ( name == "company" )
                    m_company = e.text();
                else if ( name == "email" )
                    m_email = e.text();
                else if ( name == "telephone" )
                    m_telephoneHome = e.text();
                else if ( name == "telephone-work" )
                    m_telephoneWork = e.text();
                else if ( name == "fax" )
                    m_fax = e.text();
                else if ( name == "country" )
                    m_country = e.text();
                else if ( name == "postal-code" )
                    m_postalCode = e.text();
                else if ( name == "city" )
                    m_city = e.text();
                else if ( name == "street" )
                    m_street = e.text();
                else if ( name == "position" )
                    m_position = e.text();
            }
        }
    }
    return true;
}
Ejemplo n.º 20
0
QgsFeatureRendererV2* QgsSingleSymbolRendererV2::createFromSld( QDomElement& element, Qgis::GeometryType geomType )
{
  // XXX this renderer can handle only one Rule!

  // get the first Rule element
  QDomElement ruleElem = element.firstChildElement( "Rule" );
  if ( ruleElem.isNull() )
  {
    QgsDebugMsg( "no Rule elements found!" );
    return nullptr;
  }

  QString label, description;
  QgsSymbolLayerV2List layers;

  // retrieve the Rule element child nodes
  QDomElement childElem = ruleElem.firstChildElement();
  while ( !childElem.isNull() )
  {
    if ( childElem.localName() == "Name" )
    {
      // <se:Name> tag contains the rule identifier,
      // so prefer title tag for the label property value
      if ( label.isEmpty() )
        label = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName() == "Description" )
    {
      // <se:Description> can contains a title and an abstract
      QDomElement titleElem = childElem.firstChildElement( "Title" );
      if ( !titleElem.isNull() )
      {
        label = titleElem.firstChild().nodeValue();
      }

      QDomElement abstractElem = childElem.firstChildElement( "Abstract" );
      if ( !abstractElem.isNull() )
      {
        description = abstractElem.firstChild().nodeValue();
      }
    }
    else if ( childElem.localName() == "Abstract" )
    {
      // <sld:Abstract> (v1.0)
      description = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName() == "Title" )
    {
      // <sld:Title> (v1.0)
      label = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName().endsWith( "Symbolizer" ) )
    {
      // create symbol layers for this symbolizer
      QgsSymbolLayerV2Utils::createSymbolLayerV2ListFromSld( childElem, geomType, layers );
    }

    childElem = childElem.nextSiblingElement();
  }

  if ( layers.isEmpty() )
    return nullptr;

  // now create the symbol
  QgsSymbolV2 *symbol;
  switch ( geomType )
  {
    case Qgis::Line:
      symbol = new QgsLineSymbolV2( layers );
      break;

    case Qgis::Polygon:
      symbol = new QgsFillSymbolV2( layers );
      break;

    case Qgis::Point:
      symbol = new QgsMarkerSymbolV2( layers );
      break;

    default:
      QgsDebugMsg( QString( "invalid geometry type: found %1" ).arg( geomType ) );
      return nullptr;
  }

  // and finally return the new renderer
  return new QgsSingleSymbolRendererV2( symbol );
}
Ejemplo n.º 21
0
void
XSPFLoader::gotBody()
{
    qDebug() << Q_FUNC_INFO;

    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() ) {
        if (n.namespaceURI() == m_NS && n.localName() == "title") {
            origTitle = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "creator") {
            m_creator = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "info") {
            m_info = n.text();
        } else if (n.namespaceURI() == m_NS && n.localName() == "trackList") {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );

    bool shownError = false;
    for ( unsigned int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() ) {
            if (n.namespaceURI() == m_NS && n.localName() == "duration") {
                duration = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "annotation") {
                annotation = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "creator") {
                artist = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "album") {
                album = n.text();
            } else if (n.namespaceURI() == m_NS && n.localName() == "title") {
                track = n.text();
            }
        }
        
        if( artist.isEmpty() || track.isEmpty() ) {
            if( !shownError ) {
                QMessageBox::warning( 0, tr( "Failed to save tracks" ), tr( "Some tracks in the playlist do not contain an artist and a title. They will be ignored." ), QMessageBox::Ok );
                shownError = true;
            }
            continue;
        }

        plentry_ptr p( new PlaylistEntry );
        p->setGuid( uuid() );
        p->setDuration( duration.toInt() / 1000 );
        p->setLastmodified( 0 );
        p->setAnnotation( annotation );

        p->setQuery( Tomahawk::Query::get( artist, track, album, uuid() ) );
        p->query()->setDuration( duration.toInt() / 1000 );
        m_entries << p;
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        if ( m_autoCreate )
        {
            QMessageBox::critical( 0, tr( "XSPF Error" ), tr( "This is not a valid XSPF playlist." ) );
            deleteLater();
            return;
        }
        else
        {
            emit failed();
            return;
        }
    }

    if ( m_autoCreate )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false );

        m_playlist->createNewRevision( uuid(), m_playlist->currentrevision(), m_entries );
        deleteLater();
    }

    emit ok( m_playlist );
}
Ejemplo n.º 22
0
ResourcePtr ModelMaker::readResource(Model& model, const QDomElement& el)
{
    QString rdfns = RDFVocab::self()->namespaceURI();
    QString about = QLatin1String("about");
    QString resource = QLatin1String("resource");
    QString descriptionStr = QLatin1String("Description");

    ResourcePtr res;

    ResourcePtr type = model.createResource(el.namespaceURI() + el.localName());

    if (*type == *(RDFVocab::self()->seq()))
    {
        SequencePtr seq = model.createSequence(el.attribute(about));
        
        res = seq;
    }
    else
    {
        res = model.createResource(el.attribute(about));
    }

    model.addStatement(res, RDFVocab::self()->type(), type);

    QDomNodeList children = el.childNodes();

    bool isSeq = res->isSequence();
    
    for (uint i = 0; i < children.length(); ++i)
    {
        if (children.item(i).isElement())
        {
            QDomElement ce = children.item(i).toElement();
        
            PropertyPtr pred = model.createProperty(ce.namespaceURI() + ce.localName());
        
            if (ce.hasAttribute(resource)) // referenced Resource via (rdf:)resource
            {
                NodePtr obj = model.createResource(ce.attribute(resource));
                
                if (isSeq && *pred == *(RDFVocab::self()->li()))
                {
                    SequencePtr tseq = boost::static_pointer_cast<Sequence>(res);
                    tseq->append(obj);
                }
                else
                    model.addStatement(res, pred, obj);
            }
            else if (!ce.text().isEmpty() && ce.lastChildElement().isNull()) // Literal
            {
                NodePtr obj = model.createLiteral(ce.text());
                
                if (isSeq && *pred == *(RDFVocab::self()->li()))
                {
                    SequencePtr tseq = boost::static_pointer_cast<Sequence>(res);
                    tseq->append(obj);
                }
                else
                    model.addStatement(res, pred, obj);
            }
            else // embedded description
            {
                QDomElement re = ce.lastChildElement();
                
                QString uri = re.attribute(about);
                
                // read recursively
                NodePtr obj = readResource(model, re);
                
                if (isSeq && *pred == *(RDFVocab::self()->li()))
                {
                    SequencePtr tseq = boost::static_pointer_cast<Sequence>(res);
                    tseq->append(obj);
                }
                else
                    model.addStatement(res, pred, obj);

            }
        
        //TODO: bag, reification (nice to have, but not important for basic RSS 1.0)
        }
    }
    
    return res;
}
Ejemplo n.º 23
0
  QDomDocument createTransactionDocument( QgsServerInterface* serverIface, const QString& version,
                                          const QgsServerRequest& request )
  {
    Q_UNUSED( version );

    QDomDocument doc;

    QgsWfsProjectParser* configParser = getConfigParser( serverIface );
#ifdef HAVE_SERVER_PYTHON_PLUGINS
    QgsAccessControl* accessControl = serverIface->accessControls();
#endif
    const QString requestBody = request.getParameter( QStringLiteral( "REQUEST_BODY" ) );

    QString errorMsg;
    if ( !doc.setContent( requestBody, true, &errorMsg ) )
    {
      throw QgsRequestNotWellFormedException( errorMsg );
    }

    QDomElement docElem = doc.documentElement();
    QDomNodeList docChildNodes = docElem.childNodes();

    // Re-organize the transaction document
    QDomDocument mDoc;
    QDomElement mDocElem = mDoc.createElement( QStringLiteral( "myTransactionDocument" ) );
    mDocElem.setAttribute( QStringLiteral( "xmlns" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:wfs" ), WFS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:gml" ), GML_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:qgs" ), QGS_NAMESPACE );
    mDocElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    mDoc.appendChild( mDocElem );

    QDomElement actionElem;
    QString actionName;
    QDomElement typeNameElem;
    QString typeName;

    for ( int i = docChildNodes.count(); 0 < i; --i )
    {
      actionElem = docChildNodes.at( i - 1 ).toElement();
      actionName = actionElem.localName();

      if ( actionName == QLatin1String( "Insert" ) )
      {
        QDomElement featureElem = actionElem.firstChild().toElement();
        typeName = featureElem.localName();
      }
      else if ( actionName == QLatin1String( "Update" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }
      else if ( actionName == QLatin1String( "Delete" ) )
      {
        typeName = actionElem.attribute( QStringLiteral( "typeName" ) );
      }

      if ( typeName.contains( QLatin1String( ":" ) ) )
        typeName = typeName.section( QStringLiteral( ":" ), 1, 1 );

      QDomNodeList typeNameList = mDocElem.elementsByTagName( typeName );
      if ( typeNameList.count() == 0 )
      {
        typeNameElem = mDoc.createElement( typeName );
        mDocElem.appendChild( typeNameElem );
      }
      else
        typeNameElem = typeNameList.at( 0 ).toElement();

      typeNameElem.appendChild( actionElem );
    }

    // It's time to make the transaction
    // Create the response document
    QDomDocument resp;
    //wfs:WFS_TransactionRespone element
    QDomElement respElem = resp.createElement( QStringLiteral( "WFS_TransactionResponse" )/*wfs:WFS_TransactionResponse*/ );
    respElem.setAttribute( QStringLiteral( "xmlns" ), WFS_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "xmlns:xsi" ), QStringLiteral( "http://www.w3.org/2001/XMLSchema-instance" ) );
    respElem.setAttribute( QStringLiteral( "xsi:schemaLocation" ), WFS_NAMESPACE + " http://schemas.opengis.net/wfs/1.0.0/wfs.xsd" );
    respElem.setAttribute( QStringLiteral( "xmlns:ogc" ), OGC_NAMESPACE );
    respElem.setAttribute( QStringLiteral( "version" ), QStringLiteral( "1.0.0" ) );
    resp.appendChild( respElem );

    // Store the created feature id for WFS
    QStringList insertResults;
    // Get the WFS layers id
    QStringList wfsLayersId = configParser->wfsLayers();;

    QList<QgsMapLayer*> layerList;
    QgsMapLayer* currentLayer = nullptr;

    // Loop through the layer transaction elements
    docChildNodes = mDocElem.childNodes();
    for ( int i = 0; i < docChildNodes.count(); ++i )
    {
      // Get the vector layer
      typeNameElem = docChildNodes.at( i ).toElement();
      typeName = typeNameElem.tagName();

      layerList = configParser->mapLayerFromTypeName( typeName );
      // Could be empty!
      if ( layerList.count() > 0 )
      {
        currentLayer = layerList.at( 0 );
      }
      else
      {
        throw QgsRequestNotWellFormedException( QStringLiteral( "Wrong TypeName: %1" ).arg( typeName ) );
      }

      QgsVectorLayer* layer = qobject_cast<QgsVectorLayer*>( currentLayer );
      // it's a vectorlayer and defined by the administrator as a WFS layer
      if ( layer && wfsLayersId.contains( layer->id() ) )
      {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        if ( actionName == QLatin1String( "Insert" ) )
        {
          if ( !accessControl->layerInsertPermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature insert permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Update" ) )
        {
          if ( !accessControl->layerUpdatePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature update permission denied" ) );
          }
        }
        else if ( actionName == QLatin1String( "Delete" ) )
        {
          if ( !accessControl->layerDeletePermission( layer ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature delete permission denied" ) );
          }
        }
#endif

        // Get the provider and it's capabilities
        QgsVectorDataProvider* provider = layer->dataProvider();
        if ( !provider )
        {
          continue;
        }

        int cap = provider->capabilities();

        // Start the update transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::ChangeAttributeValues ) && ( cap & QgsVectorDataProvider::ChangeGeometries ) )
        {
          // Loop through the update elements for this layer
          QDomNodeList upNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Update" ) );
          for ( int j = 0; j < upNodeList.count(); ++j )
          {
            if ( !configParser->wfstUpdateLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS updates on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Update" ), errorMsg );
              return resp;
            }

            actionElem = upNodeList.at( j ).toElement();

            // Get the Feature Ids for this filter on the layer
            QDomElement filterElem = actionElem.elementsByTagName( QStringLiteral( "Filter" ) ).at( 0 ).toElement();
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

            // Loop through the property elements
            // Store properties and the geometry element
            QDomNodeList propertyNodeList = actionElem.elementsByTagName( QStringLiteral( "Property" ) );
            QMap<QString, QString> propertyMap;
            QDomElement propertyElem;
            QDomElement nameElem;
            QDomElement valueElem;
            QDomElement geometryElem;

            for ( int l = 0; l < propertyNodeList.count(); ++l )
            {
              propertyElem = propertyNodeList.at( l ).toElement();
              nameElem = propertyElem.elementsByTagName( QStringLiteral( "Name" ) ).at( 0 ).toElement();
              valueElem = propertyElem.elementsByTagName( QStringLiteral( "Value" ) ).at( 0 ).toElement();
              if ( nameElem.text() != QLatin1String( "geometry" ) )
              {
                propertyMap.insert( nameElem.text(), valueElem.text() );
              }
              else
              {
                geometryElem = valueElem;
              }
            }

            // Update the features
            QgsFields fields = provider->fields();
            QMap<QString, int> fieldMap = provider->fieldNameMap();
            QMap<QString, int>::const_iterator fieldMapIt;
            QString fieldName;
            bool conversionSuccess;

            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
#ifdef HAVE_SERVER_PYTHON_PLUGINS
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif

              QMap< QString, QString >::const_iterator it = propertyMap.constBegin();
              for ( ; it != propertyMap.constEnd(); ++it )
              {
                fieldName = it.key();
                fieldMapIt = fieldMap.find( fieldName );
                if ( fieldMapIt == fieldMap.constEnd() )
                {
                  continue;
                }
                QgsField field = fields.at( fieldMapIt.value() );
                if ( field.type() == 2 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toInt( &conversionSuccess ) );
                else if ( field.type() == 6 )
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value().toDouble( &conversionSuccess ) );
                else
                  layer->changeAttributeValue( *fidIt, fieldMapIt.value(), it.value() );
              }

              if ( !geometryElem.isNull() )
              {
                QgsGeometry g = QgsOgcUtils::geometryFromGML( geometryElem );
                if ( !layer->changeGeometry( *fidIt, g ) )
                {
                  throw QgsRequestNotWellFormedException( QStringLiteral( "Error in change geometry" ) );
                }
              }

#ifdef HAVE_SERVER_PYTHON_PLUGINS
              fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  layer->rollBack();
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
#endif
            }
          }
        }
        // Commit the changes of the update elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Update" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }
        // Start the delete transaction
        layer->startEditing();
        if (( cap & QgsVectorDataProvider::DeleteFeatures ) )
        {
          // Loop through the delete elements
          QDomNodeList delNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Delete" ) );
          for ( int j = 0; j < delNodeList.count(); ++j )
          {
            if ( !configParser->wfstDeleteLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS deletes on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Delete" ), errorMsg );
              return resp;
            }

            actionElem = delNodeList.at( j ).toElement();
            QDomElement filterElem = actionElem.firstChild().toElement();
            // Get Feature Ids for the Filter element
            QgsFeatureIds fids = getFeatureIdsFromFilter( filterElem, layer );

#ifdef HAVE_SERVER_PYTHON_PLUGINS
            QgsFeatureIds::const_iterator fidIt = fids.constBegin();
            for ( ; fidIt != fids.constEnd(); ++fidIt )
            {
              QgsFeatureIterator fit = layer->getFeatures( QgsFeatureRequest( *fidIt ) );
              QgsFeature feature;
              while ( fit.nextFeature( feature ) )
              {
                if ( !accessControl->allowToEdit( layer, feature ) )
                {
                  throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
                }
              }
            }
#endif

            layer->selectByIds( fids );
            layer->deleteSelectedFeatures();
          }
        }
        // Commit the changes of the delete elements
        if ( !layer->commitChanges() )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "PARTIAL" ), QStringLiteral( "Delete" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          return resp;
        }

        // Store the inserted features
        QgsFeatureList inFeatList;
        if ( cap & QgsVectorDataProvider::AddFeatures )
        {
          // Get Layer Field Information
          QgsFields fields = provider->fields();
          QMap<QString, int> fieldMap = provider->fieldNameMap();
          QMap<QString, int>::const_iterator fieldMapIt;

          // Loop through the insert elements
          QDomNodeList inNodeList = typeNameElem.elementsByTagNameNS( WFS_NAMESPACE, QStringLiteral( "Insert" ) );
          for ( int j = 0; j < inNodeList.count(); ++j )
          {
            if ( !configParser->wfstInsertLayers().contains( layer->id() ) )
            {
              //no wfs permissions to do updates
              QString errorMsg = "No permissions to do WFS inserts on layer '" + layer->name() + "'";
              QgsMessageLog::logMessage( errorMsg, QStringLiteral( "Server" ), QgsMessageLog::CRITICAL );
              addTransactionResult( resp, respElem, QStringLiteral( "FAILED" ), QStringLiteral( "Insert" ), errorMsg );
              return resp;
            }

            actionElem = inNodeList.at( j ).toElement();
            // Loop through the feature element
            QDomNodeList featNodes = actionElem.childNodes();
            for ( int l = 0; l < featNodes.count(); l++ )
            {
              // Add the feature to the layer
              // and store it to put it's Feature Id in the response
              inFeatList << QgsFeature( fields );

              // Create feature for this layer
              QDomElement featureElem = featNodes.at( l ).toElement();

              QDomNode currentAttributeChild = featureElem.firstChild();

              while ( !currentAttributeChild.isNull() )
              {
                QDomElement currentAttributeElement = currentAttributeChild.toElement();
                QString attrName = currentAttributeElement.localName();

                if ( attrName != QLatin1String( "boundedBy" ) )
                {
                  if ( attrName != QLatin1String( "geometry" ) ) //a normal attribute
                  {
                    fieldMapIt = fieldMap.find( attrName );
                    if ( fieldMapIt == fieldMap.constEnd() )
                    {
                      continue;
                    }
                    QgsField field = fields.at( fieldMapIt.value() );
                    QString attrValue = currentAttributeElement.text();
                    int attrType = field.type();
                    QgsMessageLog::logMessage( QStringLiteral( "attr: name=%1 idx=%2 value=%3" ).arg( attrName ).arg( fieldMapIt.value() ).arg( attrValue ) );
                    if ( attrType == QVariant::Int )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toInt() );
                    else if ( attrType == QVariant::Double )
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue.toDouble() );
                    else
                      inFeatList.last().setAttribute( fieldMapIt.value(), attrValue );
                  }
                  else //a geometry attribute
                  {
                    QgsGeometry g = QgsOgcUtils::geometryFromGML( currentAttributeElement );
                    inFeatList.last().setGeometry( g );
                  }
                }
                currentAttributeChild = currentAttributeChild.nextSibling();
              }
            }
          }
        }
#ifdef HAVE_SERVER_PYTHON_PLUGINS
        QgsFeatureList::iterator featureIt = inFeatList.begin();
        while ( featureIt != inFeatList.end() )
        {
          if ( !accessControl->allowToEdit( layer, *featureIt ) )
          {
            throw QgsSecurityAccessException( QStringLiteral( "Feature modify permission denied" ) );
          }
          featureIt++;
        }
#endif

        // add the features
        if ( !provider->addFeatures( inFeatList ) )
        {
          addTransactionResult( resp, respElem, QStringLiteral( "Partial" ), QStringLiteral( "Insert" ), layer->commitErrors().join( QStringLiteral( "\n  " ) ) );
          if ( provider->hasErrors() )
          {
            provider->clearErrors();
          }
          return resp;
        }
        // Get the Feature Ids of the inserted feature
        for ( int j = 0; j < inFeatList.size(); j++ )
        {
          insertResults << typeName + "." + QString::number( inFeatList[j].id() );
        }
      }
    }

    // Put the Feature Ids of the inserted feature
    if ( !insertResults.isEmpty() )
    {
      Q_FOREACH ( const QString &fidStr, insertResults )
      {
        QDomElement irElem = doc.createElement( QStringLiteral( "InsertResult" ) );
        QDomElement fiElem = doc.createElement( QStringLiteral( "ogc:FeatureId" ) );
        fiElem.setAttribute( QStringLiteral( "fid" ), fidStr );
        irElem.appendChild( fiElem );
        respElem.appendChild( irElem );
      }
QgsFeatureRendererV2* QgsSingleSymbolRendererV2::createFromSld( QDomElement& element, QGis::GeometryType geomType )
{
  // XXX this renderer can handle only one Rule!

  // get the first Rule element
  QDomElement ruleElem = element.firstChildElement( "Rule" );
  if ( ruleElem.isNull() )
  {
    QgsDebugMsg( "no Rule elements found!" );
    return NULL;
  }

  QString label, description;
  QgsSymbolLayerV2List layers;

  // retrieve the Rule element child nodes
  QDomElement childElem = ruleElem.firstChildElement();
  while ( !childElem.isNull() )
  {
    if ( childElem.localName() == "Name" )
    {
      label = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName() == "Description" || childElem.localName() == "Abstract" )
    {
      description = childElem.firstChild().nodeValue();
    }
    else if ( childElem.localName().endsWith( "Symbolizer" ) )
    {
      // create symbol layers for this symbolizer
      QgsSymbolLayerV2Utils::createSymbolLayerV2ListFromSld( childElem, geomType, layers );
    }

    childElem = childElem.nextSiblingElement();
  }

  // now create the symbol
  QgsSymbolV2 *symbol = 0;
  if ( layers.size() > 0 )
  {
    switch ( geomType )
    {
      case QGis::Line:
        symbol = new QgsLineSymbolV2( layers );
        break;

      case QGis::Polygon:
        symbol = new QgsFillSymbolV2( layers );
        break;

      case QGis::Point:
        symbol = new QgsMarkerSymbolV2( layers );
        break;

      default:
        QgsDebugMsg( QString( "invalid geometry type: found %1" ).arg( geomType ) );
        return NULL;
    }
  }

  // and finally return the new renderer
  return new QgsSingleSymbolRendererV2( symbol );
}
Ejemplo n.º 25
0
int QgsSLDConfigParser::layersAndStyles( QStringList& layers, QStringList& styles ) const
{
  QgsDebugMsg( "Entering." );
  layers.clear();
  styles.clear();

  if ( mXMLDoc )
  {
    QDomElement sldElem = mXMLDoc->documentElement();
    if ( !sldElem.isNull() )
    {
      //go through all the children and search for <NamedLayers> and <UserLayers>
      QDomNodeList layerNodes = sldElem.childNodes();
      for ( int i = 0; i < layerNodes.size(); ++i )
      {
        QDomElement currentLayerElement = layerNodes.item( i ).toElement();
        if ( currentLayerElement.localName() == QLatin1String( "NamedLayer" ) )
        {
          QgsDebugMsg( "Found a NamedLayer" );
          //layer name
          QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) );
          if ( nameList.length() < 1 )
          {
            continue; //a layer name is mandatory
          }
          QString layerName = nameList.item( 0 ).toElement().text();

          //find the Named Styles and the corresponding names
          QDomNodeList namedStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "NamedStyle" ) );
          for ( int j = 0; j < namedStyleList.size(); ++j )
          {
            QDomNodeList styleNameList = namedStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) );
            if ( styleNameList.size() < 1 )
            {
              continue; //a layer name is mandatory
            }
            QString styleName = styleNameList.item( 0 ).toElement().text();
            QgsDebugMsg( "styleName is: " + styleName );
            layers.push_back( layerName );
            styles.push_back( styleName );
          }

          //named layers can also have User Styles
          QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) );
          for ( int j = 0; j < userStyleList.size(); ++j )
          {
            QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) );
            if ( styleNameList.size() < 1 )
            {
              continue; //a layer name is mandatory
            }
            QString styleName = styleNameList.item( 0 ).toElement().text();
            QgsDebugMsg( "styleName is: " + styleName );
            layers.push_back( layerName );
            styles.push_back( styleName );
          }
        }
        else if ( currentLayerElement.localName() == QLatin1String( "UserLayer" ) )
        {
          QgsDebugMsg( "Found a UserLayer" );
          //layer name
          QDomNodeList nameList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) );
          if ( nameList.length() < 1 )
          {
            QgsDebugMsg( "Namelist size is <1" );
            continue; //a layer name is mandatory
          }
          QString layerName = nameList.item( 0 ).toElement().text();
          QgsDebugMsg( "layerName is: " + layerName );
          //find the User Styles and the corresponding names
          QDomNodeList userStyleList = currentLayerElement.elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "UserStyle" ) );
          for ( int j = 0; j < userStyleList.size(); ++j )
          {
            QDomNodeList styleNameList = userStyleList.item( j ).toElement().elementsByTagName/*NS*/( /*mSLDNamespace,*/ QStringLiteral( "Name" ) );
            if ( styleNameList.size() < 1 )
            {
              QgsDebugMsg( "Namelist size is <1" );
              continue;
            }

            QString styleName = styleNameList.item( 0 ).toElement().text();
            QgsDebugMsg( "styleName is: " + styleName );
            layers.push_back( layerName );
            styles.push_back( styleName );
          }
        }
      }
    }
  }
  else
  {
    return 1;
  }
  return 0;
}
Ejemplo n.º 26
0
void QgsSOAPRequestHandler::parseInput()
{
  QString inputString = readPostBody();

  //QgsDebugMsg("input string is: " + inputString)

  //inputString to QDomDocument
  QDomDocument inputXML;
  QString errorMsg;
  if ( !inputXML.setContent( inputString, true, &errorMsg ) )
  {
    QgsDebugMsg( "soap request parse error" );
    QgsDebugMsg( "error message: " + errorMsg );
    QgsDebugMsg( "the xml string was:" );
    QgsDebugMsg( inputString );
    throw QgsMapServiceException( "InvalidXML", "XML error: " + errorMsg );
  }

  // if xml reading was successfull, save the inputXML in a file
  QFile soapFile;
  QTextStream soapStream;

  //go through soap envelope->soap body, search for either GetCapabilities or GetMap
  QDomNodeList envelopeNodeList = inputXML.elementsByTagNameNS( "http://schemas.xmlsoap.org/soap/envelope/", "Envelope" );
  if ( envelopeNodeList.size() < 1 )
  {
    QgsDebugMsg( "Envelope element not found" );
    throw QgsMapServiceException( "SOAPError", "Element <Envelope> not found" );
  }

  QDomNodeList bodyNodeList = envelopeNodeList.item( 0 ).toElement().elementsByTagNameNS( "http://schemas.xmlsoap.org/soap/envelope/", "Body" );
  if ( bodyNodeList.size() < 1 )
  {
    QgsDebugMsg( "body node not found" );
    throw QgsMapServiceException( "SOAPError", "Element <Body> not found" );
  }
  QDomElement bodyElement = bodyNodeList.item( 0 ).toElement();
  QDomElement firstChildElement = bodyElement.firstChild().toElement();

  QString serviceString = firstChildElement.attribute( "service" );
  if ( serviceString == "MS" )
  {
    QgsDebugMsg( "service = MS " );
    mParameterMap.insert( "SERVICE", "MS" );
    mService = "MS";
  }
  else if ( serviceString == "WMS" )
  {
    mParameterMap.insert( "SERVICE", "WMS" );
    mService = "WMS";
  }
  else if ( serviceString == "MDS" )
  {
    mParameterMap.insert( "SERVICE", "MDS" );
    mService = "MDS";
  }
  else if ( serviceString == "MAS" )
  {
    mParameterMap.insert( "SERVICE", "MAS" );
    mService = "MAS";
  }
  else
  {
    mParameterMap.insert( "SERVICE", "DISCOVERY" );
    mService = "DISCOVERY";
  }


  //GetCapabilities request
  //if(firstChildElement.localName().compare("getCapabilities", Qt::CaseInsensitive) == 0)
  if ( firstChildElement.localName() == "GetCapabilities" || firstChildElement.localName() == "getCapabilities" )
  {
    mParameterMap.insert( "REQUEST", "GetCapabilities" );
  }
  //GetMap request
  //else if(firstChildElement.tagName().compare("getMap",Qt::CaseInsensitive) == 0)
  else if ( firstChildElement.localName() == "GetMap" || firstChildElement.localName() == "getMap" )
  {
    mParameterMap.insert( "REQUEST", "GetMap" );
    parseGetMapElement( mParameterMap, firstChildElement );
  }
  //GetDiagram request
  //else if(firstChildElement.tagName().compare("getDiagram", Qt::CaseInsensitive) == 0)
  else if ( firstChildElement.localName() == "GetDiagram" )
  {
    mParameterMap.insert( "REQUEST", "GetDiagram" );
    parseGetMapElement( mParameterMap, firstChildElement ); //reuse the method for GetMap
  }
  //GetFeatureInfo request
  else if ( firstChildElement.localName() == "GetFeatureInfo" )
  {
    mParameterMap.insert( "REQUEST", "GetFeatureInfo" );
    parseGetFeatureInfoElement( mParameterMap, firstChildElement );
  }

  //set mFormat
  QString formatString = mParameterMap.value( "FORMAT" );
  if ( !formatString.isEmpty() )
  {
    //remove the image/ in front of the format
    if ( formatString == "image/jpeg" || formatString == "JPG" || formatString == "jpg" )
    {
      formatString = "JPG";
    }
    else if ( formatString == "image/png" || formatString == "PNG" || formatString == "png" )
    {
      formatString = "PNG";
    }
    else if ( formatString == "image/gif" || formatString == "GIF" || formatString == "gif" )
    {
      formatString = "GIF";
    }
    else
    {
      throw QgsMapServiceException( "InvalidFormat", "Invalid format " + formatString + ", only jpg and png are supported" );
    }

    mFormat = formatString;
  }
}
Ejemplo n.º 27
0
void
XSPFLoader::gotBody()
{
    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() )
    {
        if ( n.namespaceURI() == m_NS && n.localName() == "title" )
        {
            origTitle = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
        {
            m_creator = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "info" )
        {
            m_info = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "trackList" )
        {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );
    if ( !m_overrideTitle.isEmpty() )
        m_title = m_overrideTitle;

    bool shownError = false;
    for ( unsigned int i = 0; i < tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation, url;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() )
        {
            if ( n.namespaceURI() == m_NS && n.localName() == "duration" )
            {
                duration = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "annotation" )
            {
                annotation = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
            {
                artist = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "album" )
            {
                album = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "title" )
            {
                track = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "url" )
            {
                url = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "location" )
            {
                url = n.text();
            }
        }

        if ( artist.isEmpty() || track.isEmpty() )
        {
            if ( !shownError )
            {
                emit error( InvalidTrackError );
                shownError = true;
            }
            continue;
        }

        query_ptr q = Tomahawk::Query::get( artist, track, album, uuid(), false );
        if ( q.isNull() )
            continue;

        q->setDuration( duration.toInt() / 1000 );
        if ( !url.isEmpty() )
        {
            q->setResultHint( url );
            q->setSaveHTTPResultHint( true );
        }

        m_entries << q;
    }

    if ( m_autoResolve )
    {
        for ( int i = m_entries.size() - 1; i >= 0; i-- )
            Pipeline::instance()->resolve( m_entries[ i ] );
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        emit error( ParseError );
        if ( m_autoCreate )
            deleteLater();
        return;
    }

    if ( m_autoCreate )
    {
        m_playlist = Playlist::create( SourceList::instance()->getLocal(),
                                       uuid(),
                                       m_title,
                                       m_info,
                                       m_creator,
                                       false,
                                       m_entries );

        // 10 minute default---for now, no way to change it
        new Tomahawk::XspfUpdater( m_playlist, 600000, m_autoUpdate, m_url.toString() );
        emit ok( m_playlist );
    }
    else
    {

        if( !m_entries.isEmpty() )
            emit tracks( m_entries );
    }

    if ( m_autoDelete )
        deleteLater();
}
Ejemplo n.º 28
0
bool CoreProtocol::normalStep(const QDomElement &e)
{
	if(step == Start) {
		if(isIncoming()) {
			need = NSASLMechs;
			step = SendFeatures;
			return false;
		}
		else {
			if(old) {
				if(doAuth)
					step = HandleAuthGet;
				else
					return loginComplete();
			}
			else
				step = GetFeatures;

			return processStep();
		}
	}
	else if(step == HandleFeatures) {
		// deal with TLS?
		if(doTLS && !tls_started && !sasl_authed && features.tls_supported) {
			QDomElement e = doc.createElementNS(NS_TLS, "starttls");

			send(e, true);
			event = ESend;
			step = GetTLSProceed;
			return true;
		}

		// Should we go further ?
		if (!doAuth)
			return loginComplete();
		
		// Deal with compression
		if (doCompress && !compress_started && features.compress_supported && features.compression_mechs.contains("zlib")) {
			QDomElement e = doc.createElementNS(NS_COMPRESS_PROTOCOL, "compress");
			QDomElement m = doc.createElementNS(NS_COMPRESS_PROTOCOL, "method");
			m.appendChild(doc.createTextNode("zlib"));
			e.appendChild(m);
			send(e,true);
			event = ESend;
			step = GetCompressProceed;
			return true;
		}

		// deal with SASL?
		if(!sasl_authed) {
			if(!features.sasl_supported) {
				// SASL MUST be supported
				//event = EError;
				//errorCode = ErrProtocol;
				//return true;
				
				// Fall back on auth for non-compliant servers 
				step = HandleAuthGet;
				old = true;
				return true;
			}

#ifdef XMPP_TEST
			TD::msg("starting SASL authentication...");
#endif
			need = NSASLFirst;
			step = GetSASLFirst;
			return false;
		}

		if(server) {
			return loginComplete();
		}
		else {
			if(!doBinding)
				return loginComplete();
		}

		// deal with bind
		if(!features.bind_supported) {
			// bind MUST be supported
			event = EError;
			errorCode = ErrProtocol;
			return true;
		}

		QDomElement e = doc.createElement("iq");
		e.setAttribute("type", "set");
		e.setAttribute("id", "bind_1");
		QDomElement b = doc.createElementNS(NS_BIND, "bind");

		// request specific resource?
		QString resource = jid_.resource();
		if(!resource.isEmpty()) {
			QDomElement r = doc.createElement("resource");
			r.appendChild(doc.createTextNode(jid_.resource()));
			b.appendChild(r);
		}

		e.appendChild(b);

		send(e);
		event = ESend;
		step = GetBindResponse;
		return true;
	}
	else if(step == GetSASLFirst) {
		QDomElement e = doc.createElementNS(NS_SASL, "auth");
		e.setAttribute("mechanism", sasl_mech);
		if(!sasl_step.isEmpty()) {
#ifdef XMPP_TEST
			TD::msg(QString("SASL OUT: [%1]").arg(printArray(sasl_step)));
#endif
			e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(sasl_step)));
		}

		send(e, true);
		event = ESend;
		step = GetSASLChallenge;
		return true;
	}
	else if(step == GetSASLNext) {
		if(isIncoming()) {
			if(sasl_authed) {
				QDomElement e = doc.createElementNS(NS_SASL, "success");
				writeElement(e, TypeElement, false, true);
				event = ESend;
				step = IncHandleSASLSuccess;
				return true;
			}
			else {
				QByteArray stepData = sasl_step;
				QDomElement e = doc.createElementNS(NS_SASL, "challenge");
				if(!stepData.isEmpty())
					e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(stepData)));

				writeElement(e, TypeElement, false, true);
				event = ESend;
				step = GetSASLResponse;
				return true;
			}
		}
		else {
			// already authed?  then ignore last client step
			//   (this happens if "additional data with success"
			//   is used)
			if(sasl_authed)
			{
				event = ESASLSuccess;
				step = HandleSASLSuccess;
				return true;
			}

			QByteArray stepData = sasl_step;
#ifdef XMPP_TEST
			TD::msg(QString("SASL OUT: [%1]").arg(printArray(sasl_step)));
#endif
			QDomElement e = doc.createElementNS(NS_SASL, "response");
			if(!stepData.isEmpty())
				e.appendChild(doc.createTextNode(QCA::Base64().arrayToString(stepData)));

			send(e, true);
			event = ESend;
			step = GetSASLChallenge;
			return true;
		}
	}
	else if(step == HandleSASLSuccess) {
		need = NSASLLayer;
		spare = resetStream();
		step = Start;
		return false;
	}
	else if(step == HandleAuthGet) {
		QDomElement e = doc.createElement("iq");
		e.setAttribute("to", to);
		e.setAttribute("type", "get");
		e.setAttribute("id", "auth_1");
		QDomElement q = doc.createElementNS("jabber:iq:auth", "query");
		QDomElement u = doc.createElement("username");
		u.appendChild(doc.createTextNode(jid_.node()));
		q.appendChild(u);
		e.appendChild(q);

		send(e);
		event = ESend;
		step = GetAuthGetResponse;
		return true;
	}
	else if(step == HandleAuthSet) {
		QDomElement e = doc.createElement("iq");
		e.setAttribute("to", to);
		e.setAttribute("type", "set");
		e.setAttribute("id", "auth_2");
		QDomElement q = doc.createElementNS("jabber:iq:auth", "query");
		QDomElement u = doc.createElement("username");
		u.appendChild(doc.createTextNode(jid_.node()));
		q.appendChild(u);
		QDomElement p;
		if(digest) {
			// need SHA1 here
			//if(!QCA::isSupported(QCA::CAP_SHA1))
			//	QCA::insertProvider(createProviderHash());

			p = doc.createElement("digest");
			Q3CString cs = id.utf8() + password.utf8();
			p.appendChild(doc.createTextNode(QCA::Hash("sha1").hashToString(cs)));
		}
		else {
			p = doc.createElement("password");
			p.appendChild(doc.createTextNode(password));
		}
		q.appendChild(p);
		QDomElement r = doc.createElement("resource");
		r.appendChild(doc.createTextNode(jid_.resource()));
		q.appendChild(r);
		e.appendChild(q);

		send(e, true);
		event = ESend;
		step = GetAuthSetResponse;
		return true;
	}
	// server
	else if(step == SendFeatures) {
		QDomElement f = doc.createElementNS(NS_ETHERX, "stream:features");
		if(!tls_started && !sasl_authed) { // don't offer tls if we are already sasl'd
			QDomElement tls = doc.createElementNS(NS_TLS, "starttls");
			f.appendChild(tls);
		}

		if(sasl_authed) {
			if(!server) {
				QDomElement bind = doc.createElementNS(NS_BIND, "bind");
				f.appendChild(bind);
			}
		}
		else {
			QDomElement mechs = doc.createElementNS(NS_SASL, "mechanisms");
			for(QStringList::ConstIterator it = sasl_mechlist.begin(); it != sasl_mechlist.end(); ++it) {
				QDomElement m = doc.createElement("mechanism");
				m.appendChild(doc.createTextNode(*it));
				mechs.appendChild(m);
			}
			f.appendChild(mechs);
		}

		writeElement(f, TypeElement, false);
		event = ESend;
		step = GetRequest;
		return true;
	}
	// server
	else if(step == HandleTLS) {
		tls_started = true;
		need = NStartTLS;
		spare = resetStream();
		step = Start;
		return false;
	}
	// server
	else if(step == IncHandleSASLSuccess) {
		event = ESASLSuccess;
		spare = resetStream();
		step = Start;
		printf("sasl success\n");
		return true;
	}
	else if(step == GetFeatures) {
		// we are waiting for stream features
		if(e.namespaceURI() == NS_ETHERX && e.tagName() == "features") {
			// extract features
			StreamFeatures f;
			QDomElement s = e.elementsByTagNameNS(NS_TLS, "starttls").item(0).toElement();
			if(!s.isNull()) {
				f.tls_supported = true;
				f.tls_required = s.elementsByTagNameNS(NS_TLS, "required").count() > 0;
			}
			QDomElement m = e.elementsByTagNameNS(NS_SASL, "mechanisms").item(0).toElement();
			if(!m.isNull()) {
				f.sasl_supported = true;
				QDomNodeList l = m.elementsByTagNameNS(NS_SASL, "mechanism");
				for(int n = 0; n < l.count(); ++n)
					f.sasl_mechs += l.item(n).toElement().text();
			}
			QDomElement c = e.elementsByTagNameNS(NS_COMPRESS_FEATURE, "compression").item(0).toElement();
			if(!c.isNull()) {
				f.compress_supported = true;
				QDomNodeList l = c.elementsByTagNameNS(NS_COMPRESS_FEATURE, "method");
				for(int n = 0; n < l.count(); ++n)
					f.compression_mechs += l.item(n).toElement().text();
			}
			QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
			if(!b.isNull())
				f.bind_supported = true;

			if(f.tls_supported) {
#ifdef XMPP_TEST
				QString s = "STARTTLS is available";
				if(f.tls_required)
					s += " (required)";
				TD::msg(s);
#endif
			}
			if(f.sasl_supported) {
#ifdef XMPP_TEST
				QString s = "SASL mechs:";
				for(QStringList::ConstIterator it = f.sasl_mechs.begin(); it != f.sasl_mechs.end(); ++it)
					s += QString(" [%1]").arg((*it));
				TD::msg(s);
#endif
			}
			if(f.compress_supported) {
#ifdef XMPP_TEST
				QString s = "Compression mechs:";
				for(QStringList::ConstIterator it = f.compression_mechs.begin(); it != f.compression_mechs.end(); ++it)
					s += QString(" [%1]").arg((*it));
				TD::msg(s);
#endif
			}

			event = EFeatures;
			features = f;
			step = HandleFeatures;
			return true;
		}
		else {
			// ignore
		}
	}
	else if(step == GetTLSProceed) {
		// waiting for proceed to starttls
		if(e.namespaceURI() == NS_TLS) {
			if(e.tagName() == "proceed") {
#ifdef XMPP_TEST
				TD::msg("Server wants us to proceed with ssl handshake");
#endif
				tls_started = true;
				need = NStartTLS;
				spare = resetStream();
				step = Start;
				return false;
			}
			else if(e.tagName() == "failure") {
				event = EError;
				errorCode = ErrStartTLS;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetCompressProceed) {
		// waiting for proceed to compression
		if(e.namespaceURI() == NS_COMPRESS_PROTOCOL) {
			if(e.tagName() == "compressed") {
#ifdef XMPP_TEST
				TD::msg("Server wants us to proceed with compression");
#endif
				compress_started = true;
				need = NCompress;
				spare = resetStream();
				step = Start;
				return false;
			}
			else if(e.tagName() == "failure") {
				event = EError;
				errorCode = ErrCompress;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetSASLChallenge) {
		// waiting for sasl challenge/success/fail
		if(e.namespaceURI() == NS_SASL) {
			if(e.tagName() == "challenge") {
				QByteArray a = QCA::Base64().stringToArray(e.text()).toByteArray();
#ifdef XMPP_TEST
				TD::msg(QString("SASL IN: [%1]").arg(printArray(a)));
#endif
				sasl_step = a;
				need = NSASLNext;
				step = GetSASLNext;
				return false;
			}
			else if(e.tagName() == "success") {
				QString str = e.text();
				// "additional data with success" ?
				if(!str.isEmpty())
				{
					QByteArray a = QCA::Base64().stringToArray(str).toByteArray();
					sasl_step = a;
					sasl_authed = true;
					need = NSASLNext;
					step = GetSASLNext;
					return false;
				}

				sasl_authed = true;
				event = ESASLSuccess;
				step = HandleSASLSuccess;
				return true;
			}
			else if(e.tagName() == "failure") {
				QDomElement t = firstChildElement(e);
				if(t.isNull() || t.namespaceURI() != NS_SASL)
					errCond = -1;
				else
					errCond = stringToSASLCond(t.tagName());

				event = EError;
				errorCode = ErrAuth;
				return true;
			}
			else {
				event = EError;
				errorCode = ErrProtocol;
				return true;
			}
		}
	}
	else if(step == GetBindResponse) {
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			if(id == "bind_1" && (type == "result" || type == "error")) {
				if(type == "result") {
					QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
					Jid j;
					if(!b.isNull()) {
						QDomElement je = e.elementsByTagName("jid").item(0).toElement();
						j = je.text();
					}
					if(!j.isValid()) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}
					jid_ = j;
					return loginComplete();
				}
				else {
					errCond = -1;

					QDomElement err = e.elementsByTagNameNS(NS_CLIENT, "error").item(0).toElement();
					if(!err.isNull()) {
						// get error condition
						QDomNodeList nl = err.childNodes();
						QDomElement t;
						for(int n = 0; n < nl.count(); ++n) {
							QDomNode i = nl.item(n);
							if(i.isElement()) {
								t = i.toElement();
								break;
							}
						}
						if(!t.isNull() && t.namespaceURI() == NS_STANZAS) {
							QString cond = t.tagName();
							if(cond == "not-allowed")
								errCond = BindNotAllowed;
							else if(cond == "conflict")
								errCond = BindConflict;
						}
					}

					event = EError;
					errorCode = ErrBind;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetAuthGetResponse) {
		// waiting for an iq
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			Jid from(e.attribute("from"));
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			bool okfrom = (from.isEmpty() || from.compare(Jid(to)));
			if(okfrom && id == "auth_1" && (type == "result" || type == "error")) {
				if(type == "result") {
					QDomElement q = e.elementsByTagNameNS("jabber:iq:auth", "query").item(0).toElement();
					if(q.isNull() || q.elementsByTagName("username").item(0).isNull() || q.elementsByTagName("resource").item(0).isNull()) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}
					bool plain_supported = !q.elementsByTagName("password").item(0).isNull();
					bool digest_supported = !q.elementsByTagName("digest").item(0).isNull();

					if(!digest_supported && !plain_supported) {
						event = EError;
						errorCode = ErrProtocol;
						return true;
					}

					// plain text not allowed?
					if(!digest_supported && !allowPlain) {
						event = EError;
						errorCode = ErrPlain;
						return true;
					}

					digest = digest_supported;
					need = NPassword;
					step = HandleAuthSet;
					return false;
				}
				else {
					errCond = getOldErrorCode(e);

					event = EError;
					errorCode = ErrAuth;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	else if(step == GetAuthSetResponse) {
		// waiting for an iq
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			Jid from(e.attribute("from"));
			QString type(e.attribute("type"));
			QString id(e.attribute("id"));

			bool okfrom = (from.isEmpty() || from.compare(Jid(to)));
			if(okfrom && id == "auth_2" && (type == "result" || type == "error")) {
				if(type == "result") {
					return loginComplete();
				}
				else {
					errCond = getOldErrorCode(e);

					event = EError;
					errorCode = ErrAuth;
					return true;
				}
			}
			else {
				// ignore
			}
		}
		else {
			// ignore
		}
	}
	// server
	else if(step == GetRequest) {
		printf("get request: [%s], %s\n", e.namespaceURI().latin1(), e.tagName().latin1());
		if(e.namespaceURI() == NS_TLS && e.localName() == "starttls") {
			// TODO: don't let this be done twice

			QDomElement e = doc.createElementNS(NS_TLS, "proceed");
			writeElement(e, TypeElement, false, true);
			event = ESend;
			step = HandleTLS;
			return true;
		}
		if(e.namespaceURI() == NS_SASL) {
			if(e.localName() == "auth") {
				if(sasl_started) {
					// TODO
					printf("error\n");
					return false;
				}

				sasl_started = true;
				sasl_mech = e.attribute("mechanism");
				// TODO: if child text missing, don't pass it
				sasl_step = QCA::Base64().stringToArray(e.text()).toByteArray();
				need = NSASLFirst;
				step = GetSASLNext;
				return false;
			}
			else {
				// TODO
				printf("unknown sasl tag\n");
				return false;
			}
		}
		if(e.namespaceURI() == NS_CLIENT && e.tagName() == "iq") {
			QDomElement b = e.elementsByTagNameNS(NS_BIND, "bind").item(0).toElement();
			if(!b.isNull()) {
				QDomElement res = b.elementsByTagName("resource").item(0).toElement();
				QString resource = res.text();

				QDomElement r = doc.createElement("iq");
				r.setAttribute("type", "result");
				r.setAttribute("id", e.attribute("id"));
				QDomElement bind = doc.createElementNS(NS_BIND, "bind");
				QDomElement jid = doc.createElement("jid");
				Jid j = user + '@' + host + '/' + resource;
				jid.appendChild(doc.createTextNode(j.full()));
				bind.appendChild(jid);
				r.appendChild(bind);

				writeElement(r, TypeElement, false);
				event = ESend;
				// TODO
				return true;
			}
			else {
				// TODO
			}
		}
	}
	else if(step == GetSASLResponse) {
		if(e.namespaceURI() == NS_SASL && e.localName() == "response") {
			sasl_step = QCA::Base64().stringToArray(e.text()).toByteArray();
			need = NSASLNext;
			step = GetSASLNext;
			return false;
		}
	}

	if(isReady()) {
		if(!e.isNull() && isValidStanza(e)) {
			stanzaToRecv = e;
			event = EStanzaReady;
			setIncomingAsExternal();
			return true;
		}
	}

	need = NNotify;
	notify |= NRecv;
	return false;
}
Ejemplo n.º 29
0
void Programme::addSubElement( QDomElement &element) {
  if(element.localName().compare("Icon", Qt::CaseInsensitive)==0) {
    Icon *cn = Icon::fromElement(element);
    addIcon(cn);
    return;
  }
  if(element.localName().compare("Category", Qt::CaseInsensitive)==0) {
    Category *cn = Category::fromElement(element);
    addCategory(cn);
    return;
  }
  if(element.localName().compare("SubTitle", Qt::CaseInsensitive)==0) {
    SubTitle *cn = SubTitle::fromElement(element);
    addSubTitle(cn);
    return;
  }
  if(element.localName().compare("LastChance", Qt::CaseInsensitive)==0) {
    LastChance *cn = LastChance::fromElement(element);
    addLastChance(cn);
    return;
  }
  if(element.localName().compare("Audio", Qt::CaseInsensitive)==0) {
    Audio *cn = Audio::fromElement(element);
    addAudio(cn);
    return;
  }
  if(element.localName().compare("Subtitles", Qt::CaseInsensitive)==0) {
    Subtitles *cn = Subtitles::fromElement(element);
    addSubtitles(cn);
    return;
  }
  if(element.localName().compare("Date", Qt::CaseInsensitive)==0) {
    Date *cn = Date::fromElement(element);
    addDate(cn);
    return;
  }
  if(element.localName().compare("PreviouslyShown", Qt::CaseInsensitive)==0) {
    PreviouslyShown *cn = PreviouslyShown::fromElement(element);
    addPreviouslyShown(cn);
    return;
  }
  if(element.localName().compare("Country", Qt::CaseInsensitive)==0) {
    Country *cn = Country::fromElement(element);
    addCountry(cn);
    return;
  }
  if(element.localName().compare("OrigLanguage", Qt::CaseInsensitive)==0) {
    OrigLanguage *cn = OrigLanguage::fromElement(element);
    addOrigLanguage(cn);
    return;
  }
  if(element.localName().compare("StarRating", Qt::CaseInsensitive)==0) {
    StarRating *cn = StarRating::fromElement(element);
    addStarRating(cn);
    return;
  }
  if(element.localName().compare("Credits", Qt::CaseInsensitive)==0) {
    Credits *cn = Credits::fromElement(element);
    addCredits(cn);
    return;
  }
  if(element.localName().compare("Title", Qt::CaseInsensitive)==0) {
    Title *cn = Title::fromElement(element);
    addTitle(cn);
    return;
  }
  if(element.localName().compare("Video", Qt::CaseInsensitive)==0) {
    Video *cn = Video::fromElement(element);
    addVideo(cn);
    return;
  }
  if(element.localName().compare("New", Qt::CaseInsensitive)==0) {
    New *cn = New::fromElement(element);
    addNew(cn);
    return;
  }
  if(element.localName().compare("Rating", Qt::CaseInsensitive)==0) {
    Rating *cn = Rating::fromElement(element);
    addRating(cn);
    return;
  }
  if(element.localName().compare("EpisodeNum", Qt::CaseInsensitive)==0) {
    EpisodeNum *cn = EpisodeNum::fromElement(element);
    addEpisodeNum(cn);
    return;
  }
  if(element.localName().compare("Length", Qt::CaseInsensitive)==0) {
    Length *cn = Length::fromElement(element);
    addLength(cn);
    return;
  }
  if(element.localName().compare("Url", Qt::CaseInsensitive)==0) {
    Url *cn = Url::fromElement(element);
    addUrl(cn);
    return;
  }
  if(element.localName().compare("Review", Qt::CaseInsensitive)==0) {
    Review *cn = Review::fromElement(element);
    addReview(cn);
    return;
  }
  if(element.localName().compare("Language", Qt::CaseInsensitive)==0) {
    Language *cn = Language::fromElement(element);
    addLanguage(cn);
    return;
  }
  if(element.localName().compare("Premiere", Qt::CaseInsensitive)==0) {
    Premiere *cn = Premiere::fromElement(element);
    addPremiere(cn);
    return;
  }
  if(element.localName().compare("Desc", Qt::CaseInsensitive)==0) {
    Desc *cn = Desc::fromElement(element);
    addDesc(cn);
    return;
  }
}
Ejemplo n.º 30
0
void
XSPFLoader::gotBody()
{
    QDomDocument xmldoc;
    bool namespaceProcessing = true;
    xmldoc.setContent( m_body, namespaceProcessing );
    QDomElement docElement( xmldoc.documentElement() );

    QString origTitle;
    QDomNodeList tracklist;
    QDomElement n = docElement.firstChildElement();
    for ( ; !n.isNull(); n = n.nextSiblingElement() )
    {
        if ( n.namespaceURI() == m_NS && n.localName() == "title" )
        {
            origTitle = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
        {
            m_creator = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "info" )
        {
            m_info = n.text();
        }
        else if ( n.namespaceURI() == m_NS && n.localName() == "trackList" )
        {
            tracklist = n.childNodes();
        }
    }

    m_title = origTitle;
    if ( m_title.isEmpty() )
        m_title = tr( "New Playlist" );
    if ( !m_overrideTitle.isEmpty() )
        m_title = m_overrideTitle;

    bool shownError = false;
    for ( int i = 0; i < (int)tracklist.length(); i++ )
    {
        QDomNode e = tracklist.at( i );

        QString artist, album, track, duration, annotation, url;
        QDomElement n = e.firstChildElement();
        for ( ; !n.isNull(); n = n.nextSiblingElement() )
        {
            if ( n.namespaceURI() == m_NS && n.localName() == "duration" )
            {
                duration = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "annotation" )
            {
                annotation = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "creator" )
            {
                artist = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "album" )
            {
                album = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "title" )
            {
                track = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "url" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
            else if ( n.namespaceURI() == m_NS && n.localName() == "location" )
            {
                if ( !n.text().startsWith( "http" ) || TomahawkUtils::whitelistedHttpResultHint( n.text() ) )
                    url = n.text();
            }
        }

        if ( artist.isEmpty() || track.isEmpty() )
        {
            if ( !shownError )
            {
                emit error( InvalidTrackError );
                shownError = true;
            }
            continue;
        }

        track_ptr t = Tomahawk::Track::get( artist, track, album, QString(), duration.toInt() / 1000 );
        query_ptr q = Tomahawk::Query::get( t );
        if ( q.isNull() )
            continue;

        if ( !url.isEmpty() )
        {
            q->setResultHint( url );
            q->setSaveHTTPResultHint( true );
        }

        m_entries << q;
    }

    if ( m_autoResolve )
    {
        for ( int i = m_entries.size() - 1; i >= 0; i-- )
            Pipeline::instance()->resolve( m_entries[ i ] );
    }

    if ( origTitle.isEmpty() && m_entries.isEmpty() )
    {
        emit error( ParseError );
        if ( m_autoCreate )
            deleteLater();
        return;
    }

    if ( m_autoCreate )
    {
        emit ok( getPlaylistForRecentUrl() );
    }
    else
    {
        if ( !m_entries.isEmpty() )
            emit tracks( m_entries );
    }

    if ( m_autoDelete )
        deleteLater();
}