Esempio n. 1
0
void Configure::printTree(QDomElement element,QString indent) {
    QDomNode n = element.firstChild();
    if(n.isText()) {
        qDebug()<<element.tagName()<<":"<<n.nodeValue();
        widget.textEditConfiguration->append(indent+element.tagName()+": "+n.nodeValue());
        // save interesting information
        if(element.tagName()=="type") {
            serverType=n.nodeValue();
        } else if(element.tagName()=="samplerate") {
            sampleRate=n.nodeValue().toInt();
        } else if(element.tagName()=="minfrequency") {
            minFrequency=n.nodeValue().toLong();
        } else if(element.tagName()=="maxfrequency") {
            maxFrequency=n.nodeValue().toLong();
        }
    } else {
        qDebug()<<element.tagName();
        widget.textEditConfiguration->append(indent+element.tagName());
        while(!n.isNull()) {
            QDomElement e = n.toElement(); // try to convert the node to an element.
            if(!e.isNull()) {
                if(e.hasAttributes()) {
                    QDomNamedNodeMap attributes=e.attributes();
                    qDebug()<<"attributes:"<<attributes.count();
                    for(int i=0;i<attributes.count();i++) {
                        QDomNode a=attributes.item(i);
                        qDebug()<<"attribute: "<<a.nodeName()<<":"<<a.nodeValue();
                    }
                }
                printTree(e,indent+"    ");
            }
            n = n.nextSibling();
        }
    }
}
Esempio n. 2
0
/*!
	\overload
	\param elem Source element to scan
	\param ignoreNewIds whether unknown format identifiers should be ignored
	
	The given dom element must contain a proper version attribute and format
	data as child elements (&lt;format&gt; tags)
	
	\note Previous content is not discarded
*/
void QFormatScheme::load(const QDomElement& elem, bool ignoreNewIds)
{
	if (!elem.hasAttributes() && !elem.hasChildNodes()) return;

	if ( elem.attribute("version") < QFORMAT_VERSION )
	{
		qWarning("Format encoding version mismatch : [found]%s != [expected]%s",
				qPrintable(elem.attribute("version")),
				QFORMAT_VERSION);
		
		return;
	}
	
	QDomElement e, c;
	QDomNodeList l, f = elem.elementsByTagName("format");
	
	for ( int i = 0; i < f.count(); i++ )
	{
		e = f.at(i).toElement();
		
		if ( ignoreNewIds && !m_formatKeys.contains(e.attribute("id")) )
			continue;
		
		l = e.childNodes();
		
		QFormat fmt;
		
		for ( int i = 0; i < l.count(); i++ )
		{
			c = l.at(i).toElement();
			
			if ( c.isNull() )
				continue;
			
			QString field = c.tagName(),
					value = c.firstChild().toText().data();
			setFormatOption(fmt,field,value);
		}
		fmt.setPriority(fmt.priority); //update priority if other values changed

		setFormat(e.attribute("id"), fmt);
	}
}
PythonVariable* PythonDBGPVariableParser::parseVar(QDomNode& node, Variable* parent)
{
    /*
    <?xml version="1.0" encoding="utf-8"?>
    	<response xmlns="urn:debugger_protocol_v1" command="context_get" context="0" transaction_id="4">
    		<property  type="int" children="0" size="0">
    			<value><![CDATA[0]]></value>
    			<name encoding="base64"><![CDATA[REJHUEhpZGVDaGlsZHJlbg==]]></name>
    			<fullname encoding="base64"><![CDATA[REJHUEhpZGVDaGlsZHJlbg==]]></fullname>
    		</property>
    		<property  type="module" children="0" size="0">
    			<value><![CDATA[<module 'sys' (built-in)>]]></value>
    			<name encoding="base64"><![CDATA[c3lz]]></name>
    			<fullname encoding="base64"><![CDATA[c3lz]]></fullname>
    		</property>
    		<property  pagesize="300" numchildren="3" children="1" type="tuple" page="0" size="3">
    			<name encoding="base64"><![CDATA[dA==]]></name>
    			<fullname encoding="base64"><![CDATA[dA==]]></fullname>
    		</property>
    		<property  type="str" children="0" size="3">
    			<value encoding="base64"><![CDATA[b2xh]]></value>
    			<name encoding="base64"><![CDATA[dGVzdGU=]]></name>
    			<fullname encoding="base64"><![CDATA[dGVzdGU=]]>
    		</fullname>
    	</property>
    </response>
    */
    QDomElement e = node.toElement();

    PythonVariable* var = new PythonVariable(parent);

    int effectiveChildren = e.attributeNode("numchildren").value().toInt();

    QString type = e.attributeNode("type").value();
//   int size = e.attributeNode("size").value().toInt();


    QDomNodeList list = e.childNodes();
//   int broughtChildren = list.count();


    QString name;
    QString tmp, tvalue;
    for(uint i = 0; i < list.count(); i++)
    {
        e = list.item(i).toElement();

        tmp = e.text();
        if(e.hasAttributes() && (e.attributeNode("encoding").value() == QString("base64")))
        {
            tmp = KCodecs::base64Decode(tmp.utf8());
        }

        if(e.tagName() == "fullname")
        {
            name = tmp;
        }
        else if(e.tagName() == "value")
        {
            tvalue = tmp;
        }
    }

    var->setName(name);

    if(effectiveChildren == 0) //scalar
    {
        PythonScalarValue* value = new PythonScalarValue(var);
        value->setTypeName(type);
        var->setValue(value);
        value->set(tvalue);
    }
    else
    {
        PythonListValue* value = new PythonListValue(var, type);
        value->setScalar(false);
        var->setValue(value);
//     value->setList(parseList(e.childNodes(), var));
    }

    /*
      if(type == "array")
      {
        PerlArrayValue* arrayValue = new PerlArrayValue(var, effectiveChildren);
        var->setValue(arrayValue);
        arrayValue->setScalar(false);

        if((effectiveChildren == 0) || (broughtChildren != 0))
        {
          arrayValue->setList(parseList(e.childNodes(), var));
        }*/

//   if(type == "hash")
//   {
//     PythonHashValue* hashValue = new PythonHashValue(var, effectiveChildren);
//     var->setValue(hashValue);
//     hashValue->setScalar(false);
//
//     if((effectiveChildren == 0) || (broughtChildren != 0))
//     {
//       hashValue->setList(parseList(e.childNodes(), var));
//     }
//   }
//   else if(type == "array")
//   {
//     PythonArrayValue* arrayValue = new PythonArrayValue(var, effectiveChildren);
//     var->setValue(arrayValue);
//     arrayValue->setScalar(false);
//
//     if((effectiveChildren == 0) || (broughtChildren != 0))
//     {
//       arrayValue->setList(parseList(e.childNodes(), var));
//     }
//   }
//   else if(type == "scalar")
//   {
//   }
//   else //Object
//   {
//     PythonScalarValue* value = new PythonScalarValue(var);
//     value->setType(PythonScalarValue::Object);
//     value->setClassName(type);
//     var->setValue(value);
//   }

    return var;
}
Esempio n. 4
0
void QgsWfsCapabilities::capabilitiesReplyFinished()
{
  const QByteArray& buffer = mResponse;

  QgsDebugMsg( "parsing capabilities: " + buffer );

  // parse XML
  QString capabilitiesDocError;
  QDomDocument capabilitiesDocument;
  if ( !capabilitiesDocument.setContent( buffer, true, &capabilitiesDocError ) )
  {
    mErrorCode = QgsWfsRequest::XmlError;
    mErrorMessage = capabilitiesDocError;
    emit gotCapabilities();
    return;
  }

  QDomElement doc = capabilitiesDocument.documentElement();

  // handle exceptions
  if ( doc.tagName() == "ExceptionReport" )
  {
    QDomNode ex = doc.firstChild();
    QString exc = ex.toElement().attribute( "exceptionCode", "Exception" );
    QDomElement ext = ex.firstChild().toElement();
    mErrorCode = QgsWfsRequest::ServerExceptionError;
    mErrorMessage = exc + ": " + ext.firstChild().nodeValue();
    emit gotCapabilities();
    return;
  }

  mCaps.clear();

  //test wfs version
  mCaps.version = doc.attribute( "version" );
  if ( !mCaps.version.startsWith( "1.0" ) &&
       !mCaps.version.startsWith( "1.1" ) &&
       !mCaps.version.startsWith( "2.0" ) )
  {
    mErrorCode = WFSVersionNotSupported;
    mErrorMessage = tr( "WFS version %1 not supported" ).arg( mCaps.version );
    emit gotCapabilities();
    return;
  }

  // WFS 2.0 implementation are supposed to implement resultType=hits, and some
  // implementations (GeoServer) might advertize it, whereas others (MapServer) do not.
  // WFS 1.1 implementation too I think, but in the examples of the GetCapabilites
  // response of the WFS 1.1 standard (and in common implementations), this is
  // explictly advertized
  if ( mCaps.version.startsWith( "2.0" ) )
    mCaps.supportsHits = true;

  // Note: for conveniency, we do not use the elementsByTagNameNS() method as
  // the WFS and OWS namespaces URI are not the same in all versions

  // find <ows:OperationsMetadata>
  QDomElement operationsMetadataElem = doc.firstChildElement( "OperationsMetadata" );
  if ( !operationsMetadataElem.isNull() )
  {
    QDomNodeList contraintList = operationsMetadataElem.elementsByTagName( "Constraint" );
    for ( int i = 0; i < contraintList.size(); ++i )
    {
      QDomElement contraint = contraintList.at( i ).toElement();
      if ( contraint.attribute( "name" ) == "DefaultMaxFeatures" /* WFS 1.1 */ )
      {
        QDomElement value = contraint.firstChildElement( "Value" );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( "name" ) == "CountDefault" /* WFS 2.0 (e.g. MapServer) */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() )
        {
          mCaps.maxFeatures = value.text().toInt();
          QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
        }
      }
      else if ( contraint.attribute( "name" ) == "ImplementsResultPaging" /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() && value.text() == "TRUE" )
        {
          mCaps.supportsPaging = true;
          QgsDebugMsg( "Supports paging" );
        }
      }
      else if ( contraint.attribute( "name" ) == "ImplementsStandardJoins" ||
                contraint.attribute( "name" ) == "ImplementsSpatialJoins" /* WFS 2.0 */ )
      {
        QDomElement value = contraint.firstChildElement( "DefaultValue" );
        if ( !value.isNull() && value.text() == "TRUE" )
        {
          mCaps.supportsJoins = true;
          QgsDebugMsg( "Supports joins" );
        }
      }
    }

    // In WFS 2.0, max features can also be set in Operation.GetFeature (e.g. GeoServer)
    // and we are also interested by resultType=hits for WFS 1.1
    QDomNodeList operationList = operationsMetadataElem.elementsByTagName( "Operation" );
    for ( int i = 0; i < operationList.size(); ++i )
    {
      QDomElement operation = operationList.at( i ).toElement();
      if ( operation.attribute( "name" ) == "GetFeature" )
      {
        QDomNodeList operationContraintList = operation.elementsByTagName( "Constraint" );
        for ( int j = 0; j < operationContraintList.size(); ++j )
        {
          QDomElement contraint = operationContraintList.at( j ).toElement();
          if ( contraint.attribute( "name" ) == "CountDefault" )
          {
            QDomElement value = contraint.firstChildElement( "DefaultValue" );
            if ( !value.isNull() )
            {
              mCaps.maxFeatures = value.text().toInt();
              QgsDebugMsg( QString( "maxFeatures: %1" ).arg( mCaps.maxFeatures ) );
            }
            break;
          }
        }

        QDomNodeList parameterList = operation.elementsByTagName( "Parameter" );
        for ( int j = 0; j < parameterList.size(); ++j )
        {
          QDomElement parameter = parameterList.at( j ).toElement();
          if ( parameter.attribute( "name" ) == "resultType" )
          {
            QDomNodeList valueList = parameter.elementsByTagName( "Value" );
            for ( int k = 0; k < valueList.size(); ++k )
            {
              QDomElement value = valueList.at( k ).toElement();
              if ( value.text() == "hits" )
              {
                mCaps.supportsHits = true;
                QgsDebugMsg( "Support hits" );
                break;
              }
            }
          }
        }

        break;
      }
    }
  }

  //go to <FeatureTypeList>
  QDomElement featureTypeListElem = doc.firstChildElement( "FeatureTypeList" );
  if ( featureTypeListElem.isNull() )
  {
    emit gotCapabilities();
    return;
  }

  // Parse operations supported for all feature types
  bool insertCap, updateCap, deleteCap;
  parseSupportedOperations( featureTypeListElem.firstChildElement( "Operations" ),
                            insertCap,
                            updateCap,
                            deleteCap );

  // get the <FeatureType> elements
  QDomNodeList featureTypeList = featureTypeListElem.elementsByTagName( "FeatureType" );
  for ( int i = 0; i < featureTypeList.size(); ++i )
  {
    FeatureType featureType;
    QDomElement featureTypeElem = featureTypeList.at( i ).toElement();

    //Name
    QDomNodeList nameList = featureTypeElem.elementsByTagName( "Name" );
    if ( nameList.length() > 0 )
    {
      featureType.name = nameList.at( 0 ).toElement().text();
    }
    //Title
    QDomNodeList titleList = featureTypeElem.elementsByTagName( "Title" );
    if ( titleList.length() > 0 )
    {
      featureType.title = titleList.at( 0 ).toElement().text();
    }
    //Abstract
    QDomNodeList abstractList = featureTypeElem.elementsByTagName( "Abstract" );
    if ( abstractList.length() > 0 )
    {
      featureType.abstract = abstractList.at( 0 ).toElement().text();
    }

    //DefaultSRS is always the first entry in the feature srs list
    QDomNodeList defaultCRSList = featureTypeElem.elementsByTagName( "DefaultSRS" );
    if ( defaultCRSList.length() == 0 )
      // In WFS 2.0, this is spelled DefaultCRS...
      defaultCRSList = featureTypeElem.elementsByTagName( "DefaultCRS" );
    if ( defaultCRSList.length() > 0 )
    {
      QString srsname( defaultCRSList.at( 0 ).toElement().text() );
      // Some servers like Geomedia advertize EPSG:XXXX even in WFS 1.1 or 2.0
      if ( srsname.startsWith( "EPSG:" ) )
        mCaps.useEPSGColumnFormat = true;
      featureType.crslist.append( NormalizeSRSName( srsname ) );
    }

    //OtherSRS
    QDomNodeList otherCRSList = featureTypeElem.elementsByTagName( "OtherSRS" );
    if ( otherCRSList.length() == 0 )
      // In WFS 2.0, this is spelled OtherCRS...
      otherCRSList = featureTypeElem.elementsByTagName( "OtherCRS" );
    for ( int i = 0; i < otherCRSList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( otherCRSList.at( i ).toElement().text() ) );
    }

    //Support <SRS> for compatibility with older versions
    QDomNodeList srsList = featureTypeElem.elementsByTagName( "SRS" );
    for ( int i = 0; i < srsList.size(); ++i )
    {
      featureType.crslist.append( NormalizeSRSName( srsList.at( i ).toElement().text() ) );
    }

    // Get BBox WFS 1.0 way
    QDomElement latLongBB = featureTypeElem.firstChildElement( "LatLongBoundingBox" );
    if ( latLongBB.hasAttributes() )
    {
      // Despite the name LatLongBoundingBox, the coordinates are supposed to
      // be expressed in <SRS>. From the WFS schema;
      // <!-- The LatLongBoundingBox element is used to indicate the edges of
      // an enclosing rectangle in the SRS of the associated feature type.
      featureType.bbox = QgsRectangle(
                           latLongBB.attribute( "minx" ).toDouble(),
                           latLongBB.attribute( "miny" ).toDouble(),
                           latLongBB.attribute( "maxx" ).toDouble(),
                           latLongBB.attribute( "maxy" ).toDouble() );
      featureType.bboxSRSIsWGS84 = false;

      // But some servers do not honour this and systematically reproject to WGS84
      // such as GeoServer. See http://osgeo-org.1560.x6.nabble.com/WFS-LatLongBoundingBox-td3813810.html
      // This is also true of TinyOWS
      if ( !featureType.crslist.isEmpty() &&
           featureType.bbox.xMinimum() >= -180 && featureType.bbox.yMinimum() >= -90 &&
           featureType.bbox.xMaximum() <= 180 && featureType.bbox.yMaximum() < 90 )
      {
        QgsCoordinateReferenceSystem crs = QgsCoordinateReferenceSystem::fromOgcWmsCrs( featureType.crslist[0] );
        if ( !crs.isGeographic() )
        {
          // If the CRS is projected then check that projecting the corner of the bbox, assumed to be in WGS84,
          // into the CRS, and then back to WGS84, works (check that we are in the validity area)
          QgsCoordinateReferenceSystem crsWGS84 = QgsCoordinateReferenceSystem::fromOgcWmsCrs( "CRS:84" );
          QgsCoordinateTransform ct( crsWGS84, crs );

          QgsPoint ptMin( featureType.bbox.xMinimum(), featureType.bbox.yMinimum() );
          QgsPoint ptMinBack( ct.transform( ct.transform( ptMin, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );
          QgsPoint ptMax( featureType.bbox.xMaximum(), featureType.bbox.yMaximum() );
          QgsPoint ptMaxBack( ct.transform( ct.transform( ptMax, QgsCoordinateTransform::ForwardTransform ), QgsCoordinateTransform::ReverseTransform ) );

          QgsDebugMsg( featureType.bbox.toString() );
          QgsDebugMsg( ptMinBack.toString() );
          QgsDebugMsg( ptMaxBack.toString() );

          if ( fabs( featureType.bbox.xMinimum() - ptMinBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMinimum() - ptMinBack.y() ) < 1e-5 &&
               fabs( featureType.bbox.xMaximum() - ptMaxBack.x() ) < 1e-5 &&
               fabs( featureType.bbox.yMaximum() - ptMaxBack.y() ) < 1e-5 )
          {
            QgsDebugMsg( "Values of LatLongBoundingBox are consistent with WGS84 long/lat bounds, so as the CRS is projected, assume they are indeed in WGS84 and not in the CRS units" );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }
    else
    {
      // WFS 1.1 way
      QDomElement WGS84BoundingBox = featureTypeElem.firstChildElement( "WGS84BoundingBox" );
      if ( !WGS84BoundingBox.isNull() )
      {
        QDomElement lowerCorner = WGS84BoundingBox.firstChildElement( "LowerCorner" );
        QDomElement upperCorner = WGS84BoundingBox.firstChildElement( "UpperCorner" );
        if ( !lowerCorner.isNull() && !upperCorner.isNull() )
        {
          QStringList lowerCornerList = lowerCorner.text().split( " ", QString::SkipEmptyParts );
          QStringList upperCornerList = upperCorner.text().split( " ", QString::SkipEmptyParts );
          if ( lowerCornerList.size() == 2 && upperCornerList.size() == 2 )
          {
            featureType.bbox = QgsRectangle(
                                 lowerCornerList[0].toDouble(),
                                 lowerCornerList[1].toDouble(),
                                 upperCornerList[0].toDouble(),
                                 upperCornerList[1].toDouble() );
            featureType.bboxSRSIsWGS84 = true;
          }
        }
      }
    }

    // Parse Operations specific to the type name
    parseSupportedOperations( featureTypeElem.firstChildElement( "Operations" ),
                              featureType.insertCap,
                              featureType.updateCap,
                              featureType.deleteCap );
    featureType.insertCap |= insertCap;
    featureType.updateCap |= updateCap;
    featureType.deleteCap |= deleteCap;

    mCaps.featureTypes.push_back( featureType );
  }

  Q_FOREACH ( const FeatureType& f, mCaps.featureTypes )
  {
    mCaps.setAllTypenames.insert( f.name );
    QString unprefixed( QgsWFSUtils::removeNamespacePrefix( f.name ) );
    if ( !mCaps.setAmbiguousUnprefixedTypename.contains( unprefixed ) )
    {
      if ( mCaps.mapUnprefixedTypenameToPrefixedTypename.contains( unprefixed ) )
      {
        mCaps.setAmbiguousUnprefixedTypename.insert( unprefixed );
        mCaps.mapUnprefixedTypenameToPrefixedTypename.remove( unprefixed );
      }
      else
      {
        mCaps.mapUnprefixedTypenameToPrefixedTypename[unprefixed] = f.name;
      }
    }
  }

  //go to <Filter_Capabilities>
  QDomElement filterCapabilitiesElem = doc.firstChildElement( "Filter_Capabilities" );
  if ( !filterCapabilitiesElem.isNull() )
    parseFilterCapabilities( filterCapabilitiesElem );

  // Hard-coded functions
  Function f_ST_GeometryFromText( "ST_GeometryFromText", 1, 2 );
  f_ST_GeometryFromText.returnType = "gml:AbstractGeometryType";
  f_ST_GeometryFromText.argumentList << Argument( "wkt", "xs:string" );
  f_ST_GeometryFromText.argumentList << Argument( "srsname", "xs:string" );
  mCaps.functionList << f_ST_GeometryFromText;

  Function f_ST_GeomFromGML( "ST_GeomFromGML", 1 );
  f_ST_GeomFromGML.returnType = "gml:AbstractGeometryType";
  f_ST_GeomFromGML.argumentList << Argument( "gml", "xs:string" );
  mCaps.functionList << f_ST_GeomFromGML;

  Function f_ST_MakeEnvelope( "ST_MakeEnvelope", 4, 5 );
  f_ST_MakeEnvelope.returnType = "gml:AbstractGeometryType";
  f_ST_MakeEnvelope.argumentList << Argument( "minx", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "miny", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "maxx", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "maxy", "xs:double" );
  f_ST_MakeEnvelope.argumentList << Argument( "srsname", "xs:string" );
  mCaps.functionList << f_ST_MakeEnvelope;

  emit gotCapabilities();
}
Esempio n. 5
0
void cleanDomElement(QDomElement &pDomElement,
                     QMap<QString, QString> &pElementsAttributes)
{
    // Serialise all the element's attributes and sort their serialised version
    // before removing them from the element and adding a new attribute that
    // will later on be used for string replacement

    static qulonglong attributeNumber = 0;
    static const int ULLONG_WIDTH = ceil(log(ULLONG_MAX));

    if (pDomElement.hasAttributes()) {
        QStringList serialisedAttributes = QStringList();
        QDomNamedNodeMap domElementAttributes = pDomElement.attributes();
        QDomAttr attributeNode;

        while (domElementAttributes.count()) {
            // Serialise (ourselves) the element's attribute
            // Note: to rely on QDomNode::save() to do the serialisation isn't
            //       good enough. Indeed, if it is going to be fine for an
            //       attribute that doesn't have a prefix, e.g.
            //           name="my_name"
            //       it may not be fine for an attribute with a prefix, e.g.
            //           cmeta:id="my_cmeta_id"
            //       since depending on how that attribute has been created
            //       (i.e. using QDomDocument::createAttribute() or
            //       QDomDocument::createAttributeNS()), then it may or not have
            //       a namespace associated with it. If it does, then its
            //       serialisation will look something like
            //           cmeta:id="my_cmeta_id" xmlns:cmeta="http://www.cellml.org/metadata/1.0#"
            //       which is clearly not what we want since that's effectively
            //       two attributes in one. So, we need to separate them, which
            //       is what we do here, after making sure that the namespace
            //       for the attribute is not already defined for the given DOM
            //       element...

            attributeNode = domElementAttributes.item(0).toAttr();

            if (attributeNode.namespaceURI().isEmpty()) {
                serialisedAttributes << attributeNode.name()+"=\""+attributeNode.value()+"\"";
            } else {
                serialisedAttributes << attributeNode.prefix()+":"+attributeNode.name()+"=\""+attributeNode.value()+"\"";

                if (   attributeNode.prefix().compare(pDomElement.prefix())
                    && attributeNode.namespaceURI().compare(pDomElement.namespaceURI())) {
                    serialisedAttributes << "xmlns:"+attributeNode.prefix()+"=\""+attributeNode.namespaceURI()+"\"";
                }
            }

            // Remove the attribute node from the element

            pDomElement.removeAttributeNode(attributeNode);
        }

        // Sort the serialised attributes, using the attributes' name, and
        // remove duplicates, if any

        std::sort(serialisedAttributes.begin(), serialisedAttributes.end(), sortSerialisedAttributes);

        serialisedAttributes.removeDuplicates();

        // Keep track of the serialisation of the element's attribute

        QString elementAttributes = QString("Element%1Attributes").arg(++attributeNumber, ULLONG_WIDTH, 10, QChar('0'));

        pElementsAttributes.insert(elementAttributes, serialisedAttributes.join(" "));

        // Add a new attribute to the element
        // Note: this attribute, once serialised by QDomDocument::save(), will
        //       be used to do a string replacement (see
        //       qDomDocumentToString())...

        domElementAttributes.setNamedItem(pDomElement.ownerDocument().createAttribute(elementAttributes));
    }

    // Recursively clean ourselves

    for (QDomElement childElement = pDomElement.firstChildElement();
         !childElement.isNull(); childElement = childElement.nextSiblingElement()) {
        cleanDomElement(childElement, pElementsAttributes);
    }
}
Esempio n. 6
0
//---------------------------------------------------------------------------
bool ProjectSession::saveToFile( const QString & sessionFileName, const QValueList< KDevPlugin * > plugins )
{
  QString section, keyword;
  QDomElement session = domdoc.documentElement();

  int nDocs = 0;
  QString docIdStr;

////  // read the information about the mainframe widget
////  QDomElement mainframeEl = session.namedItem("Mainframe").toElement();
////  if(mainframeEl.isNull()){
////    mainframeEl=domdoc.createElement("Mainframe");
////    session.appendChild( mainframeEl);
////  }
////  bool bMaxMode = ((QextMdiMainFrm*)m_pDocViewMan->parent())->isInMaximizedChildFrmMode();
////  mainframeEl.setAttribute("MaximizeMode", bMaxMode);


  // read the information about the documents
  QDomElement docsAndViewsEl = session.namedItem("DocsAndViews").toElement();
  if (docsAndViewsEl.isNull()) {
    docsAndViewsEl = domdoc.createElement("DocsAndViews");
    session.appendChild( docsAndViewsEl);
  }
  else {
    // we need to remove the old ones before memorizing the current ones (to avoid merging)
    QDomNode n = docsAndViewsEl.firstChild();
    while ( !n.isNull() ) {
      QDomNode toBeRemoved = n;
      n = n.nextSibling();
      docsAndViewsEl.removeChild(toBeRemoved);
    }
  }

	QPtrListIterator<KParts::Part> it( *PartController::getInstance()->parts() );
	for ( ; it.current(); ++it )
	{

		KParts::ReadOnlyPart* pReadOnlyPart = dynamic_cast<KParts::ReadOnlyPart*>(it.current());
		if (!pReadOnlyPart)
			continue;

		QString url = pReadOnlyPart->url().url();

		docIdStr.setNum(nDocs);
		QDomElement docEl = domdoc.createElement("Doc" + docIdStr);
		docEl.setAttribute( "URL", url);
		docsAndViewsEl.appendChild( docEl);
		nDocs++;
		docEl.setAttribute( "NumberOfViews", 1);

		QDomElement viewEl = domdoc.createElement( "View0");
		docEl.appendChild( viewEl);

		if ( dynamic_cast<HTMLDocumentationPart*>(pReadOnlyPart) )
		{
			viewEl.setAttribute("Type", "Documentation");
		}
		else if ( pReadOnlyPart->inherits("KTextEditor::Document") )
		{
			viewEl.setAttribute("Type", "Source");
			KTextEditor::ViewCursorInterface *iface = dynamic_cast<KTextEditor::ViewCursorInterface*>(pReadOnlyPart->widget());
			if (iface) {
				unsigned int line, col;
				iface->cursorPosition(&line, &col);
				viewEl.setAttribute( "line", line );
			}
			if ( KTextEditor::EncodingInterface * ei = dynamic_cast<KTextEditor::EncodingInterface*>( pReadOnlyPart ) )
			{
				QString encoding = ei->encoding();
				if ( !encoding.isNull() )
				{
					viewEl.setAttribute( "Encoding", encoding );
				}
			}
		}
		else
		{
			viewEl.setAttribute("Type", "Other");
		}
	}

/*
  QPtrListIterator<KParts::Part> it( *PartController::getInstance()->parts() );
  for ( ; it.current(); ++it ) {
////    QString partName = it.current()->name();
////    QMessageBox::information(0L,"",partName);

    KParts::ReadOnlyPart* pReadOnlyPart = dynamic_cast<KParts::ReadOnlyPart*>(it.current());
    if (!pReadOnlyPart)
      continue; // note: read-write parts are also a read-only part, they inherit from it

    HTMLDocumentationPart* pDocuPart = dynamic_cast<HTMLDocumentationPart*>(pReadOnlyPart);

    /// @todo Save relative path for project sharing?
    QString url = pReadOnlyPart->url().url();

    docIdStr.setNum(nDocs);
    QDomElement docEl = domdoc.createElement("Doc" + docIdStr);
    docEl.setAttribute( "URL", url);
    docsAndViewsEl.appendChild( docEl);
    nDocs++;
////    docEl.setAttribute( "Type", "???");
////    // get the view list
////    QPtrList<KWpEditorPartriteView> viewList = pDoc->viewList();
////    // write the number of views
////    docEl.setAttribute( "NumberOfViews", viewList.count());
    docEl.setAttribute( "NumberOfViews", 1);
    // loop over all views of this document
    int nView = 0;
////    KWriteView* pView = 0L;
    QString viewIdStr;
////    for (viewList.first(), nView = 0; viewList.current() != 0; viewList.next(), nView++) {
////      pView = viewList.current();
////      if (pView != 0L) {
        viewIdStr.setNum( nView);
        QDomElement viewEl = domdoc.createElement( "View"+viewIdStr);
        docEl.appendChild( viewEl);
        // focus?
////        viewEl.setAttribute("Focus", (((CEditWidget*)pView->parentWidget()) == m_pDocViewMan->currentEditView()));
        viewEl.setAttribute("Type", "???");

    QDomElement viewPropertiesEl = domdoc.createElement("AdditionalSettings");
    viewEl.appendChild(viewPropertiesEl);
    emit sig_saveAdditionalViewProperties(url, &viewPropertiesEl);

    if (pReadOnlyPart->inherits("KTextEditor::Document")) {
      KTextEditor::ViewCursorInterface *iface = dynamic_cast<KTextEditor::ViewCursorInterface*>(pReadOnlyPart->widget());
      if (iface) {
        unsigned int line, col;
        iface->cursorPosition(&line, &col);
        viewEl.setAttribute( "line", line );
      }
    }

    if (pDocuPart) {
      docEl.setAttribute( "context", pDocuPart->context() );
    }
  }
*/
  docsAndViewsEl.setAttribute("NumberOfDocuments", nDocs);


  // now also let the project-related plugins save their session stuff
  // read the information about the documents
  QDomElement pluginListEl = session.namedItem("pluginList").toElement();
  if (pluginListEl.isNull()) {
    pluginListEl = domdoc.createElement("pluginList");
    session.appendChild( pluginListEl);
  }
  else {
    // we need to remove the old ones before memorizing the current ones (to avoid merging)
    QDomNode n = pluginListEl.firstChild();
    while ( !n.isNull() ) {
      QDomNode toBeRemoved = n;
      n = n.nextSibling();
      pluginListEl.removeChild(toBeRemoved);
    }
  }

	QValueList<KDevPlugin*>::ConstIterator itt = plugins.begin();
	while( itt != plugins.end() )
	{
		KDevPlugin* pPlugin = (*itt);
		QString pluginName = pPlugin->instance()->instanceName();
		QDomElement pluginEl = domdoc.createElement(pluginName);

		// now plugin, save what you have!
		pPlugin->savePartialProjectSession(&pluginEl);

		// if the plugin wrote anything, accept itt for the session, otherwise forget itt
		if (pluginEl.hasChildNodes() || pluginEl.hasAttributes())
		{
			pluginListEl.appendChild(pluginEl);
		}
		++itt;
	}

  // Write it out to the session file on disc
  QFile f(sessionFileName);
  if ( f.open(IO_WriteOnly) ) {    // file opened successfully
    QTextStream t( &f );        // use a text stream
    t << domdoc.toCString();
    f.close();
  }
  initXMLTree();  // clear and initialize the tree again

  return true;
}
Esempio n. 7
0
//Encargado de generar un nuevo archivo de registros a partir de un archivo XML
void MainWindow::on_importXML_triggered()
{
    //Se obtiene la direccion del archivo xml
    QString file = QFileDialog::getOpenFileName(this,"Importar archivo XML","","XML (*.xml)");

    //verifica que la direccion este bien
    if(!file.isEmpty()){

        //si esta abierto un archivo de registros entonces lo cierra y muestra al usuario
        //a que escoga el lugar de destino del nuevo archivo que se escribe

        //verifica que los archivos este cerrados
        if(this->fileRecord.isOpen()){
            this->fileRecord.close();
        }
        if(this->indicesFile.isOpen()){
            this->indicesFile.close();
        }

        //Limpia el vector de campos del archivo
        while(this->fileRecord.fieldsSize() != 0){
            this->fileRecord.removeField(0);
        }

        //toma la direccion del nuevo archivo de registros
        QString directory = QFileDialog::getExistingDirectory(this,"New File","");
        if(!directory.isEmpty()){
            bool val;
            //Pregunta el nombre del archivo destino
            QString fileName = QInputDialog::getText(this,"Nombre del Archivo","Escriba el nombre del archivo que desea crear",QLineEdit::Normal,"",&val);
            if(val && !fileName.isEmpty()){
                QString Path = directory + "/" + fileName + ".jjdb";
                //escribe algo, luego lo cierra y vuelve a abrir
                if(!this->fileRecord.open(Path.toStdString())){
                    this->fileRecord.open(Path.toStdString(),ios_base::out);
                    this->fileRecord.write("$$",2);
                    this->fileRecord.flush();
                    this->fileRecord.close();

                    QString indicesPath = directory + "/" + fileName + "-indices.jjdb";
                    this->indicesFile.open(indicesPath.toStdString().c_str(),ios_base::out);
                    this->indicesFile.write("$$",2);
                    this->indicesFile.flush();
                    this->indicesFile.close();

                    this->indicesFile.open(indicesPath.toStdString().c_str(),ios_base::in | ios_base::out);

                    if(this->fileRecord.open(Path.toStdString(),ios_base::in | ios_base::out)){

                        //se hace del uso de un QDomDocument que permite la lectura del xml
                        QDomDocument document;

                        //uso de un qfile
                        QFile qfile(file);

                        //verifica que archivo este abierto solamente en modo de lectura
                        if(!qfile.open(QIODevice::ReadOnly)){
                            QMessageBox::critical(this,"Error","Hubo un error en la lectura del archivo XML");
                            return;
                        }

                        //le asigna el contenido del archivo al documento que permite la lectura
                        if(!document.setContent(&qfile)){
                            QMessageBox::critical(this,"Error","Hubo un error de lectura del archivo XML");
                            return;
                        }

                        //Esta lectura se basa especificamente en tomar los elementos y crear registros
                        //a partir de ellos
                        QDomElement db = document.documentElement();

                        QDomNode fr = db.firstChild().firstChild();

                        QDomElement elem = fr.toElement();

                        //verifica que los elementos no sean nulos
                        while(!elem.isNull()){
                                QString name = elem.tagName();

                                if(!elem.hasAttributes()){
                                    QMessageBox::critical(this,"Error","El archivo XML contiene una mala estructura");
                                    return;
                                }

                                QDomNamedNodeMap map = elem.attributes();

                                char type;
                                int length;
                                int decimalPlaces = 0;
                                int key = 0;

                                if(map.size() < 3){
                                    QMessageBox::critical(this,"Error","El archivo XML contiene una mala estructura");
                                    return;
                                }

                                //toma de los elementos xml y los convierte a las caracteristicas de un registro
                                for(int i = 0; i < map.size(); i++){
                                    if(!map.item(i).isNull()){
                                        QDomNode node = map.item(i);
                                        QDomAttr attr = node.toAttr();

                                        if(attr.name() == "key"){
                                            if(attr.value() == "true"){
                                                key = 1;
                                            }
                                        }else if(attr.name() == "type"){
                                            if(attr.value() == "integer"){
                                                type = 'E';
                                            }else if(attr.value() == "real"){
                                                type = 'R';
                                            }else{
                                                type = 'C';
                                            }
                                        }else if(attr.name() == "length"){
                                            length = attr.value().toInt();
                                        }else if(attr.name() == "decimalPlaces"){
                                            decimalPlaces = attr.value().toInt();
                                        }else{
                                            QMessageBox::critical(this,"Error","El archivo XML tiene una mala estructura");
                                            return;
                                        }
                                    }else{
                                        QMessageBox::critical(this,"Error","Mala estructura del archivo XML");
                                        return;
                                    }
                                }

                                //creacion de un nuevo registro
                                Field* newField = new Field(name.toStdString(),type,key,length,decimalPlaces);
                                this->fileRecord.addField(newField);
                                elem = elem.nextSibling().toElement();
                        }

                        //cambia el tamanio de los registros del archivo
                        int rl = 0;
                        vector<Field*> fields = this->fileRecord.getFields();
                        for(int i = 0; i < fields.size(); i++){
                            rl += fields.at(i)->getLength();
                        }
                        this->fileRecord.setRecordLength(rl);

                        //limpia el mapa de indices primarios
                        this->fileRecord.cleanMap();

                        //se encarga de hacer el header del archivo y guardar los campos
                        string header = this->fileRecord.toStringHeader();
                        this->fileRecord.write(header.c_str(),header.size());
                        this->fileRecord.flush();

                        QDomElement start_data = db.firstChild().toElement();

                        //se encarga especificamente de tomar los datos del xml
                        //y los convierte en los registros
                        while(!start_data.isNull()){
                            vector<string> record;

                            QDomElement e = start_data.firstChild().toElement();
                            while(!e.isNull()){
                                record.push_back(e.text().trimmed().toStdString());
                                e = e.nextSibling().toElement();
                            }

                            //creacion de un nuevo registro
                            Record* r  = new Record(this->fileRecord.getFields(),record);
                            this->fileRecord.addRecord(r);


                            start_data = start_data.nextSibling().toElement();
                        }

                        //ahora se encarga de hacer los indices y de guardarlos en el archivo de indices
                        vector<PrimaryIndex*> indexes = this->fileRecord.getIndexes();

                        stringstream ss;
                        for(int i = 0; i < indexes.size(); i++){
                            ss<<indexes.at(i)->toString();
                            if(i != indexes.size() -1){
                                ss<<'/';
                            }
                        }
                        this->indicesFile.seekp(0,ios_base::beg);
                        this->indicesFile.write(ss.str().c_str(),ss.str().length());
                        this->indicesFile.flush();

                        //solamente cierra el archivo xml
                        qfile.close();

                        QMessageBox::information(this,"Satisfactorio","Se ha creado el archivo de registros correctamente");

                    }else{
                        QMessageBox::critical(this,"Error","Hubo un error inesperado al momento de abrir el archivo creado");
                    }
                }else{
                    QMessageBox::critical(this,"Error","Hubo un error al momento de abrir el archivo para su inicializacion");
                }
            }
        }

    }
}