Exemplo n.º 1
0
MatrixGraph::MatrixGraph(char* path)
{
	this->vertexNumber = 0;
	this->matrix = nullptr;

	readXml(path);
}
Exemplo n.º 2
0
string Config::getValue(string attribute, int value_id)
{
    if (!readXml()) {
        return "";
    }
    if (node.nChildNode(attribute.c_str())<=value_id) return "";
    return (string) node.getChildNode(attribute.c_str(),value_id).getText();
}
Exemplo n.º 3
0
std::unique_ptr<MPL::Medium> createTestMaterial(std::string const& xml)
{
    auto const ptree = readXml(xml.c_str());
    BaseLib::ConfigTree conf(ptree, "", BaseLib::ConfigTree::onerror,
                             BaseLib::ConfigTree::onwarning);
    auto const& config = conf.getConfigSubtree("medium");

    return MPL::createMedium(config);
}
std::unique_ptr<NumLib::TimeStepAlgorithm> createTestTimeStepper(
    const char xml[])
{
    auto const ptree = readXml(xml);
    BaseLib::ConfigTree conf(ptree, "", BaseLib::ConfigTree::onerror,
                             BaseLib::ConfigTree::onwarning);
    auto const& sub_config = conf.getConfigSubtree("time_stepping");
    return NumLib::createEvolutionaryPIDcontroller(sub_config);
}
Exemplo n.º 5
0
bool Config::setValue(string attribute, string value, int value_id)
{
    if (!readXml()) return false;
    while (node.nChildNode(attribute.c_str())<=value_id) {
        node.addChild(attribute.c_str());
    }
    node.getChildNode(attribute.c_str(), value_id).deleteNodeContent();
    node.addChild(attribute.c_str());
    node.getChildNode(attribute.c_str(), value_id).addText(value.c_str());
    return writeXml();
}
Exemplo n.º 6
0
Arquivo: tester.c Projeto: zanderdk/P1
int main(int argc, char const *argv[])
{
	FILE *fp = fopen("demo2.xml", "r");
	Floor *graph = readXml(fp);
	fclose(fp);

	Vertex *t = GetVertexFromId("10013", graph);

	printf("%d \n", CountVertices(1, graph));

	return 0;
}
Exemplo n.º 7
0
dialog_delftParams::dialog_delftParams(XMLReadWrite &XmlObj, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialog_delftParams)
{
    ui->setupUi(this);

    XmlDoc = XmlObj;

    closeOk = true;
    setInitialValues();
    readXml();
}
Exemplo n.º 8
0
//--------------------------------------------------------------
void ofApp::setup(){

	printCaptureDevice();

	string dev_name;
	int screen_width, screen_height;
	readXml(dev_name , screen_width , screen_height);
	cout << "out : " << dev_name << "," << screen_width << "," << screen_height << endl;
	
	dShow.setup(dev_name, screen_width, screen_height); // put your device name and set size for your deivce as your device can.

}
Exemplo n.º 9
0
std::unique_ptr<GlobalLinearSolver>
createLinearSolver()
{
    const char xml[] =
        "<petsc><parameters>"
        "-ksp_type bcgs -pc_type sor -ksp_rtol 1e-24 -ksp_max_it 100 -ksp_initial_guess_nonzero false"
        "</parameters></petsc>";
    auto const ptree = readXml(xml);
    BaseLib::ConfigTree config(ptree, "", BaseLib::ConfigTree::onerror,
                               BaseLib::ConfigTree::onwarning);
    return std::make_unique<GlobalLinearSolver>("", &config);
}
Exemplo n.º 10
0
dialog_inputs::dialog_inputs(XMLReadWrite &XmlObj, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::dialog_inputs)
{
    ui->setupUi(this);

    XmlDoc = XmlObj;
    closeOk = true;

    readXml();

    setupPlot();
}
void TestKeePass2Format::testXmlEmptyUuids()
{

    QString xmlFile = QString("%1/%2.xml").arg(KEEPASSX_TEST_DATA_DIR, "EmptyUuids");
    QVERIFY(QFile::exists(xmlFile));
    bool hasError;
    QString errorString;
    auto db = readXml(xmlFile, true, hasError, errorString);
    if (hasError) {
        qWarning("Reader error: %s", qPrintable(errorString));
    }
    QVERIFY(!hasError);
}
Exemplo n.º 12
0
QgsLayerTreeNode *QgsLayerTreeNode::readXml( QDomElement &element, const QgsProject *project )
{
  QgsReadWriteContext context;
  QgsPathResolver resolver;
  if ( project )
    resolver = project->pathResolver();
  context.setPathResolver( resolver );
  context.setProjectTranslator( const_cast<QgsProject *>( project ) );

  QgsLayerTreeNode *node = readXml( element, context );
  if ( node )
    node->resolveReferences( project );
  return node;
}
Exemplo n.º 13
0
/*
bool TextHelper::modifyTextStr(QString filePath, QString oriStr, QString newStr)
{
    QFile file(filePath);
    if(file.open(QIODevice::ReadWrite))
    {

        QTextStream stream(&file);
        oriText = stream.readAll();
        newText = oriText.replace(oriStr, newStr);
    }
    else
    {
        qDebug() << "modifyTextStr: " << " open file fail";
        return false;
    }
    return true;
}
*/
QString TextHelper::readTextStr(QString filePath, QString objStr, QString typeFlag)
{
    QString resultStr = "";
    QFile file(filePath);
    if(file.open(QIODevice::ReadOnly))
    {
        QTextStream stream(&file);
        QString objLine;
        while(!stream.atEnd())
        {
            objLine = stream.readLine();
            if(objLine.contains(objStr))
            {
                if(typeFlag == "xml")
                {
                    resultStr = readXml(objLine);
                    break;
                }else if(typeFlag == "boardCfg")
                {
                    if(objStr == "BAND_FEID")
                    {
                        if(objLine.at(0) == '#')
                            continue;
                    }
                    QStringList strlist = objLine.split(":=");
                    resultStr = strlist[1];
                    break;
                }else if(typeFlag == "kernelCfg")
                {
                    file.close();
                    return "IPS";
                }else if(typeFlag == "flash")
                {
                    objLine = stream.readLine();
                    objLine = stream.readLine();
                    objLine = stream.readLine();
                    objLine = stream.readLine();
                    objLine = stream.readLine();
                    objLine = stream.readLine();
                }
                QStringList strlist = objLine.split("=");
                resultStr = strlist[1];
                break;
            }
        }
    }
    file.close();
    return resultStr.trimmed();
}
Exemplo n.º 14
0
void podcast::xmlParse()    {
    //time variable for added column in db


    if(xml.size() > 0)  {
        QString xmlString(xml);
        QXmlStreamReader readXml(xmlString);
        QString title, fileName;
        QUrl url;
        QDateTime currentDateTime = QDateTime::currentDateTime();
        QDateTime datePublished;
        QString datePublishedStr;
        QString datePublishedMonthM;
        episode *tempEpisode;

        while(readXml.atEnd() == false && readXml.hasError() == false)  {
            readXml.readNext();

            if(readXml.isStartElement() == true)    {
                if(readXml.name() == "title")   {
                    title = readXml.readElementText();
                }
                else if(readXml.name() == "pubDate")    {
                    //fixes months
                    datePublishedStr = readXml.readElementText();
                    datePublishedMonthM = FixMonth(datePublishedStr.mid(8, 3));
                    datePublishedStr = datePublishedStr.mid(5, 20);
                    datePublishedStr = datePublishedStr.mid(0,2) + " " + datePublishedMonthM + " " + datePublishedStr.mid(7,13);
                    datePublished = QDateTime::fromString(datePublishedStr, "dd M yyyy hh:mm:ss");
                }
                else if(readXml.name() == "enclosure") {
                    QXmlStreamAttributes attrib = readXml.attributes();
                    QString urlStr = attrib.value("url").toString();
                    url = QUrl(urlStr);
                    QFileInfo fileInfo(url.path());
                    fileName = fileInfo.fileName();
                }
            }
            else    {
                if(readXml.name() == "item")    {
                    tempEpisode = new episode(0, id, title, fileName, url, false, currentDateTime, datePublished);
                    episodes.append(tempEpisode);
                }
            }
        }
        qDebug() << episodes.size();
       podcast::xmlAddToDB();
    }
}
Exemplo n.º 15
0
void rpnoc::Profile::loadProfile( void )
{
	// selection from listview
	QString selection = model->data( listView->currentIndex(), 0 ).toString();
	if( !selection.isEmpty() ) {
		QString tempUser = getUser();
		
		// get user credentials
		QStringList toNetwork = readXml(tempUser);
	
		// send credentials tonetwork
		emit sendCreds(toNetwork);
		emit sendProfile( getUser() + "/" + selection);
		hide();
	}
}
void TestKeePass2Format::testXmlBroken()
{
    QFETCH(QString, baseName);
    QFETCH(bool, strictMode);
    QFETCH(bool, expectError);

    QString xmlFile = QString("%1/%2.xml").arg(KEEPASSX_TEST_DATA_DIR, baseName);
    QVERIFY(QFile::exists(xmlFile));
    bool hasError;
    QString errorString;
    auto db = readXml(xmlFile, strictMode, hasError, errorString);
    if (hasError) {
        qWarning("Reader error: %s", qPrintable(errorString));
    }
    QCOMPARE(hasError, expectError);
}
void TestKeePass2Format::initTestCase()
{
    QVERIFY(Crypto::init());

    // read raw XML database
    bool hasError;
    QString errorString;
    m_xmlDb = readXml(QString(KEEPASSX_TEST_DATA_DIR).append("/NewDatabase.xml"), true, hasError, errorString);
    if (hasError) {
        QFAIL(qPrintable(QString("Error while reading XML: ").append(errorString)));
    }
    QVERIFY(m_xmlDb.data());

    // construct and write KDBX to buffer
    auto key = QSharedPointer<CompositeKey>::create();
    key->addKey(QSharedPointer<PasswordKey>::create("test"));

    m_kdbxSourceDb = QSharedPointer<Database>::create();
    m_kdbxSourceDb->setKey(key);
    m_kdbxSourceDb->metadata()->setName("TESTDB");
    Group* group = m_kdbxSourceDb->rootGroup();
    group->setUuid(QUuid::createUuid());
    group->setNotes("I'm a note!");
    auto entry = new Entry();
    entry->setPassword(QString::fromUtf8("\xc3\xa4\xa3\xb6\xc3\xbc\xe9\x9b\xbb\xe7\xb4\x85"));
    entry->setUuid(QUuid::createUuid());
    entry->attributes()->set("test", "protectedTest", true);
    QVERIFY(entry->attributes()->isProtected("test"));
    entry->attachments()->set("myattach.txt", QByteArray("this is an attachment"));
    entry->attachments()->set("aaa.txt", QByteArray("also an attachment"));
    entry->setGroup(group);
    auto groupNew = new Group();
    groupNew->setUuid(QUuid::createUuid());
    groupNew->setName("TESTGROUP");
    groupNew->setNotes("I'm a sub group note!");
    groupNew->setParent(group);

    m_kdbxTargetBuffer.open(QBuffer::ReadWrite);
    writeKdbx(&m_kdbxTargetBuffer, m_kdbxSourceDb.data(), hasError, errorString);
    if (hasError) {
        QFAIL(qPrintable(QString("Error while writing database: ").append(errorString)));
    }

    // call sub class init method
    initTestCaseImpl();
}
Exemplo n.º 18
0
void StreamWindow::showText(QNetworkReply *reply)
{
    ui.statusLabel->setText(tr("Done"));
    if (reply->error() != QNetworkReply::NoError)
    {
        ui.statusLabel->setText(tr("Error"));
        QMessageBox::warning (this, tr("Error"), reply->errorString());
        m_requestReply = 0;
        reply->deleteLater();
        return;
    }
    if(m_requestReply == reply)
    {
        m_requestReply = 0;
        readXml(reply, m_iceCastModel);
    }
    reply->deleteLater();
}
Exemplo n.º 19
0
bool ConfigManager::load(const icl_core::String& filename)
{
  FilePath fp(filename.c_str());

  if (fp.extension() == ".AttributeTree" || fp.extension() == ".tree")
  {
    AttributeTree attribute_tree;
    int res = attribute_tree.load(filename.c_str());
    if (res != AttributeTree::eFILE_LOAD_ERROR)
    {
      if (res == AttributeTree::eOK)
      {
        readAttributeTree("", attribute_tree.root(), false);
      }
      return true;
    }
    else
    {
      std::cerr << "CONFIG ERROR: Could not load configuration file '" << filename << std::endl;
      return false;
    }
  }
  else
  {
    TiXmlDocument doc(filename.c_str());
    if (doc.LoadFile())
    {
      TiXmlElement *root_element = doc.RootElement();
      if (root_element != 0)
      {
        readXml("", root_element, fp, false);
      }
      return true;
    }
    else
    {
      std::cerr << "CONFIG ERROR: Could not load configuration file '" << filename << "' (" << doc.ErrorRow()
          << ", " << doc.ErrorCol() << "): " << doc.ErrorDesc() << std::endl;
      return false;
    }
  }
}
Exemplo n.º 20
0
TEST(ProcessLib_Parameter, GroupBasedParameterNode)
{
    const char xml[] =
            "<parameter>"
            "<type>Group</type>"
            "<group_id_property>PointGroupIDs</group_id_property>"
            "<index_values><index>0</index><value>0</value></index_values>"
            "<index_values><index>1</index><value>100</value></index_values>"
            "<index_values><index>3</index><value>300</value></index_values>"
            "</parameter>";
    auto const ptree = readXml(xml);

    std::unique_ptr<MeshLib::Mesh> mesh(
        MeshLib::MeshGenerator::generateLineMesh(4u, 1.0));
    std::vector<int> group_ids({0, 1, 2, 3, 4});
    MeshLib::addPropertyToMesh(*mesh, "PointGroupIDs",
                               MeshLib::MeshItemType::Node, 1, group_ids);

    BaseLib::ConfigTree conf(ptree, "", BaseLib::ConfigTree::onerror,
                             BaseLib::ConfigTree::onwarning);
    std::unique_ptr<ProcessLib::ParameterBase> parameter_base =
        ProcessLib::createGroupBasedParameter(
            "", conf.getConfigSubtree("parameter"), *mesh);

    auto parameter =
        dynamic_cast<ProcessLib::Parameter<double>*>(parameter_base.get());
    double t = 0;
    ProcessLib::SpatialPosition x;
    x.setNodeID(0);
    ASSERT_EQ(0.0, (*parameter)(t, x)[0]);
    x.setNodeID(1);
    ASSERT_EQ(100.0, (*parameter)(t, x)[0]);
    x.setNodeID(2);
    ASSERT_ANY_THROW((*parameter)(t, x));
    x.setNodeID(3);
    ASSERT_EQ(300.0, (*parameter)(t, x)[0]);
    x.setNodeID(4);
    ASSERT_ANY_THROW((*parameter)(t, x));
}
Exemplo n.º 21
0
void ConfigManager::readXml(const icl_core::String& prefix, TiXmlNode *node, FilePath fp, bool extend_prefix)
{
  icl_core::String node_name(node->Value());
  icl_core::String fq_node_name = prefix;
  if (extend_prefix)
  {
    fq_node_name = prefix + "/" + node_name;
  }

  TiXmlNode *child = node->IterateChildren(NULL);
  while (child != 0)
  {
    if (child->Type() == TiXmlNode::TINYXML_ELEMENT)
    {
      if (strcmp(child->Value(), "INCLUDE") == 0)
      {
        TiXmlElement *child_element = dynamic_cast<TiXmlElement*>(child);
        assert(child_element != NULL);
        const char *included_file = child_element->GetText();
        if (included_file != NULL)
        {
          load(fp.path() + included_file);
        }
      }
      else
      {
        readXml(fq_node_name, child, fp);
      }
    }
    else if (child->Type() == TiXmlNode::TINYXML_TEXT)
    {
      insert(fq_node_name, child->Value());
      notify(fq_node_name);
    }

    child = node->IterateChildren(child);
  }
}
void TestKeePass2Format::testXmlRepairUuidHistoryItem()
{
    QString xmlFile = QString("%1/%2.xml").arg(KEEPASSX_TEST_DATA_DIR, "BrokenDifferentEntryHistoryUuid");
    QVERIFY(QFile::exists(xmlFile));
    bool hasError;
    QString errorString;
    auto db = readXml(xmlFile, false, hasError, errorString);
    if (hasError) {
        qWarning("Database read error: %s", qPrintable(errorString));
    }
    QVERIFY(!hasError);

    QList<Entry*> entries = db->rootGroup()->entries();
    QCOMPARE(entries.size(), 1);
    Entry* entry = entries.at(0);

    QList<Entry*> historyItems = entry->historyItems();
    QCOMPARE(historyItems.size(), 1);
    Entry* historyItem = historyItems.at(0);

    QVERIFY(!entry->uuid().isNull());
    QVERIFY(!historyItem->uuid().isNull());
    QCOMPARE(historyItem->uuid(), entry->uuid());
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{

	po::options_description desc("Allowed options");
	// These operator() really screw up clang-format
	// clang-format off
	desc.add_options()
		("help", "Show help message")
		("xml,x", po::value<std::string>(),"Input XML file")
		("output-header,h", po::value<std::string>(), "Path to output generated header file")
		("output-source,o", po::value<std::string>(), "Path to output generated source file")
	;
	// clang-format on

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	std::string inputXmlPath;
	std::string outputHeaderPath;
	std::string outputSourcePath;

	if (vm.count("help"))
	{
		std::cout << desc << "\n";
		return 1;
	}
	if (!vm.count("xml"))
	{
		std::cerr << "Must specify input XML file\n" << desc << "\n";
		return 1;
	}
	if (!vm.count("output-header"))
	{
		std::cerr << "Must specify output header file\n" << desc << "\n";
		return 1;
	}
	if (!vm.count("output-source"))
	{
		std::cerr << "Must specify output source file\n" << desc << "\n";
		return 1;
	}

	inputXmlPath = vm["xml"].as<std::string>();
	outputHeaderPath = vm["output-header"].as<std::string>();
	outputSourcePath = vm["output-source"].as<std::string>();

	std::ifstream inputXmlFile(inputXmlPath);
	if (!inputXmlFile)
	{
		std::cerr << "Failed to open input XML file \"" << inputXmlPath << "\"\n";
		return 1;
	}

	std::ofstream outputSourceFile(outputSourcePath);
	if (!outputSourceFile)
	{
		std::cerr << "Failed to open output source file at \"" << outputSourcePath << "\"\n";
		return 1;
	}

	std::ofstream outputHeaderFile(outputHeaderPath);
	if (!outputHeaderFile)
	{
		std::cerr << "Failed to open output header file at \"" << outputHeaderPath << "\"\n";
		return 1;
	}

	StateDefinition state;
	if (!readXml(inputXmlFile, state))
	{
		std::cerr << "Reading input XML file \"" << inputXmlPath << "\" failed\n";
		return 1;
	}

	writeHeader(outputHeaderFile, state);
	writeSource(outputSourceFile, state);

	return 0;
}
Exemplo n.º 24
0
bool QgsMapLayer::readLayerXML( const QDomElement& layerElement )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layerElement.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layerElement.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  // TODO: this should go to providers
  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else if ( provider == "wms" )
  {
    // >>> BACKWARD COMPATIBILITY < 1.9
    // For project file backward compatibility we must support old format:
    // 1. mode: <url>
    //    example: http://example.org/wms?
    // 2. mode: tiled=<width>;<height>;<resolution>;<resolution>...,ignoreUrl=GetMap;GetFeatureInfo,featureCount=<count>,username=<name>,password=<password>,url=<url>
    //    example: tiled=256;256;0.703;0.351,url=http://example.org/tilecache?
    //    example: featureCount=10,http://example.org/wms?
    //    example: ignoreUrl=GetMap;GetFeatureInfo,username=cimrman,password=jara,url=http://example.org/wms?
    // This is modified version of old QgsWmsProvider::parseUri
    // The new format has always params crs,format,layers,styles and that params
    // should not appear in old format url -> use them to identify version
    if ( !mDataSource.contains( "crs=" ) && !mDataSource.contains( "format=" ) )
    {
      QgsDebugMsg( "Old WMS URI format detected -> converting to new format" );
      QgsDataSourceURI uri;
      if ( !mDataSource.startsWith( "http:" ) )
      {
        QStringList parts = mDataSource.split( "," );
        QStringListIterator iter( parts );
        while ( iter.hasNext() )
        {
          QString item = iter.next();
          if ( item.startsWith( "username="******"username", item.mid( 9 ) );
          }
          else if ( item.startsWith( "password="******"password", item.mid( 9 ) );
          }
          else if ( item.startsWith( "tiled=" ) )
          {
            // in < 1.9 tiled= may apper in to variants:
            // tiled=width;height - non tiled mode, specifies max width and max height
            // tiled=width;height;resolutions-1;resolution2;... - tile mode

            QStringList params = item.mid( 6 ).split( ";" );

            if ( params.size() == 2 ) // non tiled mode
            {
              uri.setParam( "maxWidth", params.takeFirst() );
              uri.setParam( "maxHeight", params.takeFirst() );
            }
            else if ( params.size() > 2 ) // tiled mode
            {
              // resolutions are no more needed and size limit is not used for tiles
              // we have to tell to the provider however that it is tiled
              uri.setParam( "tileMatrixSet", "" );
            }
          }
          else if ( item.startsWith( "featureCount=" ) )
          {
            uri.setParam( "featureCount", item.mid( 13 ) );
          }
          else if ( item.startsWith( "url=" ) )
          {
            uri.setParam( "url", item.mid( 4 ) );
          }
          else if ( item.startsWith( "ignoreUrl=" ) )
          {
            uri.setParam( "ignoreUrl", item.mid( 10 ).split( ";" ) );
          }
        }
      }
      else
      {
        uri.setParam( "url", mDataSource );
      }
      mDataSource = uri.encodedUri();
      // At this point, the URI is obviously incomplete, we add additional params
      // in QgsRasterLayer::readXml
    }
    // <<< BACKWARD COMPATIBILITY < 1.9
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layerElement.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layerElement );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layerElement.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( layerElement.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( layerElement.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( layerElement.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layerElement.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layerElement.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layerElement.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //keywordList
  QDomElement keywordListElem = layerElement.firstChildElement( "keywordList" );
  if ( !keywordListElem.isNull() )
  {
    QStringList kwdList;
    for ( QDomNode n = keywordListElem.firstChild(); !n.isNull(); n = n.nextSibling() )
    {
      kwdList << n.toElement().text();
    }
    mKeywordList = kwdList.join( ", " );
  }

  //metadataUrl
  QDomElement dataUrlElem = layerElement.firstChildElement( "dataUrl" );
  if ( !dataUrlElem.isNull() )
  {
    mDataUrl = dataUrlElem.text();
    mDataUrlFormat = dataUrlElem.attribute( "format", "" );
  }

  //attribution
  QDomElement attribElem = layerElement.firstChildElement( "attribution" );
  if ( !attribElem.isNull() )
  {
    mAttribution = attribElem.text();
    mAttributionUrl = attribElem.attribute( "href", "" );
  }

  //metadataUrl
  QDomElement metaUrlElem = layerElement.firstChildElement( "metadataUrl" );
  if ( !metaUrlElem.isNull() )
  {
    mMetadataUrl = metaUrlElem.text();
    mMetadataUrlType = metaUrlElem.attribute( "type", "" );
    mMetadataUrlFormat = metaUrlElem.attribute( "format", "" );
  }

#if 0
  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }
#endif

  readCustomProperties( layerElement );

  return true;
} // bool QgsMapLayer::readLayerXML
Exemplo n.º 25
0
bool QgsMapLayer::readXML( const QDomNode& layer_node )
{
  QgsCoordinateReferenceSystem savedCRS;
  CUSTOM_CRS_VALIDATION savedValidation;
  bool layerError;

  QDomElement element = layer_node.toElement();

  QDomNode mnl;
  QDomElement mne;

  // read provider
  QString provider;
  mnl = layer_node.namedItem( "provider" );
  mne = mnl.toElement();
  provider = mne.text();

  // set data source
  mnl = layer_node.namedItem( "datasource" );
  mne = mnl.toElement();
  mDataSource = mne.text();

  if ( provider == "spatialite" )
  {
    QgsDataSourceURI uri( mDataSource );
    uri.setDatabase( QgsProject::instance()->readPath( uri.database() ) );
    mDataSource = uri.uri();
  }
  else if ( provider == "ogr" )
  {
    QStringList theURIParts = mDataSource.split( "|" );
    theURIParts[0] = QgsProject::instance()->readPath( theURIParts[0] );
    mDataSource = theURIParts.join( "|" );
  }
  else if ( provider == "delimitedtext" )
  {
    QUrl urlSource = QUrl::fromEncoded( mDataSource.toAscii() );

    if ( !mDataSource.startsWith( "file:" ) )
    {
      QUrl file = QUrl::fromLocalFile( mDataSource.left( mDataSource.indexOf( "?" ) ) );
      urlSource.setScheme( "file" );
      urlSource.setPath( file.path() );
    }

    QUrl urlDest = QUrl::fromLocalFile( QgsProject::instance()->readPath( urlSource.toLocalFile() ) );
    urlDest.setQueryItems( urlSource.queryItems() );
    mDataSource = QString::fromAscii( urlDest.toEncoded() );
  }
  else
  {
    mDataSource = QgsProject::instance()->readPath( mDataSource );
  }

  // Set the CRS from project file, asking the user if necessary.
  // Make it the saved CRS to have WMS layer projected correctly.
  // We will still overwrite whatever GDAL etc picks up anyway
  // further down this function.
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();

  QDomNode srsNode = layer_node.namedItem( "srs" );
  mCRS->readXML( srsNode );
  mCRS->setValidationHint( tr( "Specify CRS for layer %1" ).arg( mne.text() ) );
  mCRS->validate();
  savedCRS = *mCRS;

  // Do not validate any projections in children, they will be overwritten anyway.
  // No need to ask the user for a projections when it is overwritten, is there?
  savedValidation = QgsCoordinateReferenceSystem::customSrsValidation();
  QgsCoordinateReferenceSystem::setCustomSrsValidation( NULL );

  // now let the children grab what they need from the Dom node.
  layerError = !readXml( layer_node );

  // overwrite CRS with what we read from project file before the raster/vector
  // file readnig functions changed it. They will if projections is specfied in the file.
  // FIXME: is this necessary?
  QgsCoordinateReferenceSystem::setCustomSrsValidation( savedValidation );
  *mCRS = savedCRS;

  // Abort if any error in layer, such as not found.
  if ( layerError )
  {
    return false;
  }

  // the internal name is just the data source basename
  //QFileInfo dataSourceFileInfo( mDataSource );
  //internalName = dataSourceFileInfo.baseName();

  // set ID
  mnl = layer_node.namedItem( "id" );
  if ( ! mnl.isNull() )
  {
    mne = mnl.toElement();
    if ( ! mne.isNull() && mne.text().length() > 10 ) // should be at least 17 (yyyyMMddhhmmsszzz)
    {
      mID = mne.text();
    }
  }

  // use scale dependent visibility flag
  toggleScaleBasedVisibility( element.attribute( "hasScaleBasedVisibilityFlag" ).toInt() == 1 );
  setMinimumScale( element.attribute( "minimumScale" ).toFloat() );
  setMaximumScale( element.attribute( "maximumScale" ).toFloat() );

  // set name
  mnl = layer_node.namedItem( "layername" );
  mne = mnl.toElement();
  setLayerName( mne.text() );

  //title
  QDomElement titleElem = layer_node.firstChildElement( "title" );
  if ( !titleElem.isNull() )
  {
    mTitle = titleElem.text();
  }

  //abstract
  QDomElement abstractElem = layer_node.firstChildElement( "abstract" );
  if ( !abstractElem.isNull() )
  {
    mAbstract = abstractElem.text();
  }

  //read transparency level
  QDomNode transparencyNode = layer_node.namedItem( "transparencyLevelInt" );
  if ( ! transparencyNode.isNull() )
  {
    // set transparency level only if it's in project
    // (otherwise it sets the layer transparent)
    QDomElement myElement = transparencyNode.toElement();
    setTransparency( myElement.text().toInt() );
  }

  readCustomProperties( layer_node );

  return true;
} // void QgsMapLayer::readXML
Exemplo n.º 26
0
QList< QgsLayoutItem * > QgsLayout::loadFromTemplate( const QDomDocument &document, const QgsReadWriteContext &context, bool clearExisting, bool *ok )
{
  if ( ok )
    *ok = false;

  QList< QgsLayoutItem * > result;

  if ( clearExisting )
  {
    clear();
  }

  QDomDocument doc;

  // If this is a 2.x composition template, convert it to a layout template
  if ( QgsCompositionConverter::isCompositionTemplate( document ) )
  {
    doc = QgsCompositionConverter::convertCompositionTemplate( document, mProject );
  }
  else
  {
    doc = document;
  }

  // remove all uuid attributes since we don't want duplicates UUIDS
  QDomNodeList itemsNodes = doc.elementsByTagName( QStringLiteral( "LayoutItem" ) );
  for ( int i = 0; i < itemsNodes.count(); ++i )
  {
    QDomNode itemNode = itemsNodes.at( i );
    if ( itemNode.isElement() )
    {
      itemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) );
    }
  }
  QDomNodeList multiFrameNodes = doc.elementsByTagName( QStringLiteral( "LayoutMultiFrame" ) );
  for ( int i = 0; i < multiFrameNodes.count(); ++i )
  {
    QDomNode multiFrameNode = multiFrameNodes.at( i );
    if ( multiFrameNode.isElement() )
    {
      multiFrameNode.toElement().removeAttribute( QStringLiteral( "uuid" ) );
      QDomNodeList frameNodes = multiFrameNode.toElement().elementsByTagName( QStringLiteral( "childFrame" ) );
      QDomNode itemNode = frameNodes.at( i );
      if ( itemNode.isElement() )
      {
        itemNode.toElement().removeAttribute( QStringLiteral( "uuid" ) );
      }
    }
  }

  //read general settings
  if ( clearExisting )
  {
    QDomElement layoutElem = doc.documentElement();
    if ( layoutElem.isNull() )
    {
      return result;
    }

    bool loadOk = readXml( layoutElem, doc, context );
    if ( !loadOk )
    {
      return result;
    }
    layoutItems( result );
  }
  else
  {
    result = addItemsFromXml( doc.documentElement(), doc, context );
  }

  if ( ok )
    *ok = true;

  return result;
}
void TestKeePass2Format::testXmlInvalidXmlChars()
{
    QScopedPointer<Database> dbWrite(new Database());

    QString strPlainInvalid =
        QString().append(QChar(0x02)).append(QChar(0x19)).append(QChar(0xFFFE)).append(QChar(0xFFFF));
    QString strPlainValid = QString()
                                .append(QChar(0x09))
                                .append(QChar(0x0A))
                                .append(QChar(0x20))
                                .append(QChar(0xD7FF))
                                .append(QChar(0xE000))
                                .append(QChar(0xFFFD));
    // U+10437 in UTF-16: D801 DC37
    //                    high low  surrogate
    QString strSingleHighSurrogate1 = QString().append(QChar(0xD801));
    QString strSingleHighSurrogate2 = QString().append(QChar(0x31)).append(QChar(0xD801)).append(QChar(0x32));
    QString strHighHighSurrogate = QString().append(QChar(0xD801)).append(QChar(0xD801));
    QString strSingleLowSurrogate1 = QString().append(QChar(0xDC37));
    QString strSingleLowSurrogate2 = QString().append(QChar((0x31))).append(QChar(0xDC37)).append(QChar(0x32));
    QString strLowLowSurrogate = QString().append(QChar(0xDC37)).append(QChar(0xDC37));
    QString strSurrogateValid1 = QString().append(QChar(0xD801)).append(QChar(0xDC37));
    QString strSurrogateValid2 =
        QString().append(QChar(0x31)).append(QChar(0xD801)).append(QChar(0xDC37)).append(QChar(0x32));

    auto entry = new Entry();
    entry->setUuid(QUuid::createUuid());
    entry->setGroup(dbWrite->rootGroup());
    entry->attributes()->set("PlainInvalid", strPlainInvalid);
    entry->attributes()->set("PlainValid", strPlainValid);
    entry->attributes()->set("SingleHighSurrogate1", strSingleHighSurrogate1);
    entry->attributes()->set("SingleHighSurrogate2", strSingleHighSurrogate2);
    entry->attributes()->set("HighHighSurrogate", strHighHighSurrogate);
    entry->attributes()->set("SingleLowSurrogate1", strSingleLowSurrogate1);
    entry->attributes()->set("SingleLowSurrogate2", strSingleLowSurrogate2);
    entry->attributes()->set("LowLowSurrogate", strLowLowSurrogate);
    entry->attributes()->set("SurrogateValid1", strSurrogateValid1);
    entry->attributes()->set("SurrogateValid2", strSurrogateValid2);

    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);
    bool hasError;
    QString errorString;
    writeXml(&buffer, dbWrite.data(), hasError, errorString);
    QVERIFY(!hasError);
    buffer.seek(0);

    auto dbRead = readXml(&buffer, true, hasError, errorString);
    if (hasError) {
        qWarning("Database read error: %s", qPrintable(errorString));
    }
    QVERIFY(!hasError);
    QVERIFY(dbRead.data());
    QCOMPARE(dbRead->rootGroup()->entries().size(), 1);
    Entry* entryRead = dbRead->rootGroup()->entries().at(0);
    EntryAttributes* attrRead = entryRead->attributes();

    QCOMPARE(attrRead->value("PlainInvalid"), QString());
    QCOMPARE(attrRead->value("PlainValid"), strPlainValid);
    QCOMPARE(attrRead->value("SingleHighSurrogate1"), QString());
    QCOMPARE(attrRead->value("SingleHighSurrogate2"), QString("12"));
    QCOMPARE(attrRead->value("HighHighSurrogate"), QString());
    QCOMPARE(attrRead->value("SingleLowSurrogate1"), QString());
    QCOMPARE(attrRead->value("SingleLowSurrogate2"), QString("12"));
    QCOMPARE(attrRead->value("LowLowSurrogate"), QString());
    QCOMPARE(attrRead->value("SurrogateValid1"), strSurrogateValid1);
    QCOMPARE(attrRead->value("SurrogateValid2"), strSurrogateValid2);
}
Exemplo n.º 28
0
StreamWindow::StreamWindow(QWidget *parent) : QWidget(parent)
{
    ui.setupUi(this);
    setWindowFlags(Qt::Window);
    setAttribute(Qt::WA_DeleteOnClose);
    setAttribute(Qt::WA_QuitOnClose, false);
    m_requestReply = 0;
    //buttons
    ui.addPushButton->setIcon(QIcon::fromTheme("list-add"));
    ui.updatePushButton->setIcon(QIcon::fromTheme("view-refresh"));
    //icecast model
    m_iceCastModel = new QStandardItemModel(this);
    m_iceCastModel->setHorizontalHeaderLabels(QStringList() << tr("Name")
                                       << tr("Genre")
                                       << tr("Bitrate")
                                       << tr("Format"));
    m_iceCastFilterModel = new StreamsProxyModel(this);
    m_iceCastFilterModel->setSourceModel(m_iceCastModel);
    m_iceCastFilterModel->setDynamicSortFilter(true);
    m_iceCastFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    //icecast table
    ui.icecastTableView->setModel(m_iceCastFilterModel);
    ui.icecastTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height());
    ui.icecastTableView->verticalHeader()->setResizeMode(QHeaderView::Fixed);
    ui.icecastTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui.icecastTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.icecastTableView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(execIceCastMenu(QPoint)));
    //favorites model
    m_favoritesModel = new QStandardItemModel(this);
    m_favoritesModel->setHorizontalHeaderLabels(QStringList() << tr("Name")
                                                     << tr("Genre")
                                                     << tr("Bitrate")
                                                     << tr("Format"));
    m_favoritesFilterModel = new StreamsProxyModel(this);
    m_favoritesFilterModel->setSourceModel(m_favoritesModel);
    m_favoritesFilterModel->setDynamicSortFilter(true);
    m_favoritesFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
    //favorites table
    ui.favoritesTableView->setModel(m_favoritesFilterModel);
    ui.favoritesTableView->verticalHeader()->setDefaultSectionSize(fontMetrics().height());
    ui.favoritesTableView->verticalHeader()->setResizeMode(QHeaderView::Fixed);
    ui.favoritesTableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui.favoritesTableView->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui.favoritesTableView, SIGNAL(customContextMenuRequested(QPoint)),
            SLOT(execFavoritesMenu(QPoint)));

    ui.statusLabel->hide();

    m_http = new QNetworkAccessManager(this);
     //load global proxy settings
    QmmpSettings *gs = QmmpSettings::instance();
    if (gs->isProxyEnabled())
    {
        QNetworkProxy proxy(QNetworkProxy::HttpProxy, gs->proxy().host(),  gs->proxy().port());
        if(gs->useProxyAuth())
        {
            proxy.setUser(gs->proxy().userName());
            proxy.setPassword(gs->proxy().password());
        }
        m_http->setProxy(proxy);
    }
    connect(m_http, SIGNAL(finished (QNetworkReply *)), SLOT(showText(QNetworkReply *)));
    //read settings
    QSettings settings(Qmmp::configFile(), QSettings::IniFormat);
    settings.beginGroup("StreamBrowser");
    restoreGeometry(settings.value("geometry").toByteArray());
    ui.icecastTableView->horizontalHeader()->restoreState(settings.value("icecast_headers").toByteArray());
    ui.favoritesTableView->horizontalHeader()->restoreState(settings.value("favorites_headers").toByteArray());
    ui.tabWidget->setCurrentIndex(settings.value("current_tab", 1).toInt());
    settings.endGroup();
    //create cache dir
    QDir dir(Qmmp::configDir());
    if(!dir.exists("streambrowser"))
        dir.mkdir("streambrowser");
    //read cache
    QFile file(Qmmp::configDir() + "/streambrowser/icecast.xml");
    if(file.open(QIODevice::ReadOnly))
        readXml(&file, m_iceCastModel);
    else
        on_updatePushButton_clicked();
    QFile file2(Qmmp::configDir() + "/streambrowser/favorites.xml");
    if(file2.open(QIODevice::ReadOnly))
        readXml(&file2, m_favoritesModel);
    //create menus
    m_iceCastMenu = new QMenu(this);
    m_iceCastMenu->addAction(tr("&Add to favorites"), this, SLOT(addToFavorites()));
    QAction *addAction = m_iceCastMenu->addAction(tr("&Add to playlist"), this,
                                                  SLOT(on_addPushButton_clicked()));
    m_favoritesMenu = new QMenu(this);
    m_favoritesMenu->addAction(addAction);
    m_favoritesMenu->addSeparator();
    m_favoritesMenu->addAction(tr("&Remove"), this, SLOT(removeFromFavorites()), QKeySequence::Delete);
    addActions(m_favoritesMenu->actions());
}