Ejemplo n.º 1
0
QSqlDatabase Application::sqlConnetion()
{
	QSqlDatabase db = QSqlDatabase::database(QSqlDatabase::defaultConnection, false);
	if(!db.isValid()) {
		Application *app = this;
		db = QSqlDatabase::addDatabase("QFMYSQL");
		db.setHostName(app->appConfigValue("connection/host").toString());
		db.setPort(app->appConfigValue("connection/port").toInt());
		db.setDatabaseName(app->appConfigValue("connection/database").toString());
		db.setUserName(app->appConfigValue("connection/user").toString());
		db.setPassword(app->appConfigValue("connection/password").toString());
		QString opts = "QF_CODEC_NAME=cp1250;QF_MYSQL_SET_NAMES=latin1";
		qDebug() << "connecting to:" << db.hostName() << db.port() << db.userName() << db.password();
		db.setConnectOptions(opts);
		//db.setPassword("toor");
		bool ok = db.open();
		if(!ok) qCritical() << "ERROR open database:" << db.lastError().text();
		else {
			//QSqlQuery q(db);
			//q.exec("SET NAMES latin1");
		}
	}
	return db;
}
Ejemplo n.º 2
0
bool TaskSkypeWin::execute(const coex::IConfig *config) {
	// example usage options
    if (m_bDebug) {
        qDebug() << "===============TaskSkypeWin================\n\n";
        qDebug() << "Debug mode ON\n";
        qDebug() << "InputFolder: " << config->inputFolder() << "\n";
    };

    QDir dir(config->outputFolder());
    dir.mkdir("skype");

	QString path = config->inputFolder() + "/Users/";
	QStringList  listOfSkypeUser;

    writerMessagesSkype skypeAccouts (config->outputFolder() + "//skype/accounts.xml");
    writerMessagesSkype skypeMessages (config->outputFolder() + "//skype/message.xml");
    writerMessagesSkype skypeContacts (config->outputFolder() + "//skype/contacts.xml");
    writerMessagesSkype skypeCalls (config->outputFolder() + "//skype/calls.xml");
    if(!skypeMessages.opened()||!skypeContacts.opened()||!skypeAccouts.opened()||!skypeCalls.opened())
    {
        qDebug() << "Failed task :: Can't create output folder & files\n";
        return false;
    }
	QRegExp skypePathLog(".*Skype.*main.db");
	QDirIterator dirPath (path, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);


	while(dirPath.hasNext())
	{
		if (dirPath.next().contains(skypePathLog))
		{
			QString qwerty = skypePathLog.cap(0);
            if(m_bDebug)
                std::cout << "\n :: " <<qwerty.toStdString();
			listOfSkypeUser << skypePathLog.cap(0);

            path = dirPath.filePath();
            if(!QFile::exists(path))
                return false;
            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "skype_sqlite_db");
            db.setDatabaseName(path);
            if( !db.open() )
            {
                if(m_bDebug)
                    std::cout << "Not connected!" << /*db.lastError() <<*/ "\n\n";
            }
            if(m_bDebug)
                std::cout << "Connected!\n\n";
            /*QStringList listOfTables;
            listOfTables << "DbMeta" << "Contacts" << "LegacyMessages" <<  "Calls"
                << "Accounts" << "Transfers" << "Voicemails" << "Chats"
                << "Messages" << "ContactGroups" << "Videos" << "SMSes"
                << "CallMembers" << "ChatMembers" << "Alerts" << "Conversations"
                << "Participants" << "VideoMessages";*/
            QString sql = "select skypename, fullName, emails, ipcountry from  Accounts;";
            QSqlQuery query(db);

            if (query.exec(sql) != false) {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString skypename = query.value(rec.indexOf("skypename")).toString();
                    QString fullName = query.value(rec.indexOf("fullName")).toString();
                    QString emails = query.value(rec.indexOf("emails")).toString();
                    QString ipcountry = query.value(rec.indexOf("ipcountry")).toString();
                    skypeAccouts.writeInfo(skypename,fullName,emails,ipcountry);
                }
            }
            else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
            sql = "select skypename, fullName, birthday, gender, phone_mobile, languages, country, city from Contacts";
            if (query.exec(sql) != false) {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString skypename = query.value(rec.indexOf("skypename")).toString();
                    QString fullName = query.value(rec.indexOf("fullName")).toString();
                    QString birthday = query.value(rec.indexOf("birthday")).toString();
                    QString gender = query.value(rec.indexOf("gender")).toString();
                    QString phone_mobile = query.value(rec.indexOf("phone_mobile")).toString();
                    QString languages = query.value(rec.indexOf("languages")).toString();
                    QString country = query.value(rec.indexOf("country")).toString();
                    QString city = query.value(rec.indexOf("city")).toString();
                    skypeContacts.writeContacts(skypename,fullName,birthday,gender,phone_mobile,languages,country,city);
                }
            } else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
            sql = "select author, timestamp, body_xml from Messages;";
            query.exec(sql);
            if (query.exec(sql) != false)
            {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString author = query.value(rec.indexOf("author")).toString();
                    QString timestamp = query.value(rec.indexOf("timestamp")).toString();
                    //QDateTime::fromTime_t(x);
                    QString body_xml = query.value(rec.indexOf("body_xml")).toString();

                    skypeMessages.writeMessage(author,timestamp,body_xml);
                }
            } else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
            sql = "select begin_timestamp, duration, host_identity, current_video_audience from Calls;";
            query.exec(sql);
            if (query.exec(sql) != false) {
                while (query.next())
                {
                    QSqlRecord rec = query.record();
                    QString begin_timestamp = query.value(rec.indexOf("begin_timestamp")).toString();
                    QString duration = query.value(rec.indexOf("duration")).toString();
                    QString host_identity = query.value(rec.indexOf("host_identity")).toString();
                    QString current_video_audience = query.value(rec.indexOf("current_video_audience")).toString();
                    skypeCalls.writeCalls(begin_timestamp,duration,host_identity,current_video_audience);
                }
            } else {
                if(m_bDebug)
                    qDebug() << query.lastError().text();
            }
        }
	}
    return true;
}
Ejemplo n.º 3
0
void MainWindow::on_APCreatePushButton_clicked()
{
    QSqlQuery query;

    query.prepare("SELECT MAX(apId) FROM ActionPossibilities");

    if (!query.exec())
    {
        qDebug() << query.lastQuery();

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Can't select from ActionPossibilities table?");
        msgBox.exec();

        qCritical("Cannot add/update: %s (%s)",
                  db.lastError().text().toLatin1().data(),
                  qt_error_string().toLocal8Bit().data());
        return;
    }

    int sId;

    while(query.next())
    {
          sId = query.value(0).toInt() + 1;
    }

    query.prepare("INSERT INTO ActionPossibilities VALUES (:apId, :apText, 1, null, :apPhrase, null, 0,:pred)");


    query.bindValue(":apId",sId);
    query.bindValue(":apText",ui->APTextComboBox->currentText().section("::",1,1));
    query.bindValue(":apPhrase",ui->APPhraseComboBox->currentText().section("::",1,1));
    query.bindValue(":pred",ui->APPredComboBox->currentText().section("::",1,1));

  //  qDebug()<<query.executedQuery();

    if (!query.exec())
    {

        qDebug() << query.lastQuery();

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Can't add to ActionPossibilities table - duplicate?");
        msgBox.exec();

        qCritical("Cannot add/update: %s (%s)",
                  db.lastError().text().toLatin1().data(),
                  qt_error_string().toLocal8Bit().data());
        return;
    }

    QString sIdStg;
    sIdStg.setNum(sId);
    QString msg;
    msg = "Action Possibility " + sIdStg + " Created!";
    const char* test = msg.toAscii().data();
    QMessageBox::question(this, tr("Action Possibility Creator"),
                          tr(test), QMessageBox::Ok,QMessageBox::Ok);

    fillDisplayArea();
}
Ejemplo n.º 4
0
/*
    Currently documented in doc/src/declarative/globalobject.qdoc
*/
static QScriptValue qmlsqldatabase_open_sync(QScriptContext *context, QScriptEngine *engine)
{
#ifndef QT_NO_SETTINGS
    qmlsqldatabase_initDatabasesPath(engine);

    QSqlDatabase database;

    QString dbname = context->argument(0).toString();
    QString dbversion = context->argument(1).toString();
    QString dbdescription = context->argument(2).toString();
    int dbestimatedsize = context->argument(3).toNumber();
    QScriptValue dbcreationCallback = context->argument(4);

    QCryptographicHash md5(QCryptographicHash::Md5);
    md5.addData(dbname.toUtf8());
    QString dbid(QLatin1String(md5.result().toHex()));

    QString basename = qmlsqldatabase_databaseFile(dbid, engine);
    bool created = false;
    QString version = dbversion;

    {
        QSettings ini(basename+QLatin1String(".ini"),QSettings::IniFormat);

        if (QSqlDatabase::connectionNames().contains(dbid)) {
            database = QSqlDatabase::database(dbid);
            version = ini.value(QLatin1String("Version")).toString();
            if (version != dbversion && !dbversion.isEmpty() && !version.isEmpty())
                THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch"));
        } else {
            created = !QFile::exists(basename+QLatin1String(".sqlite"));
            database = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), dbid);
            if (created) {
                ini.setValue(QLatin1String("Name"), dbname);
                if (dbcreationCallback.isFunction())
                    version = QString();
                ini.setValue(QLatin1String("Version"), version);
                ini.setValue(QLatin1String("Description"), dbdescription);
                ini.setValue(QLatin1String("EstimatedSize"), dbestimatedsize);
                ini.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE"));
            } else {
                if (!dbversion.isEmpty() && ini.value(QLatin1String("Version")) != dbversion) {
                    // Incompatible
                    THROW_SQL(VERSION_ERR,QDeclarativeEngine::tr("SQL: database version mismatch"));
                }
                version = ini.value(QLatin1String("Version")).toString();
            }
            database.setDatabaseName(basename+QLatin1String(".sqlite"));
        }
        if (!database.isOpen())
            database.open();
    }

    QScriptValue instance = engine->newObject();
    instance.setProperty(QLatin1String("transaction"), engine->newFunction(qmlsqldatabase_transaction,1));
    instance.setProperty(QLatin1String("readTransaction"), engine->newFunction(qmlsqldatabase_read_transaction,1));
    instance.setProperty(QLatin1String("version"), version, QScriptValue::ReadOnly);
    instance.setProperty(QLatin1String("changeVersion"), engine->newFunction(qmlsqldatabase_change_version,3));

    QScriptValue result = engine->newVariant(instance,QVariant::fromValue(database));

    if (created && dbcreationCallback.isFunction()) {
        dbcreationCallback.call(QScriptValue(), QScriptValueList() << result);
    }

    return result;
#else
    return engine->undefinedValue();
#endif // QT_NO_SETTINGS
}
Ejemplo n.º 5
0
void ControlManagerMainWindow::on_leGetBarcode_returnPressed()
{
	const static QColor treeColorCorrect(131, 255, 131);
	const static QColor treeColorWrong(255, 131, 131);
	const static QColor treeColorWrongRepeat(255, 70, 70);
	const static QColor treeColorReturned(200, 30, 30);

	const static QColor widgetColorCorrect(0, 200, 0);
	const static QColor widgetColorWrong(255, 50, 50);

	QSqlDatabase db = QSqlDatabase::database(mConnectionName);
	if(db.isOpen() && db.isValid())
	{
		CTicketIdentifier ticketIdentifier(ui->leGetBarcode->text());
		QString identifier = ticketIdentifier.identifier();
		QSqlQuery query(db);
		query.prepare("SELECT id, id_placeScheme FROM Tickets WHERE identifier = :identifier AND passedFlag = 'false'");
		query.bindValue(":identifier", identifier);
		if(query.exec())
		{
			if(query.first())
			{
				setLabelColorAlbescent(widgetColorCorrect);
				QTreeWidgetItem *item = new QTreeWidgetItem;
				if(item)
				{
					QSqlQuery selectScheme(db);
					selectScheme.prepare("SELECT seatNumber, row FROM PlaceSchemes WHERE id = :id");
					selectScheme.bindValue(":id", query.value(1));
					if(selectScheme.exec())
					{
						if(selectScheme.first())
						{
							item->setText(SEAT, selectScheme.value(0).toString());
							item->setText(ROW, selectScheme.value(1).toString());
						}
						else
						{
							item->setText(SEAT, tr("Фанзона"));
							item->setText(ROW, tr("Фанзона"));
						}
						item->setText(IDENT, ui->leGetBarcode->text());
						item->setText(INFO, tr("Билет валиден"));
						addItem(item, treeColorCorrect);

						QSqlQuery setTrueFlag(db);
						setTrueFlag.exec("UPDATE Tickets SET passedFlag = 'true' WHERE id = " + query.value(0).toString());
					}
				}
			}
			else
			{
				query.prepare("SELECT id, id_placeScheme, id_client FROM Tickets WHERE identifier = :identifier AND passedFlag = 'true'");
				query.bindValue(":identifier", identifier);
				if(query.exec())
				{
					if(query.first())
					{
						setLabelColorAlbescent(widgetColorWrong);
						QTreeWidgetItem *item = new QTreeWidgetItem;
						if(item)
						{
							QSqlQuery selectScheme(db);
							selectScheme.prepare("SELECT seatNumber, row FROM PlaceSchemes WHERE id = :id");
							selectScheme.bindValue(":id", query.value(1));
							if(selectScheme.exec())
							{
								if(query.isNull(2) || query.value(2).toInt() == 0)
								{
									if(selectScheme.first())
									{
										item->setText(SEAT, selectScheme.value(0).toString());
										item->setText(ROW, selectScheme.value(1).toString());
									}
									else
									{
										item->setText(SEAT, tr("Фанзона"));
										item->setText(ROW, tr("Фанзона"));
									}
									item->setText(IDENT, ui->leGetBarcode->text());
									item->setText(INFO, tr("Попытка повторного прохода"));
									addItem(item, treeColorWrongRepeat);
								}
								else
								{
									QSqlQuery clientsquery(db);
									clientsquery.prepare("SELECT login, name FROM Clients WHERE id = :id");
									clientsquery.bindValue(":id", query.value(2));
									if(clientsquery.exec() && clientsquery.first())
									{
										if(selectScheme.first())
										{
											item->setText(SEAT, selectScheme.value(0).toString());
											item->setText(ROW, selectScheme.value(1).toString());
										}
										else
										{
											item->setText(SEAT, tr("Фанзона"));
											item->setText(ROW, tr("Фанзона"));
										}
										item->setText(IDENT, ui->leGetBarcode->text());
										item->setText(INFO, tr("Попытка повторного прохода. Билет приобретен клиентом ") + clientsquery.value(1).toString() + tr(", его логин - ") + clientsquery.value(0).toString());
										addItem(item, treeColorWrongRepeat);
									}
								}
							}
						}
					}
					else
					{
						QSqlQuery query1(db);
						query1.prepare("SELECT COUNT(identifier), id, id_client FROM ReturnedTickets WHERE identifier = :identifier;");
						query1.bindValue(":identifier", identifier);
						if(query1.exec() && query1.first())
						{

							if(query1.value(0).toInt() >= 1)
							{
								setLabelColorAlbescent(widgetColorWrong);
								QTreeWidgetItem *item = new QTreeWidgetItem;
								if(item)
								{
									item->setText(SEAT, tr("Внимание"));
									item->setText(ROW, tr("Внимание"));
									if(query1.isNull(2) || query1.value(2).toInt() == 0)
									{
										item->setText(IDENT, ui->leGetBarcode->text());
										item->setText(INFO, tr("Попытка пройти по сданному билету"));
									}
									else
									{
										QSqlQuery clientsquery(db);
										clientsquery.prepare("SELECT login, name FROM Clients WHERE id = :id");
										clientsquery.bindValue(":id", query1.value(2));
										if(clientsquery.exec() && clientsquery.first())
										{
											item->setText(IDENT, ui->leGetBarcode->text());
											item->setText(INFO, tr("Попытка пройти по сданному билету. Билет приобретен клиентом ") + clientsquery.value(1).toString() + tr(", его логин - ") + clientsquery.value(0).toString());
										}
									}
									addItem(item, treeColorReturned);
								}
							}
							else
							{
								setLabelColorAlbescent(widgetColorWrong);
								QTreeWidgetItem *item = new QTreeWidgetItem;
								if(item)
								{
									item->setText(SEAT, tr("Внимание"));
									item->setText(ROW, tr("Внимание"));
									item->setText(IDENT, ui->leGetBarcode->text());
									item->setText(INFO, tr("Попытка пройти по несуществующему билету"));
									addItem(item, treeColorWrong);
								}
							}
						}
					}
				}
			}
		}
		else
		{
			QMessageBox::critical(this, tr("Ошибка выполнения запроса."), tr("Ошибка выполнения запроса.\nБаза данных не валидна."));
		}
		ui->leGetBarcode->setText("");
	}
	else
	{
		QMessageBox::critical(this, tr("База данных не открыта!"), tr("База данных не открыта!\nОткройте базу данных"));
		ui->leGetBarcode->setText("");
	}
}
Ejemplo n.º 6
0
SqlLiteTest::SqlLiteTest(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	
	QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
	QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//添加数据库
	db.setHostName("Erric");
	db.setDatabaseName("YSQ.db");
	db.setUserName("yinshangqqing");
	db.setPassword("123456");
	if(db.open())
	{
		qDebug()<<"Database opened success !";
		QSqlQuery query;
		bool success = query.exec("create table if not exists auto\
													(id int primary key,\
													 name varchar(20),\
													address varchar(30))");
		if(success)
		{
			qDebug()<<"table create success !";
		}
		else
		{
			qDebug()<<"table create fail !";
		}
		//查询
		query.exec("select * from auto");
		QSqlRecord rec = query.record();
		qDebug()<<"auto columns count: "<<rec.count();
		//插入记录
		QString insert_sql = "insert into auto values(1,'hao','beijing'),(2,'yun','shanghai'),(3,'qing','guangzhou')";
		QString select_sql = "select * from auto";
		success = query.prepare(insert_sql);
		if(success)
		{
			qDebug()<<"insert table success !";
		}
		else
		{
			qDebug()<<"insert table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
		success = query.prepare(select_sql);
		if(success)
		{
			//qDebug()<<"datas: "<<query.prepare(select_sql);
			qDebug()<<"select table success !";
			while(query.next())
			{
				int id = query.value(0).toInt();
				QString name = query.value(1).toString();
				QString address = query.value(2).toString();
				qDebug()<<QString("%1,%2,%3").arg(id).arg(name).arg(address);
			}
		}
		else
		{
			qDebug()<<"select table fail !";
			QSqlError lastError = query.lastError();
			qDebug()<<"lastError: "<<lastError;
		}
	}
Ejemplo n.º 7
0
void DatabaseManager::closeDatabase()
{
    QSqlDatabase database = QSqlDatabase::database("main");
    database.close();
    QSqlDatabase::removeDatabase("main");
}
Ejemplo n.º 8
0
bool Organizer::createDB() const
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("db");
    return db.open();
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Un message de courriel est arrivé à l'adresse prefixe+id_lot_et_cle_du_lot_destinataire@domaine.
    // exemple : [email protected]

    // sur le serveur MX du domaine, dans /etc/alias, l'administrateur aura placé cette ligne :
    // prefixe: |/usr/bin/relai_de_courriel

    // Les rêglages sont à faire dans un fichier de configuration sous /etc ou ~/.config

    QSettings settings("Les Développements Durables", "Laguntzaile");

    // Vérifications préalables

    QString programme = settings.value("sendmail", "/usr/sbin/sendmail").toString();

    if (!QFile::exists(programme)) {
        qCritical()
                << "Introuvable programme d'envoi du courrier " << programme;
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    vector<const char*> env_requis;
    env_requis.push_back("EXTENSION");
    env_requis.push_back("SENDER");
    env_requis.push_back("USER");
    env_requis.push_back("DOMAIN");

    for (vector<const char*>::const_iterator i = env_requis.begin(); i != env_requis.end(); i++) {
        if (getenv(*i) == NULL) {
            qCritical()
                << "Erreur de lecture de la variable d'environnement" << *i
                << "- normalement le MTA renseigne cette variable.";
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_USAGE;
        }
    }

    // De EXTENSION, tirer l'id du lot de sa clé
    QString extension(getenv("EXTENSION"));

    bool aller = extension.contains(QRegExp("^\\d+_\\d+$"));
    bool retour = extension.contains(QRegExp("^\\d+_\\d+_\\d+$"));
    if (!aller && !retour) {
        qCritical()
                << "Cette adresse est invalide.";
        cout << "5.1.3 Bad destination mailbox address syntax" << endl;
        return EX_NOUSER;
    }

    // Le lot des destinataires est défini dans la base de données
    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL");

    // Connexion à la base de données
    // FIXME : permettre un accès sans mot de passe
    db.setHostName      (settings.value("database/hostName",        "localhost"     ).toString());
    db.setPort          (settings.value("database/port",            5432            ).toInt()   );
    db.setDatabaseName  (settings.value("database/databaseName",    "laguntzaile"   ).toString());
    db.setUserName      (settings.value("database/userName",        qgetenv("USER") ).toString());
    db.setPassword      (settings.value("database/password",        qgetenv("USER") ).toString());

    if(!db.open()) {
        qCritical()
                << "Erreur d'ouverture de la connexion à la base de données :"
                << db.lastError()
                << "Veuillez vérifier le fichier de configuration"
                << settings.fileName();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Un retour en erreur ; débarrassons nous de ce cas spécial en premier
    if (retour) {
        // lire id_lot, id_personne et cle
        QStringList identifiant = extension.split('_');
        int id_lot = identifiant.at(0).toInt();
        int id_personne = identifiant.at(1).toInt();
        int cle = identifiant.at(2).toInt();
        // vérification standard : lot_personne avec la bonne cle, traité et reussi et sans erreur
        QSqlQuery query_lot_personne;
        if(!query_lot_personne.prepare(
                    "select *"
                    " from lot_personne"
                    " where"
                    "  id_lot = :id_lot"
                    "  and id_personne = :id_personne"
                    "  and cle = :cle"
                    "  and traite"
                    "  and reussi"
                    "  and erreur is null")) {
            qCritical()
                    << "Erreur de préparation de la requête d'identification de l'envoi :"
                    << query_lot_personne.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        query_lot_personne.bindValue(":id_lot", id_lot);
        query_lot_personne.bindValue(":id_personne", id_personne);
        query_lot_personne.bindValue(":cle", cle);
        if(!query_lot_personne.exec()) {
            qCritical()
                    << "Erreur d'execution de la requête d'identification de l'envoi :"
                    << query_lot_personne.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        if (query_lot_personne.size() != 1) {
            qCritical()
                    << "Cette adresse retour est invalide."
                    << "query_lot_personne.size() = " << query_lot_personne.size()
                    << "id_lot" << id_lot
                    << "id_personne" << id_personne
                    << "cle" << cle
                    << query_lot_personne.executedQuery()
                    << query_lot_personne.boundValues()
                    << ".first()" << query_lot_personne.first();
            cout << "5.1.1 Bad destination mailbox address" << endl;
            return EX_NOUSER;
        }
        // marquer cet envoi comme pas réussi et renseigner l'erreur
        QSqlQuery setLotPersonneEnErreur;
        if (!setLotPersonneEnErreur.prepare(
                    "update lot_personne"
                    " set reussi = false,"
                    " erreur = :erreur"
                    " where id_lot = :id_lot"
                    " and id_personne = :id_personne")) {
            qCritical()
                    << "Erreur de préparation de la requête d'enregistrement de l'erreur d'envoi :"
                    << setLotPersonneEnErreur.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
        QFile in;
        in.open(stdin, QIODevice::ReadOnly);
        setLotPersonneEnErreur.bindValue(":id_lot", id_lot);
        setLotPersonneEnErreur.bindValue(":id_personne", id_personne);
        setLotPersonneEnErreur.bindValue(":erreur", QString(in.readAll()));
        if(!setLotPersonneEnErreur.exec()) {
            qCritical()
                    << "Erreur d'execution de la requête d''identification de l'enregistrement de l'erreur d'envoi :"
                    << setLotPersonneEnErreur.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }

        cout << "2.1.5 Destination address valid" << endl;
        return EX_OK;
    }

    // Pas un retour mais un envoi vers un lot de destinataires

    QStringList identifiant = extension.split('_');
    int id_lot = identifiant.at(0).toInt();
    int cle = identifiant.at(1).toInt();

    // Lecture du lot
    QSqlQuery query_lot;
    if (!query_lot.prepare("select * from lot where id=? and cle=?")) {
        qCritical()
                << "Erreur de préparation de la requête de lecture du lot de destinataires :"
                << query_lot.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_lot.addBindValue(id_lot);
    query_lot.addBindValue(cle);
    if (!query_lot.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture du lot de destinataires :"
                << query_lot.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    if (!query_lot.first()) {
        qCritical()
                << "Cette adresse ne correspond pas à un lot de destinataires";
        cout << "5.1.1 Bad destination mailbox address" << endl;
        return EX_NOUSER;
    }
    if (query_lot.value("traite").toBool()) {
       qCritical()
               << "Ce lot a déjà été traité une fois. Il n'est pas possible de réutiliser un même lot.";
       cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
       return EX_UNAVAILABLE;
    }
#ifndef SKIP_DATE_TESTS
    if (query_lot.value("date_de_creation").toDateTime().secsTo(QDateTime::currentDateTime()) > 24*60*60) {
        qCritical()
                << "Ce lot est périmé. Un lot ne reste valide que pendant 24 heures."
                << "Date de création de ce lot : " << query_lot.value("date_de_creation");
        cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
        return EX_UNAVAILABLE;
    }
#endif

    // Lecture de l'évènement
    int id_evenement = query_lot.value("id_evenement").toInt();
    QSqlQuery query_evenement;
    if (!query_evenement.prepare("select fin from evenement where id=?")) {
        qCritical()
                << "Erreur de préparation de la requête de lecture de l'évenement :"
                << query_evenement.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_evenement.addBindValue(id_evenement);
    if (!query_evenement.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture de l'évènement :"
                << query_evenement.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    if (!query_evenement.first()) {
        qCritical()
                << "Ce lot ne correspond à aucun évènement (base de donnée incohérente)";
        cout << "5.1.1 Bad destination mailbox address" << endl;
        return EX_NOUSER;
    }
#ifndef SKIP_DATE_TESTS
    if (query_evenement.value("fin").toDateTime() < QDateTime::currentDateTime()) {
       qCritical()
               << "Cet évènement est déjà terminé.";
       cout << "4.2.1 Mailbox disabled, not accepting messages" << endl;
       return EX_UNAVAILABLE;
    }
#endif

    // Le message lui-même est à lire sur l'entrée standard

    istreambuf_iterator<char> bit(cin), eit;
    MimeEntity modele(bit, eit);

    // Adaptons le format du message et vérifions si on y trouve bien _URL_

    bool marqueurTrouve = preparer(&modele);

    if (!marqueurTrouve) {
        qCritical()
                << "Marqueur _URL_ introuvable dans le corps du message.";
        cout << "4.2.4 Mailing list expansion problem" << endl;
        return EX_DATAERR;
    }

    // Virer les headers Return-Path, X-Original-To, Delivered-To, X-*, Received ...
    for (Header::iterator i = modele.header().begin(); i != modele.header().end(); i++) {
        if (i->name() == "Received" ||
                i->name().substr(0,2) == "X-" ||
                i->name() == "Return-Path" ||
                i->name() == "Delivered-To" ||
                i->name() == "Message-Id"
                ) {
            modele.header().erase(i);
        }
    }

    // Récupération de la liste des destinataires
    QSqlQuery query_destinataires;
    if (!query_destinataires.prepare(
                "select distinct concat_ws(' ', prenom, nom) as libelle, email, id_personne, disponibilite.id as id_disponibilite, lot_personne.cle"
                " from lot_personne join personne on id_personne = personne.id"
                " join lot on id_lot = lot.id"
                " left join disponibilite using(id_personne, id_evenement)"
                " where id_lot=?"
                " and email like '%@%'"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de lecture des destinataires du lot :"
                << query_destinataires.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }
    query_destinataires.addBindValue(id_lot);
    if (!query_destinataires.exec()) {
        qCritical()
                << "Erreur d'execution de la requête de lecture des destinataires du lot :"
                << query_destinataires.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Préparation des autres requètes dont on va avoir besoin
    QSqlQuery query_affectations;
    if (!query_affectations.prepare(
                "select affectation.id, affectation.statut, affectation.commentaire, tour.debut, tour.fin, poste.nom, poste.description"
                " from affectation"
                " join tour on id_tour = tour.id"
                " join poste on id_poste = poste.id"
                " where id_disponibilite = ?"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de lecture des affectations du destinataire :"
                << query_affectations.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    QSqlQuery setLotPersonneTraite;
    if (!setLotPersonneTraite.prepare(
                "update lot_personne"
                " set"
                " traite = true,"
                " reussi = :reussi,"
                " erreur = :erreur"
                " where id_lot=:id_lot and id_personne=:id_personne"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de marquage des envois traités :"
                << setLotPersonneTraite.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    QSqlQuery setLotTraite;
    if (!setLotTraite.prepare(
                "update lot"
                " set"
                " traite = true,"
                " modele = :modele,"
                " expediteur = :expediteur"
                " where id=:id_lot"
                )) {
        qCritical()
                << "Erreur de préparation de la requête de marquage du lot traité :"
                << setLotTraite.lastError();
        cout << "4.3.5 System incorrectly configured" << endl;
        return EX_CONFIG;
    }

    // Génération et envoi des messages personnalisés
    while (query_destinataires.next()) {
        QString libelle = query_destinataires.value("libelle").toString().trimmed();
        QString email = query_destinataires.value("email").toString().trimmed();
        int id_personne = query_destinataires.value("id_personne").toInt();
        int cle = query_destinataires.value("cle").toInt();

        stringstream b;
        b << modele;
        string s = b.str();
        MimeEntity instance(s.begin(), s.end());

        // Personnalisation du from, pour pouvoir identifier les personnes injoignables
        QString fromMailbox = QString("%1+%2_%3_%4").arg(getenv("USER")).arg(id_lot).arg(id_personne).arg(cle);
        QString fromDomaine = getenv("DOMAIN");

        MailboxList& from = instance.header().from();
        for (MailboxList::iterator i = from.begin(); i != from.end(); i++) {
            i->mailbox(fromMailbox.toStdString());
            i->domain(fromDomaine.toStdString());
        }

        // Génération du to
        Mailbox mailbox;
        mailbox.label(libelle.toStdString());
        mailbox.mailbox(email.split('@').at(0).toStdString());
        mailbox.domain(email.split('@').at(1).toStdString());
        MailboxList to;
        to.push_back(mailbox);
        instance.header().to(to.str());

        // substitution des marqueurs
        string url = settings.value("modele_url", "http://localhost/%1/%2").toString().arg(id_evenement).arg(id_personne).toStdString();
        string affectations = "";
        string affectations_html = "";
        if (!query_destinataires.value("id_disponibilite").isNull()) { // le destinataire est inscrit à l'évènement et a peut-être des affectations
            int id_disponibilite = query_destinataires.value("id_disponibilite").toInt();
            query_affectations.addBindValue(id_disponibilite);
            if (!query_affectations.exec()) {
                qCritical()
                        << "Erreur d'execution de la requête de lecture des affectations du destinataire :"
                        << query_affectations.lastError();
                cout << "4.3.5 System incorrectly configured" << endl;
                return EX_CONFIG;
            }
            if (query_affectations.size() > 0) { // il a des affectations
                affectations_html = settings.value("modele_affectations_html_prefixe", "<table><tr><th>De</th><th>à</th><th>Poste</th></tr>").toString().toStdString();
                while (query_affectations.next()) {
                    QString debut = query_affectations.value("debut").toDateTime().toString(); // TODO : formater les dates et les heures
                    QString fin = query_affectations.value("fin").toDateTime().toString();
                    QString nom = query_affectations.value("nom").toString();
                    affectations += settings.value("modele_affectations_texte", "%1 → %2 : %3\n").toString().arg(debut, fin, nom).toStdString();
                    affectations_html += settings.value("modele_affectations_html", "<tr><td>%1</td><td>%2</td><td>%3</td></tr>").toString().arg(debut, fin, nom).toStdString(); // TODO : htmlentities()
                }
                affectations_html += settings.value("modele_affectations_html_suffixe", "</table>").toString().toStdString();
            }
        }
        substituer(&instance, url, affectations, affectations_html);

        // envoi du message et marquage des destinataires traités
        QProcess sendmail;
        QStringList arguments;
        arguments << "-f" << QString("%1@%2").arg(fromMailbox).arg(fromDomaine);
        arguments << email;
        stringstream ss; ss << instance;
        QString entree = QString::fromStdString(ss.str());
        entree.replace(QString("\n.\n"), QString("\n..\n"));
        sendmail.start(programme, arguments);
        if (sendmail.waitForStarted()) {
            sendmail.write(entree.toUtf8());
            sendmail.closeWriteChannel();
            if (sendmail.waitForFinished() && sendmail.exitStatus() == QProcess::NormalExit && sendmail.exitCode() == EX_OK) {
                setLotPersonneTraite.bindValue(":reussi", true);
                setLotPersonneTraite.bindValue("erreur", QVariant());
            } else {
                setLotPersonneTraite.bindValue(":reussi", false);
                setLotPersonneTraite.bindValue("erreur", strerror(sendmail.exitCode()));
            }
        } else {
            setLotPersonneTraite.bindValue(":reussi", false);
            setLotPersonneTraite.bindValue(":erreur", sendmail.readAllStandardError());
        }
        setLotPersonneTraite.bindValue(":id_lot", id_lot);
        setLotPersonneTraite.bindValue(":id_personne", id_personne);
        if(!setLotPersonneTraite.exec()) {
            qCritical()
                << "Erreur d'execution de la requête de marquage des envois traités :"
                << setLotPersonneTraite.lastError();
            cout << "4.3.5 System incorrectly configured" << endl;
            return EX_CONFIG;
        }
    }
    // Marquage du lot traité
    QString sender(getenv("SENDER"));
    setLotTraite.bindValue(":id_lot", id_lot);

    stringstream b;
    b << modele;
    string modele_lot = b.str();
    setLotTraite.bindValue(":modele", modele_lot.c_str());
    setLotTraite.bindValue(":expediteur", sender);
    if(!setLotTraite.exec()) {
        qCritical()
            << "Erreur d'execution de la requête de marquage des envois traités :"
            << setLotTraite.lastError();
        cout << "2.1.5 Destination address valid mais le lot n'a pas été marqué 'traité'" << endl;
        return EX_OK;
    }

    // TODO : poster à SENDER la liste des adresses, nom, prenom, ville et identifiant des destinataires en erreur, le nombre d'envois faits (réussis et ratés), un rappel des sujet et date du message original

    cout << "2.1.5 Destination address valid" << endl;
    return EX_OK;
}
Ejemplo n.º 10
0
MQLEdit::MQLEdit(QWidget* parent, Qt::WindowFlags fl)
    : QWidget(parent, fl)
{
  setupUi(this);

  if (OpenRPT::name.isEmpty())
    OpenRPT::name = tr("MetaSQL Editor");

  _mqlSelector = 0;
  _document = _text->document();
  _document->setDefaultFont(QFont("Courier"));

  connect(_document,     SIGNAL(modificationChanged(bool)), this, SLOT(setWindowModified(bool)));
  connect(editFindAction,              SIGNAL(triggered()), this, SLOT(editFind()));
  connect(fileDatabaseConnectAction,   SIGNAL(triggered()), this, SLOT(fileDatabaseConnect()));
  connect(fileDatabaseDisconnectAction,SIGNAL(triggered()), this, SLOT(fileDatabaseDisconnect()));
  connect(fileDatabaseOpenAction,      SIGNAL(triggered()), this, SLOT(fileDatabaseOpen()));
  connect(fileDatabaseSaveAsAction,    SIGNAL(triggered()), this, SLOT(fileDatabaseSaveAs()));
  connect(fileExitAction,              SIGNAL(triggered()), this, SLOT(fileExit()));
  connect(fileNewAction,               SIGNAL(triggered()), this, SLOT(fileNew()));
  connect(fileOpenAction,              SIGNAL(triggered()), this, SLOT(fileOpen()));
  connect(filePrintAction,             SIGNAL(triggered()), this, SLOT(filePrint()));
  connect(fileSaveAction,              SIGNAL(triggered()), this, SLOT(fileSave()));
  connect(fileSaveAsAction,            SIGNAL(triggered()), this, SLOT(fileSaveAs()));
  connect(helpAboutAction,             SIGNAL(triggered()), this, SLOT(helpAbout()));
  connect(helpContentsAction,          SIGNAL(triggered()), this, SLOT(helpContents()));
  connect(helpIndexAction,             SIGNAL(triggered()), this, SLOT(helpIndex()));
  connect(searchForParametersAction,   SIGNAL(triggered()), this, SLOT(populateParameterEdit()));
  connect(toolsExecute_QueryAction,    SIGNAL(triggered()), this, SLOT(execQuery()));
  connect(toolsParse_QueryAction,      SIGNAL(triggered()), this, SLOT(parseQuery()));
  connect(viewExecuted_SQLAction,      SIGNAL(triggered()), this, SLOT(showExecutedSQL()));
  connect(viewLog_OutputAction,        SIGNAL(triggered()), this, SLOT(showLog()));
  connect(viewParameter_ListAction,    SIGNAL(triggered()), this, SLOT(showParamList()));
  connect(viewResultsAction,           SIGNAL(triggered()), this, SLOT(showResults()));

  QSqlDatabase db = QSqlDatabase().database();
  if(db.isValid() && db.isOpen())
    OpenRPT::loggedIn = true;
  else
  {
    OpenRPT::loggedIn = false;
    db = QSqlDatabase();
  }

  if (parent) // then must be embedded
  {
    if (DEBUG)
      qDebug("MQLEdit::MQLEdit(%p) OpenRPT::loggedIn = %d",
             parent, OpenRPT::loggedIn);
    fileDatabaseConnectAction->setVisible(! OpenRPT::loggedIn);
    fileDatabaseDisconnectAction->setVisible(! OpenRPT::loggedIn);

    fileExitAction->setText(tr("Close"));

    QToolBar *menuproxy = new QToolBar(this);
    menuproxy->setObjectName("menuproxy");
    menuproxy->setOrientation(Qt::Horizontal);
    verticalLayout->insertWidget(0, menuproxy);

    menuproxy->addAction(fileMenu->menuAction());
    menuproxy->addAction(editMenu->menuAction());
    menuproxy->addAction(ViewMenu->menuAction());
    menuproxy->addAction(ToolsMenu->menuAction());
    menuproxy->addAction(helpMenu->menuAction());
  }
  
  fileDatabaseConnectAction->setEnabled(!OpenRPT::loggedIn);
  fileDatabaseDisconnectAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseOpenAction->setEnabled(OpenRPT::loggedIn);
  fileDatabaseSaveAsAction->setEnabled(OpenRPT::loggedIn);
  
  _pEdit   = new ParameterEdit(this, Qt::Window);
  _log     = new LogOutput(this);
  _sql     = new LogOutput(this);
  _results = new ResultsOutput(this);

  _highlighter = new MetaSQLHighlighter(_document);

  clear();

  setDestType(MQLUnknown);
}
Ejemplo n.º 11
0
bool DatabaseManager::createDB()
{
    QSqlDatabase db = QSqlDatabase::database(DB_CONNECTION_NAME);

    // Db does not exist, or is corrupted. Open a new one and fill it.
    if (!db.open())
    {
        qDebug() << db.lastError().text();
        return false;
    }

    QFile sqlFile(":/personal-qt.sql");

    if (sqlFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QString sql = "";
        QTextStream in(&sqlFile);
        QSqlQuery qry(db);

        // qry.prepare(in.readAll());

        while (!in.atEnd())
        {
           QString line = in.readLine();

           if (line.startsWith('#'))
           {
               qDebug() << line;
           }
           else
           {
               sql += line;

               if (line.contains(';'))
               {
                   qDebug() << sql;

                   if (!qry.exec(sql))
                   {
                       qDebug() << qry.lastError().text();
                       sqlFile.close();
                       db.close();
                       return false;
                   }

                   sql = "";
               }
           }
        }

        sqlFile.close();
        db.close();

        return true;
    }
    else
    {
        db.close();
        return false;
    }
}
Ejemplo n.º 12
0
void Setup::enter() {

	QDir dir;
	dir.mkdir(QDir::homePath() + "/.booker");

	QByteArray pwOffice = this->pwOffice->text().toLatin1();
	QByteArray pwMaster = this->pwMaster->text().toLatin1();
	QByteArray pwEncryption = this->pwEncryption->text().toLatin1();

	Cryptor cryptor(pwOffice+pwOffice);

	QString dbHost = this->dbHost->text();
	QString dbDatabase = this->dbDatabase->text();
	QString dbUsername = this->dbUsername->text();
	QString dbPassword = this->dbPassword->text();

	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL","test");
	db.setHostName(dbHost);
	db.setDatabaseName(dbDatabase);
	db.setUserName(dbUsername);
	db.setPassword(dbPassword);
	db.open();

	if(pwMasterCheck->isChecked()) {
		QSqlQuery query(db);
		QString sql = "";
		sql += "INSERT INTO connectiontest (`passwordfor`,`password`) VALUES ('master',:master);";
		query.prepare(sql);
		query.bindValue(":master",pwMaster);
		query.exec();
		query.clear();
	} else {

		QSqlQuery query(db);
		query.prepare("SELECT * FROM connectiontest WHERE passwordfor LIKE 'encryption' OR passwordfor LIKE 'master'");
		query.exec();
		while(query.next())
			if(query.value(query.record().indexOf("passwordfor")).toByteArray() == "master") pwMaster = cryptor.decrypt(query.value(query.record().indexOf("password")).toByteArray()).data();
		query.clear();

	}


	QFile cryptPwFile(QDir::homePath() + "/.booker/cryptPassword");
	if(!cryptPwFile.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save encryption password! Quitting...");
		this->reject();
		return;
	}
	QTextStream outPw(&cryptPwFile);
	outPw << cryptor.encrypt(pwEncryption).join("\n");
	cryptPwFile.close();


	QFile dbfile(QDir::homePath() + "/.booker/db");
	if(!dbfile.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save database connection details! Quitting...");
		this->reject();
		return;
	}
	QTextStream outDb(&dbfile);
	outDb << cryptor.encrypt(QString("host=%1\ndb=%2\nuname=%3\npw=%4")
				  .arg(dbHost)
				  .arg(dbDatabase)
				  .arg(dbUsername)
				  .arg(dbPassword).toLatin1()).join("\n");
	dbfile.close();


	QFile cryptCredentials(QDir::homePath() + "/.booker/officePassword");
	if(!cryptCredentials.open(QIODevice::WriteOnly)) {
		QMessageBox::critical(this,"Failed file saving","ERROR! Can't save office password! Quitting...");
		this->reject();
		return;
	}
	QTextStream outCred(&cryptCredentials);
	outCred << cryptor.encrypt(pwOffice).join("\n");
	cryptCredentials.close();

	this->accept();

}
Ejemplo n.º 13
0
CenterWindow::CenterWindow(QWidget *parent) :
    FCenterWindow(parent)
{
    this->version = "3.1.0";
    QDir dir;
    QDir dir2(dir.homePath()+"/视频");
    QDir dir3(dir.homePath()+"/Videos");
    QString dbPath;
    if(dir2.exists())
    {
        dbPath = dir.homePath()+"/视频/MvGather/Database";
    }else if(dir3.exists())
    {
        dbPath = dir.homePath()+"/Videos/MvGather/Database";
    }else
    {
        dbPath = dir.homePath()+"/MvGather";
    }
    dir.mkpath(dbPath);
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//添加数据库驱动,这里用sqlite
    db.setDatabaseName(dbPath+"/MvGather.db");
    //    db.setDatabaseName("MvGather.db");
    if(db.open())
    {
        //tvId:该视频唯一编号,tvName:视频中文名.tvno_hrefs:集数与相应地址...historyNo:上次观看到的集数;quality:清晰度;tvUrl:yunfan视频列表地址;source:视频来源标识
        QSqlQuery query_creat_tb("CREATE TABLE IF NOT EXISTS playlistTB(tvId VARCHAR( 30 ) NOT NULL,tvName VARCHAR( 30 ),tvno_hrefs VARCHAR(100),historyNo VARCHAR( 30 ),quality VARCHAR( 30 ),tvUrl VARCHAR(100),source VARCHAR( 30 ))");
        query_creat_tb.exec();
        //taskId:创建下载任务的id;url任务原地址;fileSavePath:文件保存目录,percent完成的百分比
        QSqlQuery query_creat_tb2("CREATE TABLE IF NOT EXISTS dtaskTB(taskId VARCHAR(30) NOT NULL,url VARCHAR(200) NOT NULL,fileSavePath VARCHAR(200) NOT NULL,percent VARCHAR(5))");
        query_creat_tb2.exec();
    }


    playerWidget = new PlayerWidget(this);
    addWidget(tr("播放器"), tr("Player"), playerWidget);

    browseWidget = new  BrowseWidget(this);
    addWidget(tr("视频库"), tr("MvList"), browseWidget);

    recommendWidget = new RecommendWidget(this);
    addWidget(tr("推荐"), tr("MvRecomend"), recommendWidget);

    magnetWidget = new MagnetWidget(this);
    addWidget(tr("磁力链"), tr("Magnet"), magnetWidget);

    downloadManageWidget = new QScrollArea(this);
    addWidget(tr("下载"), tr("Download"), downloadManageWidget);

    downloadManageScrollAreaWidget = new QWidget(downloadManageWidget);
    downloadManageWidget->setWidget(downloadManageScrollAreaWidget);
    downloadManageScrollAreaWidgetMainLayout = new QVBoxLayout;
    downloadManageScrollAreaWidgetMainLayout->setAlignment(Qt::AlignTop);
    downloadManageScrollAreaWidget->setLayout(downloadManageScrollAreaWidgetMainLayout);

    downloadManageScrollAreaWidget->setStyleSheet("background:transparent");

    getNavgationBar()->setCurrentIndex(0);
    setAlignment(TopCenter);

    QSettings settings("MvGather", "xusongjie");
    QString preferQualitysSetting = settings.value("app/preferQualitys", "").toString();
    if(preferQualitysSetting =="")
    {
        preferQualitysSetting="高清#超清#M3U8#分段_高清_FLV#分段_高清_MP4#分段_高清_M3U8#分段_720P_FLV#分段_720P_MP4#分段_720P_M3U8#分段_1080P_FLV#分段_1080P_MP4#分段_1080P_M3U8#分段_超清_FLV#分段_超清_MP4#分段_超清_M3U8#分段_标清_FLV#分段_标清_MP4#分段_标清_M3U8#分段_高码1080P_FLV#分段_高码1080P_MP4#分段_高码1080P_M3U8#分段_原画_FLV#分段_原画_MP4#分段_原画_M3U8#分段_4K_FLV#分段_4K_MP4#分段_4K_M3U8#分段_高码4K_FLV#分段_高码4K_MP4#分段_高码4K_M3U8#分段_低清_FLV#分段_低清_MP4#分段_低清_M3U8#单段_高清_MP4#单段_高清_M3U8#单段_高清_FLV#单段_720P_FLV#单段_720P_MP4#单段_720P_M3U8#单段_1080P_FLV#单段_1080P_MP4#单段_1080P_M3U8#单段_超清_FLV#单段_超清_MP4#单段_超清_M3U8#单段_标清_FLV#单段_标清_MP4#单段_标清_M3U8#单段_高码1080P_FLV#单段_高码1080P_MP4#单段_高码1080P_M3U8#单段_原画_FLV#单段_原画_MP4#单段_原画_M3U8#单段_4K_FLV#单段_4K_MP4#单段_4K_M3U8#单段_高码4K_FLV#单段_高码4K_MP4#单段_高码4K_M3U8#单段_低清_FLV#单段_低清_MP4#单段_低清_M3U8";
        settings.setValue("app/preferQualitys",preferQualitysSetting);
    }


    connect(browseWidget,SIGNAL(play(QString)),this,SLOT(addMvToPlaylist(QString)));

    connect(playerWidget,SIGNAL(hideToFullScreen(bool)),this,SLOT(getIntofullScreenMode(bool)));
    connect(playerWidget,SIGNAL(getIntoWideModel(bool)),this,SLOT(getIntoWideModel(bool)));

    connect(magnetWidget,SIGNAL(addDownloadTask(QString)),this,SLOT(addDownloadTask(QString)));
    connect(recommendWidget,SIGNAL(addDownloadTaskSignal(QString)),this,SLOT(addDownloadTask(QString)));

    connect(getNavgationBar(),SIGNAL(indexChanged(int)),this,SLOT(firstLoadList(int)));

    hideMouseTimer = new QTimer;
    connect(hideMouseTimer,SIGNAL(timeout()),this,SLOT(hideMouse()));
    hideMouseTimer->start(500);

    loadDownloadSettings();
}
Ejemplo n.º 14
0
QgsBookmarks::QgsBookmarks( QWidget *parent, Qt::WindowFlags fl )
    : QDialog( parent, fl )
{
  setupUi( this );
  restorePosition();

  //
  // Create the zoomto and delete buttons and add them to the
  // toolbar
  //
  QPushButton *btnAdd    = new QPushButton( tr( "&Add" ) );
  QPushButton *btnDelete = new QPushButton( tr( "&Delete" ) );
  QPushButton *btnZoomTo = new QPushButton( tr( "&Zoom to" ) );
  QPushButton *btnImpExp = new QPushButton( tr( "&Share" ) );

  btnZoomTo->setDefault( true );
  buttonBox->addButton( btnAdd, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnDelete, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnZoomTo, QDialogButtonBox::ActionRole );
  buttonBox->addButton( btnImpExp, QDialogButtonBox::ActionRole );

  QMenu *share = new QMenu();
  QAction *btnExport = share->addAction( tr( "&Export" ) );
  QAction *btnImport = share->addAction( tr( "&Import" ) );
  connect( btnExport, SIGNAL( triggered() ), this, SLOT( exportToXML() ) );
  connect( btnImport, SIGNAL( triggered() ), this, SLOT( importFromXML() ) );
  btnImpExp->setMenu( share );

  connect( btnAdd, SIGNAL( clicked() ), this, SLOT( addClicked() ) );
  connect( btnDelete, SIGNAL( clicked() ), this, SLOT( deleteClicked() ) );
  connect( btnZoomTo, SIGNAL( clicked() ), this, SLOT( zoomToBookmark() ) );

  // open the database
  QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE", "bookmarks" );
  db.setDatabaseName( QgsApplication::qgisUserDbFilePath() );
  if ( !db.open() )
  {
    QMessageBox::warning( this, tr( "Error" ),
                          tr( "Unable to open bookmarks database.\nDatabase: %1\nDriver: %2\nDatabase: %3" )
                          .arg( QgsApplication::qgisUserDbFilePath() )
                          .arg( db.lastError().driverText() )
                          .arg( db.lastError().databaseText() )
                        );
    deleteLater();
    return;
  }

  QSqlTableModel *model = new QSqlTableModel( this, db );
  model->setTable( "tbl_bookmarks" );
  model->setSort( 0, Qt::AscendingOrder );
  model->setEditStrategy( QSqlTableModel::OnFieldChange );
  model->select();

  // set better headers then column names from table
  model->setHeaderData( 0, Qt::Horizontal, tr( "ID" ) );
  model->setHeaderData( 1, Qt::Horizontal, tr( "Name" ) );
  model->setHeaderData( 2, Qt::Horizontal, tr( "Project" ) );
  model->setHeaderData( 3, Qt::Horizontal, tr( "xMin" ) );
  model->setHeaderData( 4, Qt::Horizontal, tr( "yMin" ) );
  model->setHeaderData( 5, Qt::Horizontal, tr( "xMax" ) );
  model->setHeaderData( 6, Qt::Horizontal, tr( "yMax" ) );
  model->setHeaderData( 7, Qt::Horizontal, tr( "SRID" ) );

  lstBookmarks->setModel( model );

  QSettings settings;
  lstBookmarks->header()->restoreState( settings.value( "/Windows/Bookmarks/headerstate" ).toByteArray() );

#ifndef QGISDEBUG
  lstBookmarks->setColumnHidden( 0, true );
#endif
}
Ejemplo n.º 15
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    ApplicationHelper appHelper;

    QObject::connect(&app, SIGNAL(aboutToQuit()), &appHelper, SLOT(aboutToQuit()));
    signal(SIGINT, signalHandler);

    // Set application variables
    QCoreApplication::setApplicationName("pokerspiel-metaserver");
    QCoreApplication::setApplicationVersion("0.1.0");
    QCoreApplication::setOrganizationName("PokerSpielServices");
    QCoreApplication::setOrganizationDomain("pokerspielservices.me");

    // Get command line arguments
    QCommandLineParser parser;
    parser.addHelpOption();
    parser.addVersionOption();

    QCommandLineOption serverPort(QStringList() << "P" << "port",
                                  "Port of the websocket server.",
                                  "ws_port",
                                  WEBSOCKET_PORT);
    parser.addOption(serverPort);
    QCommandLineOption mysqlHost(QStringList() << "h" << "host",
                                  "Hostname for mysql database.",
                                  "mysql_hostname",
                                  MYSQL_HOSTNAME);
    parser.addOption(mysqlHost);
    QCommandLineOption mysqlUsername(QStringList() << "u" << "username",
                                  "Username for mysql database.",
                                  "mysql_username",
                                  MYSQL_USERNAME);
    parser.addOption(mysqlUsername);
    QCommandLineOption mysqlPassword(QStringList() << "p" << "password",
                                  "Password of the mysql database.",
                                  "mysql_password",
                                  MYSQL_PASSWORD);
    parser.addOption(mysqlPassword);
    QCommandLineOption mysqlDatabase(QStringList() << "d" << "database",
                                  "Name of the mysql database.",
                                  "mysql_db",
                                  MYSQL_DB);
    parser.addOption(mysqlDatabase);

    QCommandLineOption jsonLog("json");
    jsonLog.setDescription("Output log in JSON format");
    parser.addOption(jsonLog);

    parser.process(app);

    if (parser.isSet(jsonLog)) {
        appHelper.jsonOutput = true;
        qInstallMessageHandler(jsonOutput);
    } else {
        appHelper.jsonOutput = false;
        qInstallMessageHandler(messageOutput);
    }

    // Connect to database
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName(parser.value(mysqlHost));
    db.setDatabaseName(parser.value(mysqlDatabase));
    db.setUserName(parser.value(mysqlUsername));
    db.setPassword(parser.value(mysqlPassword));
    db.setConnectOptions("MYSQL_OPT_RECONNECT=1");
    if (!db.open()) {
        qFatal("SQL Error: %s", db.lastError().text().toUtf8().constData());
    } else {
        qDebug() << "Connection to MYSQL-Server established (" << db.userName() << "@" << db.hostName() << ")";
    }

    // Start websocket server
    WebSocketServer server(parser.value(serverPort).toUInt());
    Q_UNUSED(server);

    return app.exec();
}
Ejemplo n.º 16
0
// This gets called when the loadbackup.php script is finished
void BrowseBackup::openBackup(QNetworkReply *reply) {

	// Restore interface
	qApp->restoreOverrideCursor();
	busyLoadBackup->hide();
	date->setEnabled(true);
	search->setEnabled(true);
	list->setEnabled(true);
	load->setEnabled(true);
	closeWindow->setEnabled(true);

	// Store reply data
	QString all = reply->readAll();

	// If the reply is anything but a single 1, then something must have gone wrong
	if(all != "1") {

		QMessageBox::critical(this,"ERROR","ERROR: Unable to load backed up data!\n\nError message:\n" + all);
		return;

	}

	// We now need to get the old office pw (stored in plaintext),
	// use it to decrypt the encryption password used at that point,
	// then we re-encrypt it with the current officepw
	// and store it in a file called 'oldpwcrypt' (crypt.cpp will look there for a backup)

	// Connect to the backup database
	ConfigData data(pwOffice);
	SaverDbCred s = data.getDbLogin();
	// We now need the temporary passwords:
	QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",QString("loadbackup%1").arg(qrand()%12345));
	db.setHostName(s.host.data());
	db.setDatabaseName(s.databaseBackup.data());
	db.setUserName(s.username.data());
	db.setPassword(s.password.data());
	db.open();

	// We need these two pw data
	QByteArray oldpwCrypt = "";
	QByteArray oldpwOffice = "";

	QSqlQuery query(db);
	query.prepare("SELECT * FROM `current` WHERE `id` NOT LIKE 'master'");
	query.exec();
	while(query.next()) {

		// Get the pws
		QString txt = query.value(query.record().indexOf("id")).toString();
		if(txt == "office")
			oldpwOffice = query.value(query.record().indexOf("txt")).toByteArray();
		else if(txt == "crypt")
			oldpwCrypt = query.value(query.record().indexOf("txt")).toByteArray();

	}
	query.clear();
	db.close();

	// We first decrypt the old encryption pw with the old pw
	Cryptor crypt(oldpwOffice, true);
	oldpwCrypt = crypt.decrypt(oldpwCrypt).data();

	// Then we re-encrypt it with the current office pw
	crypt.setPassword(pwOffice + pwOffice);
	oldpwCrypt = crypt.encrypt(oldpwCrypt).join("\n").toLatin1();

	// And we write it to the file (crypt.cpp will look there for a backup)
	QFile file(QDir::homePath() + "/.booker/oldpwcrypt");
	if(file.open(QIODevice::WriteOnly)) {
		QTextStream out(&file);
		out << oldpwCrypt;
		file.close();
	}


	// If the browser is not yet set up (first run)
	if(!browseSetup) {

		browseSetup = true;

		// Set up the heading (will hold info that it is a backup and from when)
		heading = new QLabel;
		heading->setStyleSheet("font-weight: bold; color: red; font-size: 12pt");
		// Right beside the info is a close button
		QPushButton *closeBut = new QPushButton("Close Backup");
		closeBut->setStyleSheet("font-weight: bold; font-size: 11.5pt");
		// And the header lay
		QHBoxLayout *headerLay = new QHBoxLayout;
		headerLay->addStretch();
		headerLay->addWidget(heading);
		headerLay->addSpacing(20);
		headerLay->addWidget(closeBut);
		headerLay->addStretch();

		// the two main elements
		BookingsTab *browse = new BookingsTab(pwOffice, true);
		Details *details = new Details(pwOffice, true);
		Tools *tools = new Tools(true);

		// This is the dialog combining the above three elements
		browseDialog = new QDialog;

		// The bookingstab and details are put into a splitter (as in the normal main interface)
		splitter = new QSplitter(Qt::Vertical);
		splitter->addWidget(browse);
		splitter->addWidget(details);

		QVBoxLayout *lay = new QVBoxLayout;
		lay->addLayout(headerLay);
		lay->addWidget(tools);
		lay->addWidget(splitter);
		browseDialog->setLayout(lay);

		// Load empty details
		details->showDetails(browse->bookingsInd->getSelectedData());

		// Button to close dialog
		connect(closeBut, SIGNAL(clicked()), browseDialog, SLOT(close()));

		// click on booking shows details
		connect(browse->bookingsInd, SIGNAL(showDetails(SafeMultiMap)), details, SLOT(showDetails(SafeMultiMap)));
		connect(browse->bookingsGrp, SIGNAL(showDetails(SafeMultiMap)), details, SLOT(showDetails(SafeMultiMap)));

		// tools SIGNALS/SLOTS
		connect(tools, SIGNAL(gotoDate(QDate)), browse, SLOT(gotoDay(QDate)));
		connect(tools, SIGNAL(setFilter(QString)), browse, SLOT(setFilter(QString)));

	}

	// Set heading
	QStringList time = list->selectedItems().at(0)->data(Qt::UserRole).toStringList();
	heading->setText(QString("BACKUP FROM %1, %2 - THIS DATA IS READ-ONLY!").arg(date->getDate().toString("dd/MM/yyyy")).arg(time.join(":").trimmed()));

	// Show in fullscreen
	browseDialog->setWindowState(this->windowState() & ~Qt::WindowMaximized);
	browseDialog->setWindowState(this->windowState() | Qt::WindowMaximized);

	// And adjust the splitter ratios in just a split second
	QTimer::singleShot(50,this,SLOT(adjustSplitterSize()));

	// And eventually show the dialog
	browseDialog->exec();

}
Ejemplo n.º 17
0
void TOSMWidget::loadNData(QString DbFileName)
{
//    TIDs multiusedNodes;

    {
        QSqlDatabase db;
        db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName(DbFileName);
        if (!db.open())
        {
            qDebug() << "!!! Failed to open database !!!";
            exit(0);
        }
        QSqlQuery q(db);
        qDebug() << QTime::currentTime().toString() << " " << "requesting ways...";
        if (!q.exec("select "
                    "w.id way, "
                    "t.value tag, "
                    "tv.value value "
                    "from "
                    "t_ways w "
                    "inner join t_ways_tags wt on w.id = wt.way "
                    "inner join t_tags t on wt.tag = t.id and (t.value in ('highway', 'oneway', 'junction')) "
                    "inner join t_tags_values tv on wt.value = tv.id"
                    ))
        {
            qDebug() << "!!! failed to recieve ways!!" << q.lastError().text();
            return;
        }
        qDebug() << QTime::currentTime().toString() << "receiving ways...";
        while (q.next())
        {
            TID w = q.value(q.record().indexOf("way")).toLongLong();
            QString t = q.value(q.record().indexOf("tag")).toString();
            QString v = q.value(q.record().indexOf("value")).toString();
            if (!nways.contains(w)) nways.insert(w, TNWay(this));
            TNWay * way = &(nways[w]);

            if (v == "motorway") { way->setRoadClass(TNWay::EW_Motorway); }
            if (v == "motorway_link") { way->setRoadClass(TNWay::EW_Motorway); way->setIsLink(true);}
            if (v == "trunk") { way->setRoadClass(TNWay::EW_Trunk); }
            if (v == "trunk_link") { way->setRoadClass(TNWay::EW_Trunk); way->setIsLink(true);}
            if (v == "primary") { way->setRoadClass(TNWay::EW_Primary); }
            if (v == "primary_link") { way->setRoadClass(TNWay::EW_Primary); way->setIsLink(true);}
            if (v == "secondary") { way->setRoadClass(TNWay::EW_Secondary); }
            if (v == "secondary_link") { way->setRoadClass(TNWay::EW_Secondary); way->setIsLink(true);}
            if (v == "tertiary") { way->setRoadClass(TNWay::EW_Tertiary); }
            if (v == "tertiary_link") { way->setRoadClass(TNWay::EW_Tertiary); way->setIsLink(true);}
            if (v == "living_street") { way->setRoadClass(TNWay::EW_LivingStreet); }
            if (v == "pedestrian") { way->setRoadClass(TNWay::EW_Pedestrian); }
            if (v == "residential") { way->setRoadClass(TNWay::EW_Residental); }
            if (v == "unclassified") { way->setRoadClass(TNWay::EW_Unclassified); }
            if (v == "service") { way->setRoadClass(TNWay::EW_Service); }
            if (v == "track") { way->setRoadClass(TNWay::EW_Track); }
            if (v == "bus_guideway") { way->setRoadClass(TNWay::EW_BusGuideway); }
            if (v == "raceway") { way->setRoadClass(TNWay::EW_Raceway); }
            if (v == "road") { way->setRoadClass(TNWay::EW_Road); }
            if (v == "path") { way->setRoadClass(TNWay::EW_Path); }
            if (v == "footway") { way->setRoadClass(TNWay::EW_Footway); }
            if (v == "bridleway") { way->setRoadClass(TNWay::EW_Bridleway); }
            if (v == "steps") { way->setRoadClass(TNWay::EW_Steps); }
            if (v == "cycleway") { way->setRoadClass(TNWay::EW_Cycleway); }
            if (v == "proposed") { way->setRoadClass(TNWay::EW_Proposed); }
            if (v == "construction") { way->setRoadClass(TNWay::EW_Construction); }
            if (v == "escape") { way->setRoadClass(TNWay::EW_Escape); }
            if (t == "oneway")
            {
                if ((v == "yes") || (v == "true") || (v == "true"))
                {
                    way->setOneWay(TNWay::OW_yes_forward);
                }
                if ((v == "-1") || (v == "reverse"))
                {
                    way->setOneWay(TNWay::OW_yes_reverce);
                }
                if (v == "no")
                {
                    way->setOneWay(TNWay::OW_no);
                }
            }
            if (t == "area")
            {
                if ((v == "yes") || (v == "true") || (v == "true"))
                {
                    way->setIsArea(true);
                }
                if ((v == "-1") || (v == "reverse"))
                {
                    way->setIsArea(true);
                }
                if (v == "no")
                {
                    way->setIsArea(false);
                }
            }
        }

        qDebug() << QTime::currentTime().toString() << "requesting nodes...";

        if (!q.exec("select "
                       "w.id way, "
                       "n.lat lat, "
                       "n.lon lon, "
                       "n.id node "
                   "from "
                       "t_ways w "
                       "inner join t_ways_tags wt on w.id = wt.way "
                       "inner join t_tags t on wt.tag = t.id and (t.value = 'highway') "
                       "inner join t_ways_nodes wn on w.id = wn.way "
                       "inner join t_nodes n on n.id = wn.node "
                       "inner join t_tags_values tv on wt.value = tv.id "
//                   "where "
//                    "tv.value not in ("
//                                    "'pedestrian',"
//                                    "'footway',"
//                                    "'path',"
//                                    "'steps',"
//                                    "'construction',"
//                                    "'cycleway',"
//                                    "'proposed',"
//                                    "'platform',"
//                                    "'bridleway',"
//                                    "'piste'"
//                                ") "
//                    "tv.value in ("
    //                "'residental',"
    //                "'service',"
    //                "'living_street',"
    //                "'road',"
//                                    "'motorway',"
//                                    "'motorway_link',"
//                                    "'trunk', "
//                                    "'trunk_link',"
//                                    "'primary',"
//                                    "'primary_link',"
//                                    "'secondary',"
//                                    "'secondary_link',"
//                                    "'tertiary_link',"
//                                    "'tertiary'"
//                                ") "

    //                   "and n.lat > 61.1 and n.lat < 61.2 and n.lon > 62.75 "
                   "order by 1"))

        {
            qDebug() << "!!! Failed to recieve nodes !!! " << q.lastError().driverText() ;
            return;
        }
        bool first = true;
        qDebug() << QTime::currentTime().toString() << " " << "receiving nodes...";
        while (q.next())
        {
    //        qDebug() << "q.next()";
            TID w = q.value(q.record().indexOf("way")).toLongLong();
            TID n = q.value(q.record().indexOf("node")).toLongLong();
            double lat = q.value(q.record().indexOf("lat")).toDouble();
            double lon = q.value(q.record().indexOf("lon")).toDouble();
            QPointF point(lon, lat);
            if (first)
            {
                first = false;
                Rect.setLeft(point.x());
                Rect.setRight(point.x());
                Rect.setTop(point.y());
                Rect.setBottom(point.y());

            }
            else
            {
    //            qDebug() << point;
                Rect.setLeft(std::min(Rect.left(), point.x()));
                Rect.setRight(std::max(Rect.right(), point.x()));
                Rect.setTop(std::min(Rect.top(), point.y()));
                Rect.setBottom(std::max(Rect.bottom(), point.y()));
            }
            if (!nways.contains(w)) nways.insert(w, TNWay(this));
            nways[w].nodes.append(n);
            if (!nnodes.contains(n))
            {
                TNNode NNode(lat, lon);
                nnodes.insert(n, NNode);
            }
            nnodes[n].lat = lat;
            nnodes[n].lon = lon;
            nnodes[n].ownedBy.insert(w);
//            if (nnodes[n].containedBy.size() > 1)
//            {
//                MyCrosses.insert(n);
//            }
        }
        db.close();
    }

//    for (TIDs::Iterator it = MyCrosses.begin(); it != MyCrosses.end(); it++)
//    {
//        for (TIDs::Iterator it_w = nnodes[*it].containedBy.begin(); it_w != nnodes[*it].containedBy.end(); it_w++)
//        {
//            nways[*it_w].
//            nways[*it_w]. (*it);
//        }
//    }



//    Rect.setBottom((Rect.top() + Rect.bottom()) / 2);
//    qDebug() << "rect " << Rect;

//    TIDs checkedNodes;
////    QMap <TID, TID> nodesToMyNodes;

//    qDebug() << QTime::currentTime().toString() << " " << "converting data...";

//    for (TIDsIter it_n = multiusedNodes.begin(); it_n != multiusedNodes.end(); it_n++)
//    {
//        TID nodeId = (*it_n);
//        TNNode *node = &nnodes[nodeId];
//        if (node->containedBy.size() > 1)
//        {
//            TID newMyNodeId = 0;
//            if (!nodesToMyNodes.contains(nodeId))
//            {
//                newMyNodeId = MyNodes.size();
//                nodesToMyNodes.insert(nodeId, newMyNodeId);
//                TNNode newMyNode(node->lat, node->lon);
//                MyNodes.push_back(newMyNode);

//            }
//            else
//            {
//                newMyNodeId = nodesToMyNodes[nodeId];
//            }
////            MyNodes.append(TNNode(node->lat, node->lon));
////            qDebug() << "!!!  NEW multinode (" << node->containedBy.size() << ") " << newMyNodeId;

//            for (TIDsIter it_w = node->containedBy.begin(); it_w != node->containedBy.end(); it_w++)
//            {
//                TNWay *way = &nways[*it_w];
////                qDebug() << " ! next way " << way->nodes << " we need " << nodeId;
////                qDebug() << "<<<";
//                int inode = way->getNodeIndex(nodeId);
////                QList <TID> newWayNodes;
//                bool addThisWay = true;
//                TNWay newMyWay(this);
//                newMyWay.nodes.append(newMyNodeId);
//                for (int i = inode - 1; i >= 0; i--)
//                {
//                    TNNode *waynode = &nnodes[way->nodes[i]];
//                    if (!nodesToMyNodes.contains(way->nodes[i]))
//                    {
//                        nodesToMyNodes.insert(way->nodes[i], MyNodes.size());
//                        TNNode newMyNode(waynode->lat, waynode->lon);
////                        qDebug() << newMyNode.lat << ", " << newMyNode.lon;
//                        MyNodes.push_back(newMyNode);
//                    }
//                    newMyWay.nodes.push_back(nodesToMyNodes[way->nodes[i]]);
//                    if (checkedNodes.contains(way->nodes[i]))
//                    {
//                        addThisWay = false;
////                        qDebug() << "already checked " << nodesToMyNodes[way->nodes[i]];
//                        break;
//                    }
//                    if (waynode->containedBy.size() > 1) break;
//                }
//                if (addThisWay && (newMyWay.nodes.size() > 1))
//                {
//                    MyWays.push_back(newMyWay);
////                    qDebug() << "++ way " << newMyWay.nodes;
//                }
//                else
//                {
////                    qDebug() << "-- way " << newMyWay.nodes << " " << (!addThisWay?"checked":"");
//                }

////                qDebug() << ">>>";
//                addThisWay = true;
//                newMyWay.nodes.clear();
//                newMyWay.nodes.append(newMyNodeId);
//                for (int i = inode + 1; i < way->nodes.size(); i++)
//                {
//                    TNNode *waynode = &nnodes[way->nodes[i]];
//                    if (!nodesToMyNodes.contains(way->nodes[i]))
//                    {
//                        nodesToMyNodes.insert(way->nodes[i], MyNodes.size());
//                        TNNode newMyNode(waynode->lat, waynode->lon);
////                        qDebug() << newMyNode.lat << ", " << newMyNode.lon;
//                        MyNodes.push_back(newMyNode);
//                    }
//                    newMyWay.nodes.push_back(nodesToMyNodes[way->nodes[i]]);
//                    if (checkedNodes.contains(way->nodes[i]))
//                    {
//                        addThisWay = false;
////                        qDebug() << "already checked " << nodesToMyNodes[way->nodes[i]];
//                        break;
//                    }
//                    if (waynode->containedBy.size() > 1) break;
//                }
//                if (addThisWay && (newMyWay.nodes.size() > 1))
//                {
//                    MyWays.push_back(newMyWay);
////                    qDebug() << "++ way " << newMyWay.nodes;
//                }
//                else
//                {
////                    qDebug() << "-- way " << newMyWay.nodes << " " << (!addThisWay?"checked":"");
//                }
//            }
//            checkedNodes.insert(nodeId);
//        }

//    }

//    for (TID i = 0; i < MyWays.size(); i++)
////    for (QList <TNWay>::iterator it_w = MyWays.begin(); it_w != MyWays.end(); it_w++)
//    {
//        TNWay *way = &MyWays[i];
//        for (QList <TID> ::Iterator it = way->nodes.begin(); it != way->nodes.end(); it++)
//        {
//            MyNodes[*it].containedBy.insert(i);
//        }
////        MyNodes[way->nodes.first()].containedBy.insert(i);
////        MyNodes[way->nodes.last()].containedBy.insert(i);
//        MyCrosses.insert(way->nodes.first());
//        MyCrosses.insert(way->nodes.last());
//    }



}
Ejemplo n.º 18
0
//----------------------------------------------------------------------------
void ctkPluginStorageSQL::open()
{
  if (m_isDatabaseOpen)
    return;

  QString path;

  //Create full path to database
  if(m_databasePath.isEmpty ())
    m_databasePath = getDatabasePath();

  path = m_databasePath;
  QFileInfo dbFileInfo(path);
  if (!dbFileInfo.dir().exists())
  {
    if(!QDir::root().mkpath(dbFileInfo.path()))
    {
      close();
      QString errorText("Could not create database directory: %1");
      throw ctkPluginDatabaseException(errorText.arg(dbFileInfo.path()), ctkPluginDatabaseException::DB_CREATE_DIR_ERROR);
    }
  }

  m_connectionName = dbFileInfo.completeBaseName();
  QSqlDatabase database;
  if (QSqlDatabase::contains(m_connectionName))
  {
    database = QSqlDatabase::database(m_connectionName);
  }
  else
  {
    database = QSqlDatabase::addDatabase("QSQLITE", m_connectionName);
    database.setDatabaseName(path);
  }

  if (!database.isValid())
  {
    close();
    throw ctkPluginDatabaseException(QString("Invalid database connection: %1").arg(m_connectionName),
                                  ctkPluginDatabaseException::DB_CONNECTION_INVALID);
  }

  //Create or open database
  if (!database.isOpen())
  {
    if (!database.open())
    {
      close();
      throw ctkPluginDatabaseException(QString("Could not open database. ") + database.lastError().text(),
                                    ctkPluginDatabaseException::DB_SQL_ERROR);
    }
  }
  m_isDatabaseOpen = true;

  //Check if the sqlite version supports foreign key constraints
  QSqlQuery query(database);
  if (!query.exec("PRAGMA foreign_keys"))
  {
    close();
    throw ctkPluginDatabaseException(QString("Check for foreign key support failed."),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }

  if (!query.next())
  {
    close();
    throw ctkPluginDatabaseException(QString("SQLite db does not support foreign keys. It is either older than 3.6.19 or was compiled with SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER"),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }
  query.finish();
  query.clear();

  //Enable foreign key support
  if (!query.exec("PRAGMA foreign_keys = ON"))
  {
    close();
    throw ctkPluginDatabaseException(QString("Enabling foreign key support failed."),
                                  ctkPluginDatabaseException::DB_SQL_ERROR);
  }
  query.finish();


  //Check database structure (tables) and recreate tables if neccessary
  //If one of the tables is missing remove all tables and recreate them
  //This operation is required in order to avoid data coruption
  if (!checkTables())
  {
    if (dropTables())
    {
      createTables();
    }
    else
    {
      //dropTables() should've handled error message
      //and warning
      close();
    }
  }

  // silently remove any plugin marked as uninstalled
  cleanupDB();

  //Update database based on the recorded timestamps
  updateDB();

  initNextFreeIds();
}
Ejemplo n.º 19
0
void FrmCompras_cls::on_btn_comprar_clicked()
{
	{
	
		QString verify = ui_edt_idpro -> text();
		if (verify ==""){
		QMessageBox::information(this, tr("Mensagem!"),
			tr("Por Favor Localize o Produto\n"
				"a ser (Comprado) Obrigado!..."));			
			
		}else{
			QSqlDatabase db ;		
			db = QSqlDatabase::addDatabase("QMYSQL","01");
			db.setHostName(my_hostname);
			db.setDatabaseName(my_database);
			db.setUserName(my_username);
			db.setPassword(my_password);			
			bool ok = db.open();
			db = QSqlDatabase::database("01");		
			QSqlQuery query = QSqlQuery::QSqlQuery(db);

			QString idpro = ui_edt_idpro -> text();
			QString sqlvery = "Select * from estoque where pro_id="+idpro;

			query.exec(sqlvery);
			QString qtd_pro;
			while (query.next()) {
				qtd_pro = query.value(2).toString();					
			};
			int nraff = query.numRowsAffected();

			if (nraff > 0){
				QString qtdpro = ui_edt_qtdpro -> text();
				QString vlrpro = ui_edt_vlrpro -> text();
				QString vlrtotal = ui_edt_vlrtotal -> text();
				QString sqlcompras = "insert into compras (cmp_id,pro_id,pro_qtd,vlr_unit,vlr_total)Values(0,'"+idpro+"','"+qtdpro+"','"+vlrpro+"','"+vlrtotal+"')";

				int qtd1 = qtd_pro.toInt();
				int qtd2 = qtdpro.toInt();
				int qtdtotal = qtd1+qtd2;

				QVariant qtdUp;
				qtdUp = qtdtotal;
				QString qtdTotalUp = qtdUp.toString();

				QString sqlup = "UPDATE estoque SET pro_qtd = '"+qtdTotalUp+"' where pro_id ="+idpro;
				query.exec(sqlcompras);
				query.exec(sqlup);

				db.close();		
				QMessageBox::information(this, tr("Mensagem!"),
					"Compra Realizada com Sucesso!\n"
					"Produtos Adicionados no Estoque = "+qtdpro+"");			
				limpar_cmp();


			}else{
				QString qtdpro = ui_edt_qtdpro -> text();
				QString vlrpro = ui_edt_vlrpro -> text();
				QString vlrtotal = ui_edt_vlrtotal -> text();
				QString sqlcompras2 = "insert into compras (cmp_id,pro_id,pro_qtd,vlr_unit,vlr_total)Values(0,'"+idpro+"','"+qtdpro+"','"+vlrpro+"','"+vlrtotal+"')";

				QString sqlestoque = "insert into estoque (estq_id,pro_id,pro_qtd)Values(0,'"+idpro+"','"+qtdpro+"')";

				query.exec(sqlcompras2);
				query.exec(sqlestoque);
				db.close();		
				QMessageBox::information(this, tr("Mensagem!"),
					"Compra Realizada com Sucesso!\n"
					"Produtos Cadastrados no Estoque = "+qtdpro+"");			
				limpar_cmp();
			     }
	    	     }
	}
 
	 QSqlDatabase::removeDatabase("01"); // correct
	 


}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    qDebug() << QSqlDatabase::drivers();

    QSqlDatabase db = QSqlDatabase::addDatabase("SQLITECIPHER");
    db.setUserName("hrono");
    db.setPassword("password");
    db.setDatabaseName("storage.db");

    if (!db.open()) {
        qDebug() << "Can not open connection.";
        exit(CONNECTION_FAILED);
    }

    QSqlQuery query;
    QSqlError errordb,errorqr;
    query.exec("drop table permissions");
    query.exec("drop table users");
    query.exec("drop table sasha");
    query.exec("drop table pasha");
     if ( !query.exec("create table users (client_id integer PRIMARY KEY AUTOINCREMENT, login text not null, pass text not null)")){
       errorqr=query.lastError();
       errordb=db.lastError();
       cout<<"Ни в какие ворота! Я покидаю это бренное ядро  № "<<errordb.number()<<"\n";
       qDebug() << "\n""Can not create table.  "<<
                errordb.text()
                <<errorqr.text();
     query.exec("drop table users");
     exit(CONNECTION_FAILED);
    }
     if (! query.exec("insert into users (login,pass) values ('sasha', '123')")){
        errorqr=query.lastError();
        errordb=db.lastError();
        qDebug() << "\n Can not insert into table.  "
                 <<errordb.text()
                 <<errorqr.text();
      query.exec("drop table users");
      exit(CONNECTION_FAILED);
     }
           query.exec("insert into users (login,pass) values ('pasha', '123')");

    query.exec("select client_id, login, pass from users");
    while (query.next()) {
    qDebug() << query.value(0).toInt() << ": " << query.value(1).toString()<<" "<< query.value(2).toString();
    }

     if ( !query.exec("create table permissions (client_id integer not null,table_id int not null)")){
       errorqr=query.lastError();
       errordb=db.lastError();
       qDebug() << "\n""Can not create table permissions.  "<<
                errordb.text()
                <<errorqr.text();
    query.exec("drop table permissions");
     exit(CONNECTION_FAILED);
     }
     if (! query.exec("insert into permissions (client_id,table_id) values ('1', '1')")){
        errorqr=query.lastError();
        errordb=db.lastError();
        qDebug() << "\n Can not insert into table permissions.  "
                 <<errordb.text()
                 <<errorqr.text();
      query.exec("drop table permissions");
      exit(CONNECTION_FAILED);
     }
           query.exec("insert into permissions (client_id,table_id) values ('1', '2')");
           query.exec("insert into permissions (client_id,table_id) values ('2', '2')");

    query.exec("select client_id, table_id from permissions");
    while (query.next()) {
   qDebug() << query.value(0).toInt() << ": "<< query.value(1).toInt();
   }

    if ( !query.exec("create table sasha (name text not null, data blob not null)")){
      errorqr=query.lastError();
      errordb=db.lastError();
      qDebug() << "\n""Can not create table sasha.  "<<
               errordb.text()
               <<errorqr.text();
    query.exec("drop table sasha");
    }

    if ( !query.exec("create table pasha (name text not null, data blob not null)")){
      errorqr=query.lastError();
      errordb=db.lastError();
      qDebug() << "\n""Can not create table pasha.  "<<
               errordb.text()
               <<errorqr.text();
    query.exec("drop table pasha");
        exit(CONNECTION_FAILED);
    }

    db.close();

    return app.exec();
}
Ejemplo n.º 21
0
void DatabaseManager::initDatabase(QSqlDatabase &database)
{
    QSqlQuery query(database);

    //to speed things massively up
    //move operations in one big transaction
    database.transaction();

    //create collections table
    query.exec(SQL_CREATE_TABLE_COLLECTIONS);

    //create info table
    query.exec(SQL_CREATE_TABLE_INFO);

    //create file table
    query.exec(SQL_CREATE_TABLE_FILES);

    //create alarm table
    query.exec(SQL_CREATE_TABLE_ALARMS);

    //init info data
    query.prepare("INSERT INTO \"symphytum_info\" (\"key\",\"value\") VALUES"
                  "(\"db_version\", :version)");
    query.bindValue(":version", DefinitionHolder::DATABASE_VERSION);
    query.exec();

    //init example data
    query.exec("INSERT INTO \"collections\" (\"name\",\"type\",\"table_name\")"
               " VALUES (\"Medicinal Plants\",1,\"cb92ee55f44577b584464c13f47fa3771\")");
    query.exec("CREATE TABLE \"cb92ee55f44577b584464c13f47fa3771\" (\"_id\" "
               "INTEGER PRIMARY KEY , \"1\" TEXT, \"2\" TEXT, \"3\" TEXT, \"4\" INTEGER,"
               " \"5\" INTEGER, \"6\" INTEGER)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771\" "
               "VALUES (\"1\",\"Symphytum officinale\",\"Synthesis, Recovery\",\"Painkiller,"
               " anti-inflammatory property on skin and mucosae\",\"1\",\"1\",\"1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771\" VALUES (\"2\",\"Calendula"
               " officinalis\",\"Healing, Wound healing\",\"Stomach discomfort, "
               "severe wounds, soul injury\",\"2\",\"0\",\"2\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771\" VALUES "
               "(\"3\",\"Coffea arabica\",\"Radical change, Adaption\",\"Balance "
               "of neurotransmitters, nervous system, heart, circulation, "
               "leave illusions, liberation\",\"0\",\"1\",\"3\")");
    query.exec("CREATE TABLE \"cb92ee55f44577b584464c13f47fa3771_metadata\""
               " (\"_id\" INTEGER PRIMARY KEY , \"key\" TEXT, \"value\" TEXT)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"1\",\"column_count\",\"7\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"2\",\"col1_pos\",\"0;0\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"3\",\"col1_size\",\"1;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"4\",\"col1_display\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"5\",\"col1_edit\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"6\",\"col1_trigger\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"7\",\"col1_name\",\"Name\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"8\",\"col1_type\",\"1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"9\",\"col2_pos\",\"1;0\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"10\",\"col2_size\",\"1;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"11\",\"col2_display\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"12\",\"col2_edit\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"13\",\"col2_trigger\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"14\",\"col2_name\",\"Keywords\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"15\",\"col2_type\",\"1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"16\",\"col3_pos\",\"0;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"17\",\"col3_size\",\"1;2\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"18\",\"col3_display\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"19\",\"col3_edit\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"20\",\"col3_trigger\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"21\",\"col3_name\",\"Healing effect\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"22\",\"col3_type\",\"1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"23\",\"col4_pos\",\"1;2\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"24\",\"col4_size\",\"1;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"25\",\"col4_display\",\"items:10 ml,30 ml,50 ml;\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"26\",\"col4_edit\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"27\",\"col4_trigger\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"28\",\"col4_name\",\"Recommended dosage\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"29\",\"col4_type\",\"7\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"30\",\"col5_pos\",\"1;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"31\",\"col5_size\",\"1;1\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"32\",\"col5_display\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"33\",\"col5_edit\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"34\",\"col5_trigger\",null)");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"35\",\"col5_name\",\"Harvest before bloom\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"36\",\"col5_type\",\"6\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"37\",\"col6_pos\",\"2;0\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"38\",\"col6_size\",\"1;3\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"39\",\"col6_display\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"40\",\"col6_edit\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"41\",\"col6_trigger\",\"\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"42\",\"col6_name\",\"Photo\")");
    query.exec("INSERT INTO \"cb92ee55f44577b584464c13f47fa3771_metadata\" VALUES (\"43\",\"col6_type\",\"9\")");
    query.exec("INSERT INTO \"files\" VALUES (\"1\",\"symphytum.jpg\",\"25993661ea0bdede9699836f9ba0956b.jpg\",\"2012-12-01T16:00:00\")");
    query.exec("INSERT INTO \"files\" VALUES (\"2\",\"calendula.jpg\",\"81f87c38d8fd4cff00f35847e454e753.jpg\",\"2012-12-01T16:00:00\")");
    query.exec("INSERT INTO \"files\" VALUES (\"3\",\"coffea.jpg\",\"fd461a1f28d6682993422d65dafa2ddf.jpg\",\"2012-12-01T16:00:00\")");
    query.exec("INSERT INTO \"symphytum_info\" (\"key\",\"value\") VALUES (\"current_collection\",\"1\")");

    if (!database.commit()) {
        QString err = query.lastError().text();
        QMessageBox::critical(0, QObject::tr("Database Error"),
                              QObject::tr("Failed to initialize "
                                          "the database: %1")
                              .arg(err));
    }

    //copy example files
    QString filesDir = FileManager().getFilesDirectory();
    QFile::copy(":/images/sample/symphytum.jpg", filesDir + "25993661ea0bdede9699836f9ba0956b.jpg");
    QFile::copy(":/images/sample/calendula.jpg", filesDir + "81f87c38d8fd4cff00f35847e454e753.jpg");
    QFile::copy(":/images/sample/coffea.jpg", filesDir + "fd461a1f28d6682993422d65dafa2ddf.jpg");
}
Ejemplo n.º 22
0
bool closeConnection( QSqlDatabase db ){
    db.close();
}
Ejemplo n.º 23
0
SqlQuery::SqlQuery(const QSqlDatabase& db) :
    QSqlQuery( db ), m_db(db)
{
    m_connectionName = db.connectionName();
    SqlQueryManager::instance()->registerQuery(this);
}
Ejemplo n.º 24
0
double _createRtree(){
    //    QString query = "SELECT c.id, c.ctid, ST_AsText(c.geoloc), sum(sa.sale_total)  ";
    //    query += "FROM clients c JOIN sales sa ON c.id = sa.client_id, ibge_sectors i  ";
    //    query += "WHERE ST_Contains(i.area_polyg, c.geoloc)  ";
    //    query += "GROUP BY c.id LIMIT 100000;";

    QString query = "SELECT c.id, ST_AsText(c.geoloc)  ";
    query += "FROM clients c  ";
    query += "WHERE geoloc IS NOT NULL;";


    logger.message("METHOD _createRtree");

    logger.message(query.toStdString().c_str());

    int counter = 0;

    QSqlDatabase db = openConnection();

    QSqlQuery qsq;
    qsq.prepare(query);

    if (qsq.exec()) {

//        myBasicArrayObjectRTree **rows;
//        rows = new myBasicArrayObjectRTree*[qsq.numRowsAffected()];
        logger.message("Adding nodes to the rtree");


        // Rtree Instatiation
        myBasicMetricEvaluator *me = new myBasicMetricEvaluator();
        stDiskPageManager *pmR = new stDiskPageManager("/var/lib/postgresql/artree.dat", 1024);
        myRTree *rtree = new myRTree(pmR);
        rtree->SetQueryMetricEvaluator(me);
        rtree->SetSplitMethod(myRTree::smQUADRATIC); // smLINEAR, smQUADRATIC, smEXPONENTIAL

        myBasicArrayObjectRTree *aux = new myBasicArrayObjectRTree(2);

        while (qsq.next() && qsq.isValid()) {
            //Getting the values from the record
            QString oid = qsq.value(0).toString();
            //                QString ctid = qsq.value(1).toString();
            QString point = qsq.value(1).toString();
            //                QString sumSales = qsq.value(3).toString();


//            float *latlon = new float[2];
            point.replace(QString("POINT("), QString(""));
            point.replace(QString(")"), QString(""));
            QStringList listLatLon = point.split(" ");
//            latlon[0] = listLatLon.at(0).toFloat();
//            latlon[1] = listLatLon.at(1).toFloat();
            aux->Set(0, listLatLon.at(0).toFloat());
            aux->Set(1, listLatLon.at(1).toFloat());
            aux->SetOID(oid.toInt());
            rtree->Add(aux);

//            rows[counter] = new myBasicArrayObjectRTree(2, latlon);
//            rows[counter]->SetOID(oid.toInt());
//            rtree->Add(rows[counter++]);

        }
        logger.message("DONE! Adding nodes to the rtree");



        closeConnection(db);
        delete rtree;
        delete pmR;
        delete me;
        delete aux;
//        delete[] rows;
    }else{
        logger.error(db.lastError().text().toStdString().c_str());
    }

    return (double) counter;
}
Ejemplo n.º 25
0
QSqlDatabase QgsDb2Provider::getDatabase( const QString &connInfo, QString &errMsg )
{
  QSqlDatabase db;
  QString service;
  QString driver;
  QString host;
  QString databaseName;
  QString port;
  QString userName;
  QString password;
  QString connectionName;
  QString connectionString;

  QgsDataSourceUri uri( connInfo );
  // Fill in the password if authentication is used
  QString expandedConnectionInfo = uri.connectionInfo( true );
  QgsDebugMsg( "expanded connInfo: " + expandedConnectionInfo );
  QgsDataSourceUri uriExpanded( expandedConnectionInfo );

  userName = uriExpanded.username();
  password = uriExpanded.password();
  service = uriExpanded.service();
  databaseName = uriExpanded.database();
  host = uriExpanded.host();
  port = uriExpanded.port();
  driver = uriExpanded.driver();
  QgsDebugMsg( QString( "driver: '%1'; host: '%2'; databaseName: '%3'" ).arg( driver, host, databaseName ) );
  if ( service.isEmpty() )
  {
    if ( driver.isEmpty() || host.isEmpty() || databaseName.isEmpty() )
    {
      QgsDebugMsg( "service not provided, a required argument is empty." );
      return db;
    }
    connectionName = databaseName + ".";
  }
  else
  {
    connectionName = service;
  }
  QgsDebugMsg( "connectionName: " + connectionName );
  /* if new database connection */
  if ( !QSqlDatabase::contains( connectionName ) )
  {
    QgsDebugMsg( "new connection. create new QODBC mapping" );
    db = QSqlDatabase::addDatabase( QStringLiteral( "QODBC3" ), connectionName );
  }
  else  /* if existing database connection */
  {
    QgsDebugMsg( "found existing connection, use the existing one" );
    db = QSqlDatabase::database( connectionName );
  }
  db.setHostName( host );
  db.setPort( port.toInt() );
  bool connected = false;
  int i = 0;
  QgsCredentials::instance()->lock();
  while ( !connected && i < 3 )
  {
    i++;
    // Don't prompt if this is the first time and we have both userName and password
    // This is needed for Python or any non-GUI process
    if ( userName.isEmpty() || password.isEmpty() || ( !connected && i > 1 ) )
    {
      bool ok = QgsCredentials::instance()->get( databaseName, userName,
                password, errMsg );
      if ( !ok )
      {
        errMsg = QStringLiteral( "Cancel clicked" );
        QgsDebugMsg( errMsg );
        QgsCredentials::instance()->unlock();
        break;
      }
    }

    db.setUserName( userName );
    db.setPassword( password );

    /* start building connection string */
    if ( service.isEmpty() )
    {
      connectionString = QString( "Driver={%1};Hostname=%2;Port=%3;"
                                  "Protocol=TCPIP;Database=%4;Uid=%5;Pwd=%6;" )
                         .arg( driver,
                               host )
                         .arg( db.port() )
                         .arg( databaseName,
                               userName,
                               password );
    }
    else
    {
      connectionString = service;
    }
    QgsDebugMsg( "ODBC connection string: " + connectionString );

    db.setDatabaseName( connectionString ); //for QODBC driver, the name can be a DSN or connection string
    if ( db.open() )
    {
      connected = true;
      errMsg = QLatin1String( "" );
    }
    else
    {
      errMsg = db.lastError().text();
      QgsDebugMsg( "DB not open" + errMsg );
    }
  }
  if ( connected )
  {
    QgsCredentials::instance()->put( databaseName, userName, password );
  }
  QgsCredentials::instance()->unlock();

  return db;
}
Ejemplo n.º 26
0
void login::sLogin()
{
  QSqlDatabase db;

// Open the Database Driver
  if (_splash)
  {
    _splash->show();
    _splash->showMessage(tr("Initializing the Database Connector"));
    qApp->processEvents();
  }

  QString databaseURL;
  databaseURL = _databaseURL;
  QString protocol;
  QString hostName;
  QString dbName;
  QString port;
  db = databaseFromURL( databaseURL );
  if (!db.isValid())
  {
    QMessageBox::warning( this, tr("No Database Driver"),
                          tr( "A connection could not be established with the specified\n"
                              "Database as the Proper Database Drivers have not been installed.\n"
                                 "Contact your Systems Administrator.\n"  ));
    
    if (_splash)
      _splash->hide();
    
    return;
  }

//  Try to connect to the Database
  _cUsername = _username->text().trimmed();
  _cPassword = _password->text().trimmed();

  db.setUserName(_cUsername);
  db.setPassword(_cPassword);
  setCursor(QCursor(Qt::WaitCursor));

  if (_splash)
  {
    _splash->showMessage(tr("Connecting to the Database"));
    qApp->processEvents();
  }
  
  bool result = db.open();

  if (!result)
  {
    if (_splash)
      _splash->hide();
    
    setCursor(QCursor(Qt::ArrowCursor));

    QMessageBox::critical( this, tr("Cannot Connect to Database Server"),
                           tr( "A connection to the specified Database Server cannot be made.  This may be due to an\n"
                               "incorrect Username and/or Password or that the Database Server in question cannot\n"
                               "support anymore connections.\n\n"
                               "Please verify your Username and Password and try again or wait until the specified\n"
                               "Database Server is less busy.\n\n"
                               "System Error '%1'\n%2" ).arg(db.lastError().text(), db.lastError().driverText()));
    if (!_captive)
    {
      _username->setText("");
      _username->setFocus();
    }
    else
      _password->setFocus();

    _password->setText("");
    return;
  }

  if (_splash)
  {
    _splash->showMessage(tr("Logging into the Database"));
    qApp->processEvents();
  }
  
  setCursor(QCursor(Qt::ArrowCursor));
  accept();
}
Ejemplo n.º 27
0
void MainWindow::setup()
{

    bool ok;
    QString host, user, pw, dBase;

    QFile file;

    if (lv=="BATCH" || lv == "BATCHNORM")
    {
      file.setFileName("/home/joe/git/accompany/UHCore/Core/config/database.yaml");
    }
    else
    {
      file.setFileName("../UHCore/Core/config/database.yaml");
    }

    if (!file.exists())
    {
       qDebug()<<"No database config found!!";
    }

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        closeDownRequest = true;
        return;
    }

    QTextStream in(&file);
    while (!in.atEnd())
    {
       QString line = in.readLine();

       if (line.startsWith("mysql_log_user"))
       {
          user = line.section(":",1,1).trimmed();
       }
       if (line.startsWith("mysql_log_password"))
       {
           pw = line.section(":",1,1).trimmed();
       }
       if (line.startsWith("mysql_log_server"))
       {
          host = line.section(":",1,1).trimmed();
       }
       if (line.startsWith("mysql_log_db"))
       {
          dBase = line.section(":",1,1).trimmed();
       }
    }
    qDebug()<<lv << "," << user << "," << host << "," << dBase;

    if (lv != "BATCH" && lv!= "BATCHNORM")
    {
    user = QInputDialog::getText ( this, "Accompany DB", "User:"******"Accompany DB", "Password:"******"Accompany DB", "Host:",QLineEdit::Normal,
                                     host, &ok);
    if (!ok)
    {
      closeDownRequest = true;
      return;
    };

    dBase = QInputDialog::getText ( this, "Accompany DB", "Database:",QLineEdit::Normal,
                                     dBase, &ok);
    if (!ok)
    {
      closeDownRequest = true;
      return;
    };

    }


    ui->locnLabel->setText(lv + ":" + user + ":" + host + ":" + dBase);


    db = QSqlDatabase::addDatabase("QMYSQL");

    db.setHostName(host);
    db.setDatabaseName(dBase);
    db.setUserName(user);
    db.setPassword(pw);

    dbOpen = db.open();

    if (!dbOpen)
    {

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Database error - login problem - see console log!");
        msgBox.exec();

        qCritical("Cannot open database: %s (%s)",
                  db.lastError().text().toLatin1().data(),
                  qt_error_string().toLocal8Bit().data());

        closeDownRequest = true;

        return;
    }
    else
    {
        qDebug() << "Database Opened";
    }

    // get experimental location


    QSqlQuery expQuery("SELECT ExperimentalLocationId  FROM SessionControl WHERE SessionId = 1 LIMIT 1");

    if (expQuery.next())
    {
       experimentLocation = expQuery.value(0).toString();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Can find session control table!");
        msgBox.exec();
        closeDownRequest = true;
        return;
    }


    QString seqQuery;

    // get the date of the latest row in sensorStateHistory

    seqQuery = "select max(lastUpdate) from SensorStateHistory";
    query = seqQuery;

    if (!query.exec())
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);

        msgBox.setText("Cannot select from SensorStateHistory table!");
        msgBox.exec();
        return;
    }

    while (query.next())
    {
        latestStateDate = query.value(0).toDateTime();
    }

    ui->inflatePushButton->setEnabled(false);

//    QDateTime Test = QDateTime(QDate(2014,3,19),QTime(13,0,0));
    QDateTime Test1 = QDateTime(QDate(2030,01,01),QTime(0,0,0));


    ui->dateFrom->setDateTime(latestStateDate);
 //   ui->dateTo->setDateTime(latestStateDate);

 //     ui->dateFrom->setDateTime(Test);
      ui->dateTo->setDateTime(Test1);

      behTable = "BehaviourLog";

      if (lv=="BATCH")
      {
          behTable = "BehaviourLog";
          fillSensorStateTable();
          closeDownRequest = true;

      }

      if (lv=="BATCHNORM")
      {
          behTable = "NormBehaviourLog";
          on_inflatePushButton_clicked();  // create sensor states for every 1 second
          fillSensorStateTable();         // update the state table from the behaviourlog
          closeDownRequest = true;

      }

}
Ejemplo n.º 28
0
int main(int argc, char * argv[]){
    /* первым делом создадим директорию для работы нашей проги */
    pathDBfile = QDir::toNativeSeparators(QDir::homePath()) + separator + ".dplayer";

    if (!QDir(pathDBfile).exists()) {
        qDebug() << "path programm not exists! Create...";
        QDir().mkdir(pathDBfile);
    }

    /* вторым делом подготовим таблицы */
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(pathDBfile + separator + "dbplayer.db");
    if (!db.open()) {
        QString message = db.lastError().text();
        qDebug() << "DB error: " << message;
    }
    QSqlQuery a_query(db);
    QString str = "CREATE TABLE IF NOT EXISTS file ("
        "id integer PRIMARY KEY AUTOINCREMENT NOT NULL, "
        "name VARCHAR(255), "
        "create_date DATETIME"
        ");";
    bool b = a_query.exec(str);
    if (!b) {
        QString message = db.lastError().text();
        qDebug() << "DB Create table [file] error: " << message;
    }
    str = "CREATE TABLE IF NOT EXISTS conf ("
        "name VARCHAR(255) PRIMARY KEY NOT NULL, "
        "value VARCHAR(255) "
        ");";
    b = a_query.exec(str);
    if (!b) {
        QString message = db.lastError().text();
        qDebug() << "DB Create table [file] error: " << message;
    }
    db.close();     // закроем подключение к базе
    /* конец создания таблиц */

    /* инициализируем гуи */
    QGuiApplication app(argc, argv);
    QQmlEngine engine;

    QStringList dataList;
    dataList.append("Item 1");
    dataList.append("Item 2");
    dataList.append("Item 3");
    dataList.append("Item 4");
    //QQmlContext *ctxt = engine.rootContext();
    engine.rootContext()->setContextProperty("myModel", QVariant::fromValue(dataList));

    QQmlComponent component(&engine, QUrl(QStringLiteral("qrc:/main.qml")));


    /* маппим объекты GML с нашими классами */
    QObject * object = component.create();
    watcherTxtDrive chekUSB;
    chekUSB.txtDrive = object->findChild<QObject *>("txtDrive");
    chekUSB.txtMemo = object->findChild<QObject *>("txtMemo");

    /* нужно просканировать наличие УЖЕ подключенных съемных дисков WIN32*/
    QFileInfoList drivers = QDir::drives();
    foreach(QFileInfo drive, drivers) {
        chekUSB.slotDeviceAdded(drive.absoluteFilePath());
    }
Ejemplo n.º 29
0
void MainWindow::setup()
{

    bool ok;
    QString host, user, pw, dBase;

    user = QInputDialog::getText ( this, "Accompany DB", "User:"******"", &ok);
    if (!ok)
    {
       closeDownRequest = true;
       return;
    }


    pw = QInputDialog::getText ( this, "Accompany DB", "Password:"******"", &ok);
    if (!ok)
    {
       closeDownRequest = true;
       return;
    }


    host = QInputDialog::getText ( this, "Accompany DB", "Host:",QLineEdit::Normal,
                                   "", &ok);
    if (!ok)
    {
       closeDownRequest = true;
       return;
    };

    dBase = QInputDialog::getText ( this, "Accompany DB", "Database:",QLineEdit::Normal,
                                   "", &ok);
    if (!ok)
    {
       closeDownRequest = true;
       return;
    };

    ui->locnLabel->setText(lv);

    if (lv=="ZUYD")
    {
       if (host=="") host = "accompany1";
       if (user=="") user = "******";
       if (pw=="") pw = "accompany";

    }
    else
    {
        if (host=="") host = "localhost";
        if (user=="") user = "******";
        if (pw=="") pw = "waterloo";
    }

    if (dBase=="")  dBase = "Accompany";


    ui->userLabel->setText(user + ":" + host);


    db = QSqlDatabase::addDatabase("QMYSQL");

    db.setHostName(host);
    db.setDatabaseName(dBase);
    db.setUserName(user);
    db.setPassword(pw);

    dbOpen = db.open();

    if (!dbOpen)
    {

        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Database error - login problem - see console log!");
        msgBox.exec();

        qCritical("Cannot open database: %s (%s)",
                  db.lastError().text().toLatin1().data(),
                  qt_error_string().toLocal8Bit().data());

        closeDownRequest = true;

        return;
    }
    else
    {
        qDebug() << "Database Opened";
    }

    // get experimental location


    QSqlQuery query("SELECT ExperimentalLocationId,Sessionuser  FROM SessionControl WHERE SessionId = 1 LIMIT 1");

    if (query.next())
    {
       experimentLocation = query.value(0).toInt();
       sessionUser = query.value(1).toString();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Cant find session control table!");
        msgBox.exec();
        closeDownRequest = true;
        return;
    }

    // get language

    query = "SELECT languageId FROM Users where userId = " + sessionUser + " LIMIT 1";

    if (query.next())
    {
       languageId = query.value(0).toString();
    }
    else
    {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Critical);

        msgBox.setText("Cant find users table!");
        msgBox.exec();
        closeDownRequest = true;
        return;
    }

    fillAPTextCombo();
    fillAPPredicates();
    fillDisplayArea();

 }
Ejemplo n.º 30
0
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QTextCodec::setCodecForLocale(QTextCodec::codecForLocale());
    QSqlDatabase db =QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("easybook-3313b0");          //设置数据库主机名
    db.setDatabaseName("qtDB.db");              //设置数据库名
    db.setUserName("zhouhejun");                //设置数据库用户名
    db.setPassword("123456");                   //设置数据库密码
    db.open();                             		//打开连接

    //创建数据库表
    QSqlQuery query;
    bool success=query.exec("create table automobil(id int primary key,attribute varchar,type varchar,kind varchar,nation int,carnumber int,elevaltor int,distance int,oil int,temperature int)");
    if(success)
        qDebug()<<QObject::tr("数据库表创建成功!\n");
    else
        qDebug()<<QObject::tr("数据库表创建失败!\n");

    //查询
    query.exec("select * from automobil");
    QSqlRecord rec = query.record();
    qDebug() << QObject::tr("automobil表字段数:" )<< rec.count();

    //插入记录
    QTime t;
    t.start();
    query.prepare("insert into automobil values(?,?,?,?,?,?,?,?,?,?)");

    long records=100;
    for(int i=0;i<records;i++)
    {
        query.bindValue(0,i);
        query.bindValue(1,"四轮");
        query.bindValue(2,"轿车");
        query.bindValue(3,"富康");
        query.bindValue(4,rand()%100);
        query.bindValue(5,rand()%10000);
        query.bindValue(6,rand()%300);
        query.bindValue(7,rand()%200000);
        query.bindValue(8,rand()%52);
        query.bindValue(9,rand()%100);

        success=query.exec();
        if(!success)
        {
            QSqlError lastError=query.lastError();
            qDebug()<<lastError.driverText()<<QString(QObject::tr("插入失败"));
        }
    }
    qDebug()<<QObject::tr("插入 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());

    //排序
    t.restart();
    success=query.exec("select * from automobil order by id desc");
    if(success)
        qDebug()<<QObject::tr("排序 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());
    else
        qDebug()<<QObject::tr("排序失败!");

    //更新记录
    t.restart();
    for(int i=0;i<records;i++)
    {
       query.clear();
       query.prepare(QString("update automobil set attribute=?,type=?,"
                             "kind=?,nation=?,"
                             "carnumber=?,elevaltor=?,"
                             "distance=?,oil=?,"
                             "temperature=? where id=%1").arg(i));

       query.bindValue(0,"四轮");
       query.bindValue(1,"轿车");
       query.bindValue(2,"富康");
       query.bindValue(3,rand()%100);
       query.bindValue(4,rand()%10000);
       query.bindValue(5,rand()%300);
       query.bindValue(6,rand()%200000);
       query.bindValue(7,rand()%52);
       query.bindValue(8,rand()%100);

       success=query.exec();
       if(!success)
       {
           QSqlError lastError=query.lastError();
           qDebug()<<lastError.driverText()<<QString(QObject::tr("更新失败"));
       }
    }
    qDebug()<<QObject::tr("更新 %1 条记录,耗时:%2 ms").arg(records).arg(t.elapsed());

    //删除
    t.restart();
    query.exec("delete from automobil where id=15");
    qDebug()<<QObject::tr("删除一条记录,耗时:%1 ms").arg(t.elapsed());

    return 0;
    //return a.exec();
}