void Calendar::initDatabase() { QFile dbFile("data.db"); if(dbFile.exists()) { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName("data.db"); m_db.open(); qDebug() << "Database oppened."; } else { m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName("data.db"); m_db.open(); QSqlQuery createTable(m_db); createTable.exec("CREATE TABLE events(empty_place TEXT NULL, name TEXT NULL, description TEXT NULL, date_time DATETIME)"); qDebug() << "Database created."; } m_sqlTableModel = new QSqlTableModel(this, m_db); m_sqlTableModel->setTable("events"); m_sqlTableModel->setSort(3, Qt::AscendingOrder); m_sqlTableModel->select(); }
bool DatabaseManager::openDB(QString filePath) { if (!QSqlDatabase::contains()) { // Find QSLite driver QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", DB_CONNECTION_NAME); if (filePath.isEmpty()) { // Set database file name and path filePath = QDesktopServices::storageLocation(QDesktopServices::DataLocation); if (!QDir(filePath).exists()) { // It doesn't exist, we have to create it. if (!QDir().mkpath(filePath)) { // Can't create directory, try to use application one (this may work in windows) filePath = QCoreApplication::applicationFilePath(); } } filePath.append(QDir::separator()).append("personal-qt.sqlite3"); } filePath = QDir::toNativeSeparators(filePath); db.setDatabaseName(filePath); qDebug() << QString("Database file : %1").arg(filePath); QFile dbFile(db.databaseName()); if (!dbFile.exists() || dbFile.size() <= 0) { qDebug() << "database does not exist or is corrputed. I'll try to create it."; if (!createDB()) { qDebug() << "ERROR: Can't create a new database!"; return false; } } else { qDebug() << "OK, database already exists."; } // Open databasee if (!db.open()) { qDebug() << "ERROR: Can't open database!"; qDebug() << db.lastError().text(); return false; } } return true; }
void KMDriverDB::loadDbFile() { // first clear everything m_entries.clear(); m_pnpentries.clear(); TQFile f(dbFile()); if (f.exists() && f.open(IO_ReadOnly)) { TQTextStream t(&f); TQString line; TQStringList words; KMDBEntry *entry(0); while (!t.eof()) { line = t.readLine().stripWhiteSpace(); if (line.isEmpty()) continue; int p = line.find('='); if (p == -1) continue; words.clear(); words << line.left(p) << line.mid(p+1); if (words[0] == "FILE") { if (entry) insertEntry(entry); entry = new KMDBEntry; entry->file = words[1]; } else if (words[0] == "MANUFACTURER" && entry) entry->manufacturer = words[1].upper(); else if (words[0] == "MODEL" && entry) entry->model = words[1]; else if (words[0] == "MODELNAME" && entry) entry->modelname = words[1]; else if (words[0] == "PNPMANUFACTURER" && entry) entry->pnpmanufacturer = words[1].upper(); else if (words[0] == "PNPMODEL" && entry) entry->pnpmodel = words[1]; else if (words[0] == "DESCRIPTION" && entry) entry->description = words[1]; else if (words[0] == "RECOMMANDED" && entry && words[1].lower() == "yes") entry->recommended = true; else if (words[0] == "DRIVERCOMMENT" && entry) entry->drivercomment = ("<qt>"+words[1].replace("<", "<").replace(">", ">")+"</qt>"); } if (entry) insertEntry(entry); } }
/*! \fn bool UcDbSettings::establishDatabase() * Writes the clean database file to a folder in User's Home Folder. This method should not depend on anything else. * \return If folder creation and file copy operations were successful * \warning Method Should not depend on anything else except for bool UcDbSettings::restoreDefaultDatabase(). * \warning Not used in application due to Write Access depending on OS, file system or folder location. * \sa bool UcDbSettings::restoreDefaultDatabase() */ bool UcDbSettings::establishDatabase(){ bool returnVal = false; QDir appDir(QDir::home().filePath("sprintedapp")); QFile dbFile(appDir.filePath("sprinted.db")); QFile settingsTxt(appDir.filePath("usersettings.txt")); if(dbFile.exists() || settingsTxt.exists()){ returnVal = true; }else if(appDir.exists()){ return returnVal = restoreDefaultDatabase(); }else{ QDir::home().mkdir("sprintedapp"); return returnVal = restoreDefaultDatabase(); } return returnVal; }
void CModelManager::RenderOrigList(ID3D11Device* device,ID3D11DeviceContext* deviceContext) { int selected = -1; std::ifstream dbFile("D:\\bool\\DebugConfig.ini"); if (dbFile) { dbFile >> selected; } dbFile.close(); if (selected == -1) return ; mpMeshList[selected]->Render(device, deviceContext, mbInvalidate); mbInvalidate = false ; }
/*! * \brief DropBoxOperations::dropBoxGetfile * Download file from dropbox to local directory * If the local file allready exists, it is delete firs * \param filename to create/update * \param dropbox handler * \param action update : delete existing file, download new one from dropbox, else, new file * \return 0 if ok negative value else * TODO handle directories */ int DropBoxOperations::getfile(QString filename, QDropbox *dropbox, QString action){ QByteArray utf8filename,writeBuffer; qint64 lentoread=512; int read; bool readloop=true; char *readBuffer = new char[lentoread]; utf8filename.append(filename.toUtf8()); QDropboxFile dbFile(dropBoxAccess + utf8filename,dropbox); if(action == "update"){ //Delete existing file QFile targetFile( documents + QDir::separator() + playListDir + QDir::separator() + filename.mid(1)); if(! targetFile.remove()){ return -4; } } QFile targetFile( documents + QDir::separator() + playListDir + QDir::separator() + filename.mid(1)); if(! targetFile.open(QIODevice::ReadWrite)){ return -3 ; } if(dbFile.open(QIODevice::ReadOnly)){ QDataStream readStream(&dbFile); while(readloop){ read=readStream.readRawData(readBuffer,lentoread); if (read>0){ writeBuffer=QByteArray(readBuffer,read); if(targetFile.write(writeBuffer)<0) return -5; } else readloop=false; }; dbFile.close(); targetFile.close(); delete readBuffer; return 0 ; } else{ return -1 ; } }
void DB::LoadRectangles( const char* file ) { std::ifstream dbFile(file); std::string line; if (dbFile.is_open()) { while ( dbFile.good() ) { getline (dbFile, line); s_pDB->m_pInitRectangles.push_back(s_pDB->ParseLineToRectangle(line)); } dbFile.close(); } }
bool DataCache::load() { qDebug() << Q_FUNC_INFO << this->name() << "Loading database at" << m_fileName; reset(); if (!this->preLoad()) { qWarning() << Q_FUNC_INFO << this->name() << "Preload implementation failed."; this->postLoad(false); return false; } std::ifstream dbFile(m_fileName.toStdString().c_str()); if (!dbFile) { qWarning() << Q_FUNC_INFO << this->name() << "Error opening file" << m_fileName << "for reading."; this->postLoad(false); return false; } Json::Value root; Json::Reader reader; if (!reader.parse(dbFile, root)) { qWarning() << Q_FUNC_INFO << this->name() << "Error parsing item database from" << m_fileName; this->postLoad(false); return false; } if (!this->insertData(root)) { qWarning() << Q_FUNC_INFO << this->name() << "Error inserting loaded data from cache file:" << m_fileName; this->postLoad(false); return false; } if (!this->postLoad(true)) { qWarning() << Q_FUNC_INFO << this->name() << "Postload implementation failed."; return false; } return true; }
/** * Open the database from a file. * Unless `readOnly` is set to false, the database will be opened in * read-write mode and fall back to read-only if that is not possible. * * @param filePath path to the file * @param key composite key for unlocking the database * @param readOnly open in read-only mode * @param error error message in case of failure * @return true on success */ bool Database::open(const QString& filePath, QSharedPointer<const CompositeKey> key, QString* error, bool readOnly) { if (isInitialized() && m_modified) { emit databaseDiscarded(); } setEmitModified(false); QFile dbFile(filePath); if (!dbFile.exists()) { if (error) { *error = tr("File %1 does not exist.").arg(filePath); } return false; } if (!readOnly && !dbFile.open(QIODevice::ReadWrite)) { readOnly = true; } if (!dbFile.isOpen() && !dbFile.open(QIODevice::ReadOnly)) { if (error) { *error = tr("Unable to open file %1.").arg(filePath); } return false; } KeePass2Reader reader; bool ok = reader.readDatabase(&dbFile, std::move(key), this); if (reader.hasError()) { if (error) { *error = tr("Error while reading the database: %1").arg(reader.errorString()); } return false; } setReadOnly(readOnly); setFilePath(filePath); dbFile.close(); setInitialized(ok); markAsClean(); setEmitModified(true); return ok; }
void PersistentStore::purge() { if(_initialized) { QString dbUrl = _db.databaseName(); deinit(); QFile dbFile(dbUrl); if(dbFile.exists()) dbFile.remove(); else DEBUG << "DB file not accessible: " << dbUrl; } else { DEBUG << "DB not initialized."; } }
bool EncryptedDb::pullFileContent(const QString &fname, QByteArray &buf) { QFile dbFile(fname); if (!dbFile.open(QIODevice::ReadOnly)) { qDebug() << "pullFileContent: file doesn't exist"; buf = QByteArray(); return false; } QByteArray fileContent; while (!dbFile.atEnd()) { QByteArray encrChunk = dbFile.read(encryptedChunkSize); buf = Core::getInstance()->decryptData(encrChunk, decryptionKey); if (buf.size() > 0) { fileContent += buf; } else { qWarning() << "pullFileContent: Encrypted history log is corrupted: can't decrypt, will be deleted"; buf = QByteArray(); return false; } } QList<QByteArray> splittedBA = fileContent.split('\n'); QList<QString> sqlCmds; for (auto ba_line : splittedBA) { QString line = QByteArray::fromBase64(ba_line); sqlCmds.append(line); } PlainDb::exec("BEGIN TRANSACTION;"); for (auto line : sqlCmds) QSqlQuery r = PlainDb::exec(line); PlainDb::exec("COMMIT TRANSACTION;"); dbFile.close(); return true; }
int DropBoxOperations::putfile(QString filename, QDropbox *dropbox, QString *revision,QString action="update"){ QByteArray utf8filename,writeBuffer; qint64 lentoread=512; int read; bool readloop=true; char *readBuffer = new char[lentoread]; utf8filename.append(filename.toUtf8()); QDropboxFile dbFile(dropBoxAccess + utf8filename,dropbox); if(!dbFile.open(QIODevice::ReadWrite)) return -3; // if(action == "update"){ // //Reset existing file // dbFile.reset(); // } QFile sourceFile( documents + QDir::separator() + playListDir + QDir::separator() + filename.mid(1)); if(sourceFile.open(QIODevice::ReadOnly)){ QDataStream readStream(&sourceFile); while(readloop){ read=readStream.readRawData(readBuffer,lentoread); if (read>0){ writeBuffer=QByteArray(readBuffer,read); if(dbFile.write(writeBuffer)<0) return -5; } else readloop=false; }; dbFile.flush() ; dbFile.close(); sourceFile.close(); delete readBuffer; *revision = dbFile.metadata().revisionHash() ; return 0 ; } else{ return -1 ; } }
void DbContentCacher::Process(wxThread* thread) { wxStopWatch sw; sw.Start(); wxFFile dbFile(m_filename, wxT("rb")); if(dbFile.IsOpened()) { wxString fileContent; wxCSConv fontEncConv(wxFONTENCODING_ISO8859_1); dbFile.ReadAll(&fileContent, fontEncConv); dbFile.Close(); } if (m_parent) { wxCommandEvent e(wxEVT_CMD_DB_CONTENT_CACHE_COMPLETED); e.SetString(wxString::Format(_("Symbols file loaded into OS file system cache (%ld seconds)"), sw.Time()/1000).c_str()); m_parent->AddPendingEvent(e); } }
int SqlManager::init(){ bool databaseExist = false; int res = -1; this->database = QSqlDatabase::addDatabase("QSQLITE"); QFile dbFile("/home/smaricha/qt_workspace/kinova-modules/kinova_root/KinovaAdvancedGUI/database/trajectoryProg.db"); if(!dbFile.exists()){ //TODO create database ?? }else{ databaseExist=true; this->database.setDatabaseName(dbFile.fileName()); } if(databaseExist){ if(this->database.open()){ cout << "database opened" << endl; } } return res; }
bool TeachRegManager::loadDB(const QString &filePath) { quint32 magic; quint16 streamVersion; if(db) { if(!saveDb()) return false; delete db; db = 0; } dbFilePath = filePath; QFile dbFile(dbFilePath); if(!dbFile.exists()) { qDebug() << "DataBase file " << dbFilePath << " no exist."; return false; } if(!dbFile.open(QIODevice::ReadOnly)) { qDebug() << "Can not open file " << dbFilePath << " for reading. Error: " << dbFile.errorString(); return false; } QDataStream in(&dbFile); in >> magic >> streamVersion; if(magic != magicNumber) { qDebug() << "ERROR: File is not recognized by this application"; return false; } else if(streamVersion > in.version()) { qDebug() << "ERROR: File is from a more recent version of the application"; return false; } db = new DataBaseTeachReg(this); in >> *db; return true; }
Application::Application(int argc, char *argv[]) : QCoreApplication(argc, argv) { QCommandLineParser parser; parser.setApplicationDescription("HTTP Interface for MPD/CantataWeb"); parser.addHelpOption(); parser.addVersionOption(); QCommandLineOption configOption(QStringList() << "c" << "c", "Config file (default " PACKAGE_NAME ".conf).", "configfile", PACKAGE_NAME".conf"); parser.addOption(configOption); parser.process(*this); QString cfgFile=parser.value(configOption); if (!QFile::exists(cfgFile)) { qWarning() << cfgFile << "does not exist"; ::exit(-1); } QSettings *cfg=new QSettings(cfgFile, QSettings::IniFormat, this); MPDConnection::self()->start(); // Place in separate thread... connect(this, SIGNAL(mpdDetails(MPDConnectionDetails)), MPDConnection::self(), SLOT(setDetails(MPDConnectionDetails))); MPDConnectionDetails mpd; mpd.hostname=cfg->value("mpd/host", "127.0.0.1").toString(); mpd.port=cfg->value("mpd/port", "6600").toUInt(); mpd.password=cfg->value("mpd/password", QString()).toString(); mpd.dir=cfg->value("mpd/dir", "/var/lib/mpd/music").toString(); MPDParseUtils::setSingleTracksFolder(cfg->value("mpd/singleTracksFolder", QString()).toString()); QString dbFile(cfg->value("db", QCoreApplication::applicationDirPath()+QDir::separator()+PACKAGE_NAME".sqlite").toString()); if (!MpdLibraryDb::self()->init(dbFile)) { qWarning() << dbFile << "failed to initialize"; ::exit(-1); } emit mpdDetails(mpd); HttpServer *http=new HttpServer(this, cfg); if (!http->start()) { qWarning() << "Failed to start HTTP server"; ::exit(-1); } StatusApi::self(); }
void mainWindow::loadArchive() { discList.clear(); softList.clear(); std::ifstream dbFile(dbFilePath,std::ios::in | std::ios::binary); if(!dbFile) { QMessageBox::critical(this,tr("YADSA"),tr("Archive File not found!!! Place it where it is supposed to be or reinstall!!<br /><br /><font color=red>Exiting!!</font>")); exit(1); } while(dbFile.read((char *) &tmpDisc, discSize)) { discList.push_back(tmpDisc); for(int i=0;i<tmpDisc.count;i++) { dbFile.read((char *) &tmpSoft, softSize); softList.push_back(tmpSoft); } } dbFile.close(); }
/** * @brief DbCoordinator::openDatabase Open a database or create a new * one if non existent. * @param path the path to the folder that contains the database * @param dbName the name of the database to open. Relative or Absolute path. */ void DbCoordinator::openDatabase(QString path, QString dbName) { if (isOpened()) { qDebug() << "Database is already opened!"; return; } QString dbFilePath(QString(path + "/" + dbName)); QFile dbFile(dbFilePath); bool needsGenerateSchema = false; if(!dbFile.exists()) { needsGenerateSchema = true; } m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(dbFilePath); bool db_opened = m_db.open(); if (db_opened) { qDebug() << "Opened Database for access."; opened = true; if (needsGenerateSchema) { QString schemaFilePath(QString(path + "TAEval.sql")); qDebug() << "Generating Schema..." << schemaFilePath; QFile* file = new QFile(schemaFilePath); runSqlScript(file); delete file; qDebug() << "Generated DB " << dbName; } } }
bool DataCache::save() const { qDebug() << Q_FUNC_INFO << this->name() << "Serializing item database to" << m_fileName; QFileInfo dbFileInfo(m_fileName); if (!QDir().mkpath(dbFileInfo.path())) { qWarning() << Q_FUNC_INFO << this->name() << "Error creating path" << dbFileInfo.path(); return false; } std::ofstream dbFile(m_fileName.toStdString().c_str()); if (!dbFile) { qWarning() << Q_FUNC_INFO << this->name() << "Error opening file" << m_fileName << "for writing."; return false; } Json::Value json; if (!this->exportData(json)) { qWarning() << Q_FUNC_INFO << this->name() << "Error exporting data to JSON."; return false; } Json::StyledStreamWriter writer(" "); writer.write(dbFile, json); if (!dbFile) { qWarning() << "Error writing to" << m_fileName; return false; } return true; }
wxFileName t4p::NativeFunctionsAsset() { wxFileName asset = AssetRootDir(); wxFileName dbFile(asset.GetPath(), wxT("php.db")); return dbFile; }
int main(int argc, char **argv) { // This program should receive one parameter - the folder of compressed bits if(argc != 2) { std::cout << "Pass correct parameters. Usage: " << argv[0] << " <folder of compressed bit files" << std::endl; return -1; } // Check if the folder exist boost::filesystem::path libPath(argv[1]); if(!boost::filesystem::exists(libPath)) { std::cout << "The folder " << libPath.string().c_str() << " does not exist" << std::endl; return -1; } // Maps to store the information on tile type, elements and configs std::vector<ConfigBitMap> configMapVector; std::vector<ElementConfigMap> elementMapVector; TiletypeElementMap tileMap; // Write the database file to disk std::string dbFileName = kFamily + ".ldb"; boost::filesystem::path dbFilePath = libPath / dbFileName; std::ofstream dbFile(dbFilePath.string().c_str(), std::ofstream::binary); if(!dbFile.good()) { std::cout << "Could not open file " << dbFilePath.string() << " to write" << std::endl; return -1; } // Populate the maps PopulateMaps(libPath, tileMap, elementMapVector, configMapVector); std::cout << "Opened file " << dbFilePath.string() << " to store library database" << std::endl; dbFile.write("<<<<BITLIBDB>>>>", 16); // std::cout << "Tile map size " << sizeof(tileMap.size()) << std::endl; uint32_t dataSize; dataSize = tileMap.size(); dbFile.write((char *) (&dataSize), sizeof(dataSize)); // Now go over the map data structure and write it to a file // File format is given at the top of this file TiletypeElementMap::const_iterator pTiletypes = tileMap.begin(); TiletypeElementMap::const_iterator eTiletypes = tileMap.end(); while(pTiletypes != eTiletypes) { // Write the tile name char count, name string and element count dataSize = pTiletypes->first.size(); dbFile.write((const char *) &dataSize, sizeof(dataSize)); dbFile.write((const char *) pTiletypes->first.c_str(), pTiletypes->first.size()); dataSize = pTiletypes->second.size(); dbFile.write((const char*) &dataSize, sizeof(dataSize)); std::cout << "Tile type " << pTiletypes->first << " has " << pTiletypes->second.size() << " elements." << std::endl; // Iterate over elements ElementConfigMap::const_iterator pElements = pTiletypes->second.begin(); ElementConfigMap::const_iterator eElements = pTiletypes->second.end(); while(pElements != eElements) { // Write element name char count, name string and config count dataSize = pElements->first.size(); dbFile.write((const char *) &dataSize, sizeof(dataSize)); dbFile.write((const char *) pElements->first.c_str(), pElements->first.size()); dataSize = pElements->second.size(); dbFile.write((const char *) &dataSize, sizeof(dataSize)); // std::cout << " Element type " << pElements->first << " has " // << pElements->second.size() << " configs." << std::endl; // Itereate over configs ConfigBitMap::const_iterator pConfigs = pElements->second.begin(); ConfigBitMap::const_iterator eConfigs = pElements->second.end(); while(pConfigs != eConfigs) { // Write config namem char count, name string and count of bit addresses dataSize = pConfigs->first.size(); dbFile.write((const char *) &dataSize, sizeof(dataSize)); dbFile.write(pConfigs->first.c_str(), pConfigs->first.size()); dataSize = pConfigs->second.size(); dbFile.write((const char *) &dataSize, sizeof(dataSize)); // Write the bit addresses for(std::vector<uint32_t>::const_iterator iter = pConfigs->second.begin(); iter != pConfigs->second.end(); iter++) { dbFile.write((char *) &*iter, sizeof(uint32_t)); } // std::cout << "\t" << pConfigs->first << " " << pConfigs->second.size(); pConfigs++; } // std::cout << std::endl; pElements++; } pTiletypes++; } return 0; }
bool PersistentStore::init() { QMutexLocker locker(&_mutex); // Get application data directory and database filename. QSettings settings; QString appdata = settings.value("app/app_data").toString(); if(appdata.isEmpty()) { DEBUG << "Error creating the PersistentStore: app.appdata not set."; return false; } bool create = false; QString dbUrl(appdata + QDir::separator() + DEFAULT_DBNAME); QFileInfo dbFileInfo(dbUrl); // Initialize database object. _db = _db.addDatabase("QSQLITE", "tarsnap"); _db.setConnectOptions("QSQLITE_OPEN_URI"); _db.setDatabaseName(dbUrl); // Determine whether to try to open the database. if(!dbFileInfo.exists()) { create = true; } else if(!dbFileInfo.isFile() || !dbFileInfo.isReadable()) { DEBUG << "Error creating the PersistentStore: DB file is not accessible " << dbUrl; return false; } // Database file exists and is readable; attempt to open. else if(!_db.open()) { DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text(); return false; } else { // Successfully opened database. QStringList tables = _db.tables(); // Is the database valid? if(!tables.contains("archives", Qt::CaseInsensitive)) { _db.close(); DEBUG << "Invalid PersistentStore DB found. Attempting to recover."; QString newName(dbUrl + "." + QString::number(QDateTime::currentMSecsSinceEpoch())); if(!QFile::rename(dbUrl, newName)) { DEBUG << "Failed to rename current invalid PersistentStore DB. " "Please manually clean up the DB directory " << appdata; return false; } create = true; } else { // Check the database version, and upgrade if necessary. if(!tables.contains("version", Qt::CaseInsensitive)) { if(!upgradeVersion0()) { DEBUG << "Failed to upgrade PersistentStore DB. It's best " "to start from scratch by purging the existing DB " "in " << appdata; return false; } } int version = -1; QSqlQuery query(_db); if(query.exec("SELECT version FROM version")) { query.next(); version = query.value(0).toInt(); } else { DEBUG << "Failed to get current DB version: " << query.lastError().text(); return false; } if((version == 0) && upgradeVersion1()) { DEBUG << "DB upgraded to version 1."; version = 1; } if((version == 1) && upgradeVersion2()) { DEBUG << "DB upgraded to version 2."; version = 2; } if((version == 2) && upgradeVersion3()) { DEBUG << "DB upgraded to version 3."; version = 3; } if((version == 3) && upgradeVersion4()) { DEBUG << "DB upgraded to version 4."; version = 4; } } } // Create new database (if needed). if(create) { QFile dbTemplate(":/dbtemplate.db"); if(!dbTemplate.copy(dbUrl)) { DEBUG << "Failed to create the PersistentStore DB."; return false; } // Work around the fact that QFile::copy from the resource system does // not set u+w on the resulted file QFile dbFile(dbUrl); dbFile.setPermissions(dbFile.permissions() | QFileDevice::WriteOwner); dbFile.close(); if(!_db.open()) { DEBUG << "Error opening the PersistentStore DB: " << _db.lastError().text(); return false; } } return _initialized = true; }
void ITunesFeature::activate(bool forceReload) { //qDebug("ITunesFeature::activate()"); if (!m_isActivated || forceReload) { //Delete all table entries of iTunes feature ScopedTransaction transaction(m_database); clearTable("itunes_playlist_tracks"); clearTable("itunes_library"); clearTable("itunes_playlists"); transaction.commit(); emit(showTrackModel(m_pITunesTrackModel)); SettingsDAO settings(m_pTrackCollection->database()); QString dbSetting(settings.getValue(ITDB_PATH_KEY)); // if a path exists in the database, use it if (!dbSetting.isEmpty() && QFile::exists(dbSetting)) { m_dbfile = dbSetting; } else { // No Path in settings, try the default m_dbfile = getiTunesMusicPath(); } QFileInfo dbFile(m_dbfile); if (!m_dbfile.isEmpty() && dbFile.exists()) { // Users of Mixxx <1.12.0 didn't support sandboxing. If we are sandboxed // and using a custom iTunes path then we have to ask for access to this // file. Sandbox::askForAccess(m_dbfile); } else { // if the path we got between the default and the database doesn't // exist, ask for a new one and use/save it if it exists m_dbfile = QFileDialog::getOpenFileName( NULL, tr("Select your iTunes library"), QDir::homePath(), "*.xml"); QFileInfo dbFile(m_dbfile); if (m_dbfile.isEmpty() || !dbFile.exists()) { return; } // The user has picked a new directory via a file dialog. This means the // system sandboxer (if we are sandboxed) has granted us permission to // this folder. Create a security bookmark while we have permission so // that we can access the folder on future runs. We need to canonicalize // the path so we first wrap the directory string with a QDir. Sandbox::createSecurityToken(dbFile); settings.setValue(ITDB_PATH_KEY, m_dbfile); } m_isActivated = true; // Usually the maximum number of threads // is > 2 depending on the CPU cores // Unfortunately, within VirtualBox // the maximum number of allowed threads // is 1 at all times We'll need to increase // the number to > 1, otherwise importing the music collection // takes place when the GUI threads terminates, i.e., on // Mixxx shutdown. QThreadPool::globalInstance()->setMaxThreadCount(4); //Tobias decided to use 4 // Let a worker thread do the XML parsing m_future = QtConcurrent::run(this, &ITunesFeature::importLibrary); m_future_watcher.setFuture(m_future); m_title = tr("(loading) iTunes"); // calls a slot in the sidebar model such that 'iTunes (isLoading)' is displayed. emit(featureIsLoading(this, true)); } else { emit(showTrackModel(m_pITunesTrackModel)); } emit(enableCoverArtDisplay(false)); }
/** * Saves changes in the current database. * If successful, returns true and emits dbSaved() signal; * otherwise returns false and (sometimes) emits an appropriate error signal. */ Q_INVOKABLE bool PwDatabaseFacade::save() { if (!db) { LOG("Cannot save - no DB open"); return false; } if (isLocked()) { LOG("Cannot save - DB is locked"); return false; } emit dbAboutToSave(); // Encrypt and save to memory QByteArray outData; if (!db->save(outData)) { LOG("DB saving failed"); return false; } // Copy original DB to temporary timestamped file // (but when we create a DB, the original does not exist, and it is ok) QFile dbFile(db->getDatabaseFilePath()); QString bakFileName = makeBackupFilePath(db->getDatabaseFilePath()); if (dbFile.exists() && !dbFile.copy(bakFileName)) { LOG("Failed to backup the original DB: %s", dbFile.errorString().toUtf8().constData()); emit fileSaveError(tr("Cannot backup database file. Saving cancelled.", "An error message: failed to make a backup copy of the database file."), dbFile.errorString()); return false; } // Write the new data directly to the original file if (!dbFile.open(QIODevice::WriteOnly)) { LOG("Cannot open DB file: '%s' Error: %d. Message: %s", dbFile.fileName().toUtf8().constData(), dbFile.error(), dbFile.errorString().toUtf8().constData()); emit fileSaveError(tr("Cannot save database file", "An error message shown when the database file cannot be saved."), dbFile.errorString()); return false; } qint64 bytesWritten = dbFile.write(outData); if ((dbFile.error() != QFile::NoError) || (bytesWritten != outData.size())) { LOG("Cannot write to DB file. Error: %d. Message: %s", dbFile.error(), dbFile.errorString().toUtf8().constData()); emit fileSaveError(tr("Cannot write to database file", "An error message shown when the database file cannot be written to."), dbFile.errorString()); return false; } if (!dbFile.flush()) { LOG("Could not flush the DB file. Error: %d. Message: %s", dbFile.error(), dbFile.errorString().toUtf8().constData()); emit fileSaveError(tr("Error writing to database file", "An error message shown when the database file cannot be written to."), dbFile.errorString()); dbFile.close(); // could not flush -> possibly not completely written -> not saved return false; } dbFile.close(); if (!Settings::instance()->isBackupDatabaseOnSave()) { // Backup switched off, so remove the backup file // (there are no backup files for newly created DBs) QFile bakFile(bakFileName); if (bakFile.exists() && !bakFile.remove()) { // Could not delete backup. Not critical and nothing we/user can do about it - so just ignore it silently. LOG("Could not remove backup file: %s", bakFile.fileName().toUtf8().constData()); } } emit dbSaved(); return true; }
bool BackupTask::fullExport(const QString &destPath, QString &errorMessage) { int dbVersion = DefinitionHolder::DATABASE_VERSION; qint64 metadataOffset = 0; QMap<qint64, QString> fileOffset; QStringList contentFileList = MetadataEngine::getInstance() .getAllContentFiles().values(); //calc progress int progress = 0; int totalSteps = 0; totalSteps = 1 + contentFileList.size(); emit progressSignal(progress, totalSteps); QFile destFile(destPath); if (!destFile.open(QIODevice::WriteOnly)) { errorMessage = tr("Failed to open create file %1: %2") .arg(destPath).arg(destFile.errorString()); return false; } QDataStream out(&destFile); out << m_magicNumber; out << dbVersion; int placeHolderOffset = destFile.pos(); out << metadataOffset; //place holder //write database file fileOffset.insert(destFile.pos(), "database"); QFile dbFile(m_dbPath); if (!dbFile.open(QIODevice::ReadOnly)) { errorMessage = tr("Failed to open file %1: %2") .arg(m_dbPath).arg(dbFile.errorString()); return false; } while(!dbFile.atEnd()) { destFile.write(dbFile.read(m_fileBufSize)); } dbFile.close(); //update progress emit progressSignal(++progress, totalSteps); //write content files foreach (QString s, contentFileList) { fileOffset.insert(destFile.pos(), s); QFile file(m_filesDir + s); if (!file.open(QIODevice::ReadOnly)) { errorMessage = tr("Failed to open file %1: %2") .arg(m_filesDir + s).arg(file.errorString()); return false; } while(!file.atEnd()) { destFile.write(file.read(m_fileBufSize)); } file.close(); //update progress emit progressSignal(++progress, totalSteps); }
int TcDatabase::open() { int ret = 0; close(); switch(dbType()) { case SQLSERVER: //QSqlDatabase::removeDatabase("FriendSafe"); m_handle = QSqlDatabase::addDatabase("QODBC"); { QString dsn = QString("DRIVER={SQL SERVER};SERVER=%1;DATABASE=%2;").arg(hostName()).arg(dbName()); m_handle.setDatabaseName(dsn); m_handle.setUserName(m_username); m_handle.setPassword(m_password); } ret = m_handle.open() ? 1 : 0; break; case MYSQL: //QSqlDatabase::removeDatabase("qt_sql_default_connection"); m_handle = QSqlDatabase::addDatabase("QMYSQL");//, "qt_sql_default_connection");//, "allowMultiQueries=true"); m_handle.setHostName(hostName()); m_handle.setDatabaseName(dbName()); m_handle.setUserName(m_username); m_handle.setPassword(m_password); //m_handle.setConnectOptions("allowMultiQueries=true"); //m_handle.cloneDatabase() ret = m_handle.open() ? 1 : 0; //DEBUG_OUT(m_handle.connectionName()) //DEBUG_OUT(m_handle.connectionNames().join("\n")) break; case POSTGRESQL: //QSqlDatabase::removeDatabase(""); m_handle = QSqlDatabase::addDatabase("QPSQL"); m_handle.setHostName(hostName()); m_handle.setDatabaseName(dbName()); m_handle.setUserName(m_username); m_handle.setPassword(m_password); //m_handle.setConnectOptions("allowMultiQueries=true"); //m_handle.cloneDatabase() ret = m_handle.open() ? 1 : 0; //DEBUG_OUT(m_handle.connectionName()) //DEBUG_OUT(m_handle.connectionNames().join("\n")) break; case SQLTIE: //QSqlDatabase::removeDatabase("FriendSafe"); m_handle = QSqlDatabase::addDatabase("QSQLITE"); QFileInfo dbFile(m_dbName); QDir dir(dbFile.absoluteDir()); dir.mkpath(dbFile.absolutePath()); m_handle.setDatabaseName(m_dbName); m_handle.setUserName(m_username); m_handle.setPassword(m_password); if ( m_handle.open() ) { m_hostName = "localhost"; m_hostPort = 0; QStringList tables = m_handle.tables(); if ( tables.count() <= 0 ) { // 没有任何表,这个库是新建的。 QFile f(CreateDDL); if ( f.open(QFile::Text | QFile::ReadOnly) ) { QTextStream in(&f); QString fileText = in.readAll(); f.close(); ret = 1; QSqlQuery query = QSqlQuery(m_handle); int pos; while((pos=fileText.indexOf(";")) >-1) { QString sqlText = fileText.mid(0, pos).trimmed(); fileText.remove(0, pos+1); fileText = fileText.trimmed(); QStringList sqlLines = sqlText.split("\n", QString::SkipEmptyParts); QString sql; for( int i=0;i<sqlLines.count();i++ ) { QString s = sqlLines.at(i); if ( ! s.startsWith("--") ) { sql += s + "\n"; } } if ( ! sql.isEmpty() && ! query.exec(sql) ) { ret = -1; } } query.finish(); } }else { ret = 1; } } break; } m_accepted = ret >0; return ret; }
int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); app.setOrganizationName("ITI"); app.setOrganizationDomain("myaircoach.eu"); app.setApplicationName("myAirCoach"); //--------- //QTranslator qtTranslator; // qtTranslator.load("myAirCoach_" + QLocale::system().name(), ":/"); //app.installTranslator(&qtTranslator); //--------- qmlRegisterType<MyAdmob>("myadmob", 1, 0, "MyAdmob"); qmlRegisterType<MyDevice>("mydevice", 1, 0, "MyDevice"); qmlRegisterType<QMLObjectStore>("QMLObjectStore", 1, 0, "QMLObjectStore"); qmlRegisterType<WaterfallItem>("hu.timur", 1, 0, "Waterfall"); qmlRegisterType<Graph>("Graph", 1, 0, "Graph"); //QQmlApplicationEngine engine; qmlRegisterType<WeatherData>("WeatherInfo", 1, 0, "WeatherData"); qmlRegisterType<AppModel>("WeatherInfo", 1, 0, "AppModel"); qmlRegisterType<AudioRecorder>("AudioRecorder", 1, 0, "AudioRecorder"); qmlRegisterType<FPSText>("FPSText", 1, 0, "FPSText"); //! [0] qRegisterMetaType<WeatherData>(); //AudioRecorder recorder; QQmlApplicationEngine* engine = new QQmlApplicationEngine(); //engine->rootContext()->setContextProperty("recorder", &recorder); engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); //main1 QQmlContext * rootContext = engine->rootContext(); /*const QStringList & musicPaths = QStandardPaths::standardLocations(QStandardPaths::MusicLocation); const QUrl musicUrl = QUrl::fromLocalFile(musicPaths.isEmpty() ? QDir::homePath() : musicPaths.first()); rootContext->setContextProperty(QStringLiteral("musicUrl"), musicUrl); const QStringList arguments = QCoreApplication::arguments(); const QUrl commandLineUrl = arguments.size() > 1 ? QUrl::fromLocalFile(arguments.at(1)) : QUrl(); rootContext->setContextProperty(QStringLiteral("url"), commandLineUrl); */ // NotificationClient *notificationClient; // rootContext->setContextProperty(QLatin1String("notificationClient"), // notificationClient); //view.setResizeMode(QQuickView::SizeRootObjectToView); QObject * root = engine->rootObjects().first(); #ifdef Q_OS_ANDROID QString hash = QString("myAirCoach"); QString dirStorageString = QString("/sdcard/Android/data/com.qtproject.qtangled/"); QDir dir; if( dir.mkpath(dirStorageString) ) { engine->setOfflineStoragePath( dirStorageString ); engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); QString dbFileString = dirStorageString + hash + QString(".sqlite"); QFile dbFile(dbFileString); if (dbFile.exists()) { QFile::setPermissions(dbFileString, QFile::WriteOwner | QFile::ReadOwner); } QFile iniFile( dir.path() + hash + QString(".ini") ); iniFile.open( QIODevice::WriteOnly ); iniFile.write( "[General]\nDescription=Catalog\nDriver=QSQLITE\nName=Catalog\nVersion=1.0" ); iniFile.close(); } else { #endif //engine->load(QUrl(QStringLiteral("qrc:/qml/main.qml"))); //sos prosoxh velos h teleia #ifdef Q_OS_ANDROID } #endif return app.exec(); }