/*! Worker method, checks if the thumb does not exist and starts saving to file. */ bool ImageScaler::convertToThumb(const QFileInfo& info) { bool retVal = false; // The thumbnails are saved under a hidden folder in order // to avoid showing the thumbnails in the Media Gallery. const QString privatePath("/home/user/.mediabrowser/thumbs"); QDir saveDir(privatePath + info.path()); if (!saveDir.exists()) { if (!saveDir.mkpath(saveDir.path())) { qDebug() << "Thumbs folder creation failed. Quitting!"; return false; } } // Create the thumb file path to the private save folder. QString saveName = saveDir.path() + "/" + info.fileName(); // Check if the file already exists if (QFile::exists(saveName)) { qDebug() << "File: " << saveName << " already exist!"; } else { // Does not exist yet, read, scale & save the image! retVal = saveImage(info, saveName); } return retVal; }
QString ResourceFinder::getResourceSaveDir(QString resourceCat) { // Returns the "user" location QString user = getUserResourcePrefix(); if (user == "") return ""; if (resourceCat != "") resourceCat = "/" + resourceCat; QDir userDir(user); if (!userDir.exists()) { if (!userDir.mkpath(user)) { std::cerr << "ResourceFinder::getResourceSaveDir: ERROR: Failed to create user resource path \"" << user << "\"" << std::endl; return ""; } } if (resourceCat != "") { QString save = QString("%1%2").arg(user).arg(resourceCat); QDir saveDir(save); if (!saveDir.exists()) { if (!userDir.mkpath(save)) { std::cerr << "ResourceFinder::getResourceSaveDir: ERROR: Failed to create user resource path \"" << save << "\"" << std::endl; return ""; } } return save; } else { return user; } }
QString& KLameOptionsDialogue::getConversionDirectory() { QString originalDirectory = conversionDirectory_; conversionDirectory_ = optionsDialogueUi.outputDirectory->text(); QDir saveDir(conversionDirectory_); bool isOk(true); if (! saveDir.exists()) { int ans = 0; if (! saveDir.exists()) ans = QMessageBox::warning(this, "kLAME Settings -- Create Directory", QString( "Directory\n'%1'\ndoes not exist - Create it?" ) .arg(conversionDirectory_), "&Yes", "&No", QString::null, 1, 1 ); if (ans == 0) { isOk = saveDir.mkpath(conversionDirectory_); if (isOk) conversionDirectory_ = saveDir.canonicalPath(); else { QMessageBox::information(this, "kLAME","Unable to create the directory"); } } else isOk = false; } if (! isOk) { conversionDirectory_ = originalDirectory; } conversionDirectory_ = QDir::cleanPath(conversionDirectory_); return conversionDirectory_; }
POSIXSaveFileManager::POSIXSaveFileManager() { // Register default savepath based on HOME #if defined(SAMSUNGTV) ConfMan.registerDefault("savepath", "/mtd_wiselink/scummvm savegames"); #else Common::String savePath; const char *home = getenv("HOME"); if (home && *home && strlen(home) < MAXPATHLEN) { savePath = home; savePath += "/" DEFAULT_SAVE_PATH; ConfMan.registerDefault("savepath", savePath); } // The user can override the savepath with the SCUMMVM_SAVEPATH // environment variable. This is weaker than a --savepath on the // command line, but overrides the default savepath. // // To ensure that the command line option (if given) has precedence, // we only set the value in the transient domain if it is not // yet present there. if (!ConfMan.hasKey("savepath", Common::ConfigManager::kTransientDomain)) { const char *dir = getenv("SCUMMVM_SAVEPATH"); if (dir && *dir && strlen(dir) < MAXPATHLEN) { Common::FSNode saveDir(dir); if (!saveDir.exists()) { warning("Ignoring non-existent SCUMMVM_SAVEPATH '%s'", dir); } else if (!saveDir.isWritable()) { warning("Ignoring non-writable SCUMMVM_SAVEPATH '%s'", dir); } else { ConfMan.set("savepath", dir, Common::ConfigManager::kTransientDomain); } } } #endif }
// save_path is a folder, not an absolute file path int AddNewTorrentDialog::indexOfSavePath(const QString &save_path) { QDir saveDir(save_path); for(int i = 0; i < ui->save_path_combo->count(); ++i) if (QDir(ui->save_path_combo->itemData(i).toString()) == saveDir) return i; return -1; }
int saveDir(struct NODE *inputCWD, char *outputFile){ struct NODE *Temp; FILE *outfile; outfile = fopen(outputFile, "a"); //appends file // fprintf(outfile, "\n"); fclose(outfile); rwd(inputCWD, outputFile); // writes cwd to file outfile = fopen(outputFile, "a"); //appends file fprintf(outfile, "\n"); if(inputCWD->childPtr){ Temp = inputCWD->childPtr; if(*Temp->Type == 'F'){ // checking to see if first childPtr of inputCWD is a file fprintf(outfile, "\n"); fprintf(outfile, "~%s", Temp->Name); } while(Temp->siblingPtr){ // going through directory and fprintf all files within Temp = Temp->siblingPtr; if(*Temp->Type == 'F'){ // checking to see if first childPtr of inputCWD is a file fprintf(outfile, "~%s", Temp->Name); } } fprintf(outfile, "\n"); fclose(outfile); // Now we recursively print the folders within the input directory Temp = inputCWD->childPtr; if(*Temp->Type == 'D'){ // checking to see if first childPtr of inputCWD is a file saveDir(Temp, outputFile); } while(Temp->siblingPtr){ // going through directory and fprintf all files within Temp = Temp->siblingPtr; if(*Temp->Type == 'D'){ // checking to see if first childPtr of inputCWD is a file // outfile = fopen(outputFile, "a"); //appends file // fprintf(outfile, "\n"); // fclose(outfile); saveDir(Temp, outputFile); } } } return 1; }
Entries Directory::entries() const { FileSystem& fs = FileSystem::instance(); Directory saveDir( fs.workingDirectory() ); Directory changeDd = *this; fs.changeWorkingDirectoryTo( changeDd ); Entries fList( changeDd.toString(), Path::nativeCase, false ); fList = fs.getFileList(); fs.changeWorkingDirectoryTo( saveDir ); return fList; }
FileList FileDir::getEntries() const { FileSystem& fs = FileSystem::instance(); FileDir saveDir( fs.getWorkingDirectory() ); FileDir changeDd = *this; fs.changeWorkingDirectoryTo( changeDd ); FileList fList( changeDd.toString(), false, false ); fList = fs.getFileList(); fs.changeWorkingDirectoryTo( saveDir ); return fList; }
void loadFilterDialogue(QWidget * parent) { // Get filepath from user QString filepath = QFileDialog::getOpenFileName( parent, QString("Open Moviesoap filter file"), QString(saveDir().c_str()), QString(MOVIESOAP_FILECHOOSER_FILTER)); if ( !filepath.isEmpty() ) { vlc_mutex_lock( &Moviesoap::lock ); // Ensure existence of loaded filter if (Moviesoap::p_loadedFilter == NULL) Moviesoap::p_loadedFilter = new Filter; // Stop loaded filter in case it is running vlc_mutex_unlock( &Moviesoap::lock ); Moviesoap::spawn_stop_filter(); // Overwrite loaded filter with data from filter file const char * c_filepath = qPrintable(filepath); int err = Moviesoap::p_loadedFilter->load( c_filepath ); // Display error (if any) in QMessageBox if (err) { stringstream msgs; msgs << "Failure to load filter from file.\nError code " << err; QMessageBox::warning( parent, QString("File IO failure"), QString(msgs.str().c_str()), QMessageBox::Ok); return; } // if no error: #ifdef MSDEBUG1 msg_Info( p_obj, "OLD FILTER OVERWRITTEN" ); msg_Info( p_obj, "IS ACTIVE SELECTED: %d", isActiveSelected() ); #endif // Start loaded filter if menu has active selected if ( isActiveSelected() ) { if (Moviesoap::p_input == NULL) spawn_set_p_input(false); #ifdef MSDEBUG1 msg_Info(p_obj, "p input: %x", p_input); #endif if (Moviesoap::p_input) Moviesoap::spawn_restart_filter(); } } }
void AnimatorApplication::animate(){ printed = 0; QDir sourceDir(rootQML->property("sourceDirectory").toUrl().toLocalFile()); destinationDir = rootQML->property("destinationDirectory").toUrl().toLocalFile(); QString pathToSave(destinationDir); QDir saveDir(sourceDir); QStringList nameFilters; nameFilters << QString("*.json"); QStringList filelist = saveDir.entryList(nameFilters); //QMap сам сортирует по ключу вроде как QMap<int,GenAlgObject> map; QMap<int,double> fitnessMap; foreach(QString file, filelist){ int popNum = file.split("-")[0].toInt(); QFile jsonFile(sourceDir.absolutePath()+"\\" + file); jsonFile.open(QIODevice::ReadOnly); QByteArray data = jsonFile.readAll(); QJsonDocument doc = QJsonDocument::fromJson(data); map[popNum] = GenAlgObject(doc.object()); fitnessMap[popNum] = file.split("-")[1].toDouble(); }
save(struct NODE *inputCWD, char *outputFile){ FILE *outfile; if (outputFile == NULL){ printf("ERROR: No output file name.\n"); return 0; } outfile = fopen(outputFile, "w"); // creates output file if(outfile){ fclose(outfile); // closes root } else{ printf("error with file name '%s' try different name\n", outputFile); return 0; } if(saveDir(inputCWD, outputFile)){// begins examining root and saving directory information. returns true if successful. printf("save successful\n"); return 1; } else{ printf("Error: an unknown error occured in saveDir()\n"); } }
bool ModelPackager::zipModel() { QTemporaryDir dir; dir.setAutoRemove(true); QDir tempDir(dir.path()); QByteArray nameField = _mapping.value(NAME_FIELD).toByteArray(); tempDir.mkpath(nameField + "/textures"); QDir fbxDir(tempDir.path() + "/" + nameField); QDir texDir(fbxDir.path() + "/textures"); // Copy textures listTextures(); if (!_textures.empty()) { QByteArray texdirField = _mapping.value(TEXDIR_FIELD).toByteArray(); _texDir = _modelFile.path() + "/" + texdirField; copyTextures(_texDir, texDir); } // Copy LODs QVariantHash lodField = _mapping.value(LOD_FIELD).toHash(); if (!lodField.empty()) { for (auto it = lodField.constBegin(); it != lodField.constEnd(); ++it) { QString oldPath = _modelFile.path() + "/" + it.key(); QFile lod(oldPath); QString newPath = fbxDir.path() + "/" + QFileInfo(lod).fileName(); if (lod.exists()) { lod.copy(newPath); } } } // Copy FBX QFile fbx(_fbxInfo.filePath()); QByteArray filenameField = _mapping.value(FILENAME_FIELD).toByteArray(); QString newPath = fbxDir.path() + "/" + QFileInfo(filenameField).fileName(); fbx.copy(newPath); // Correct FST _mapping[FILENAME_FIELD] = tempDir.relativeFilePath(newPath); _mapping[TEXDIR_FIELD] = tempDir.relativeFilePath(texDir.path()); // Copy FST QFile fst(tempDir.path() + "/" + nameField + ".fst"); if (fst.open(QIODevice::WriteOnly)) { fst.write(FSTReader::writeMapping(_mapping)); fst.close(); } else { qCDebug(interfaceapp) << "Couldn't write FST file" << fst.fileName(); return false; } QString saveDirPath = QFileDialog::getExistingDirectory(nullptr, "Save Model", "", QFileDialog::ShowDirsOnly); if (saveDirPath.isEmpty()) { qCDebug(interfaceapp) << "Invalid directory" << saveDirPath; return false; } QDir saveDir(saveDirPath); copyDirectoryContent(tempDir, saveDir); return true; }
std::string terrama2::core::DataRetrieverFTP::retrieveData(const std::string& mask, const Filter& filter, const std::string& timezone, std::shared_ptr<terrama2::core::FileRemover> remover, const std::string& temporaryFolderUri, const std::string& foldersMask) const { std::string downloadBaseFolderUri = getTemporaryFolder(remover, temporaryFolderUri); try { // find valid directories std::vector< std::string > baseUriList; baseUriList.push_back(dataProvider_->uri); if(!foldersMask.empty()) { auto uriList = getFoldersList(baseUriList, foldersMask); if(uriList.empty()) { QString errMsg = QObject::tr("No files found!"); TERRAMA2_LOG_WARNING() << errMsg; throw terrama2::core::NoDataException() << ErrorDescription(errMsg); } baseUriList = uriList; } // Get a file listing from server for(const auto& uri : baseUriList) { std::vector<std::string> vectorFiles = curlwrapper_->listFiles(te::core::URI(uri)); std::vector<std::string> vectorNames; // filter file names that should be downloaded. for(const std::string& fileName: vectorFiles) { // FIXME: use timestamp std::shared_ptr< te::dt::TimeInstantTZ > timestamp; if(terrama2::core::isValidDataSetName(mask,filter, timezone.empty() ? "UTC+00" : timezone, fileName,timestamp)) vectorNames.push_back(fileName); } if(vectorNames.empty()) { continue; } // Create directory struct QString saveDir(QString::fromStdString(uri)); saveDir.replace(QString::fromStdString(dataProvider_->uri), QString::fromStdString(downloadBaseFolderUri)); QString savePath = QUrl(saveDir).toString(QUrl::RemoveScheme); QDir dir(savePath); if(!dir.exists()) dir.mkpath(savePath); // Performs the download of files in the vectorNames for(const auto& file: vectorNames) { std::string uriOrigin = uri + "/" + file; std::string filePath = savePath.toStdString() + "/" + file; try { curlwrapper_->downloadFile(uriOrigin, filePath); } catch(const te::Exception& e) { QString errMsg = QObject::tr("Error during download of file %1.\n").arg(QString::fromStdString(file)); auto errStr = boost::get_error_info<te::ErrorDescription>(e); if(errStr) errMsg.append(QString::fromStdString(*errStr)); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } remover->addTemporaryFile(filePath); } } } catch(const NoDataException&) { throw; } catch(const DataRetrieverException&) { throw; } catch(const te::Exception& e) { QString errMsg = QObject::tr("Error during download.\n"); errMsg.append(boost::get_error_info<terrama2::ErrorDescription>(e)); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } catch(const std::exception& e) { QString errMsg = QObject::tr("Error during download.\n"); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } catch(...) { throw DataRetrieverException() << ErrorDescription(QObject::tr("Unknown Error.")); } // returns the absolute path of the folder that contains the files that have been made the download. return downloadBaseFolderUri; }
bool JsonMapStorage::saveData(bool baseMapOnly) { emit log("JsonMapStorage", "Writing data to files ..."); // Collect the room and marker lists. The room list can't be acquired // directly apparently and we have to go through a RoomSaver which receives // them from a sort of callback function. // The RoomSaver acts as a lock on the rooms. ConstRoomList roomList{}; MarkerList &markerList = m_mapData.getMarkersList(); RoomSaver saver(m_mapData, roomList); for (uint i = 0; i < m_mapData.getRoomsCount(); ++i) { m_mapData.lookingForRooms(saver, RoomId{i}); } uint roomsCount = saver.getRoomsCount(); auto marksCount = static_cast<uint>(markerList.size()); auto &progressCounter = getProgressCounter(); progressCounter.reset(); progressCounter.increaseTotalStepsBy(roomsCount * 2 + marksCount); BaseMapSaveFilter filter; if (baseMapOnly) { filter.setMapData(&m_mapData); progressCounter.increaseTotalStepsBy(filter.prepareCount()); filter.prepare(progressCounter); } JsonWorld world; world.addRooms(roomList, filter, progressCounter, baseMapOnly); QDir saveDir(m_fileName); QDir destDir(QFileInfo(saveDir, "v1").filePath()); QDir roomIndexDir(QFileInfo(destDir, "roomindex").filePath()); QDir zoneDir(QFileInfo(destDir, "zone").filePath()); try { if (!saveDir.mkdir("v1")) { throw std::runtime_error("error creating dir v1"); } if (!destDir.mkdir("roomindex")) { throw std::runtime_error("error creating dir v1/roomindex"); } if (!destDir.mkdir("zone")) { throw std::runtime_error("error creating dir v1/zone"); } world.writeMetadata(QFileInfo(destDir, "arda.json"), m_mapData); world.writeRoomIndex(roomIndexDir); world.writeZones(zoneDir, filter, progressCounter, baseMapOnly); } catch (std::exception &e) { emit log("JsonMapStorage", e.what()); return false; } emit log("JsonMapStorage", "Writing data finished."); m_mapData.unsetDataChanged(); emit onDataSaved(); return true; }
POSIXSaveFileManager::POSIXSaveFileManager() { // Register default savepath. #if defined(SAMSUNGTV) ConfMan.registerDefault("savepath", "/mtd_wiselink/scummvm savegames"); #else Common::String savePath; #if defined(MACOSX) const char *home = getenv("HOME"); if (home && *home && strlen(home) < MAXPATHLEN) { savePath = home; savePath += "/Documents/ScummVM Savegames"; ConfMan.registerDefault("savepath", savePath); } #else const char *envVar; // Previously we placed our default savepath in HOME. If the directory // still exists, we will use it for backwards compatability. envVar = getenv("HOME"); if (envVar && *envVar) { savePath = envVar; savePath += "/.scummvm"; struct stat sb; if (stat(savePath.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) { savePath.clear(); } } if (savePath.empty()) { Common::String prefix; // On POSIX systems we follow the XDG Base Directory Specification for // where to store files. The version we based our code upon can be found // over here: http://standards.freedesktop.org/basedir-spec/basedir-spec-0.8.html envVar = getenv("XDG_DATA_HOME"); if (!envVar || !*envVar) { envVar = getenv("HOME"); if (envVar && *envVar) { prefix = envVar; savePath = ".local/share/"; } } else { prefix = envVar; } // Our default save path is '$XDG_DATA_HOME/scummvm/saves' savePath += "scummvm/saves"; if (!Posix::assureDirectoryExists(savePath, prefix.c_str())) { savePath.clear(); } else { savePath = prefix + '/' + savePath; } } if (!savePath.empty() && savePath.size() < MAXPATHLEN) { ConfMan.registerDefault("savepath", savePath); } #endif // The user can override the savepath with the SCUMMVM_SAVEPATH // environment variable. This is weaker than a --savepath on the // command line, but overrides the default savepath. // // To ensure that the command line option (if given) has precedence, // we only set the value in the transient domain if it is not // yet present there. if (!ConfMan.hasKey("savepath", Common::ConfigManager::kTransientDomain)) { const char *dir = getenv("SCUMMVM_SAVEPATH"); if (dir && *dir && strlen(dir) < MAXPATHLEN) { Common::FSNode saveDir(dir); if (!saveDir.exists()) { warning("Ignoring non-existent SCUMMVM_SAVEPATH '%s'", dir); } else if (!saveDir.isWritable()) { warning("Ignoring non-writable SCUMMVM_SAVEPATH '%s'", dir); } else { ConfMan.set("savepath", dir, Common::ConfigManager::kTransientDomain); } } } #endif }
void TCueSheetWindow::Save(BMessage* message) { status_t myErr; entry_ref theRef; char* theString = NULL; // Get directory to save data to message->FindRef("directory", &theRef); // Get name of file to be saved as message->FindString("name", (const char**)&theString); // Set window title to new filename SetTitle(theString); // Create a BDirectory object BDirectory saveDir(&theRef); // Now create the file. Create new file if fFile is unitialized. if (fFile) delete fFile; fFile = new BFile(); myErr = saveDir.CreateFile(theString, fFile, false); if (myErr != B_OK) return; // Write out file header //WriteHeader(fFile); BMessage archive; // Archive CueSheetWindow and write to file BMessage cueSheetArchive; Archive(&cueSheetArchive, true); // Flatten and write out to file ssize_t numBytes; cueSheetArchive.Flatten(fFile, &numBytes); // Set file type BNodeInfo info(fFile); if ( info.InitCheck() ) return; myErr = info.SetType("application/x-mediapede-cuesheet"); // Set icons BBitmap* smallIcon = GetMICNFromResource("application/x-mediapede-cuesheet"); info.SetIcon( smallIcon, B_MINI_ICON); BBitmap* largeIcon = GetICONFromResource("application/x-mediapede-cuesheet"); info.SetIcon( largeIcon, B_LARGE_ICON); delete smallIcon; delete largeIcon; // Update our entry in the Windows menu to reflect possible new filename BMenuItem* theItem = fAppMenu->GetWindowsMenu()->FindItem( Title()); if (theItem) theItem->SetLabel(theString); // We aren't dirty now fCueSheetView->SetDirty(false); }
bool ModelPackager::zipModel() { QTemporaryDir dir; dir.setAutoRemove(true); QDir tempDir(dir.path()); QByteArray nameField = _mapping.value(NAME_FIELD).toByteArray(); tempDir.mkpath(nameField + "/textures"); tempDir.mkpath(nameField + "/scripts"); QDir fbxDir(tempDir.path() + "/" + nameField); QDir texDir(fbxDir.path() + "/textures"); QDir scriptDir(fbxDir.path() + "/scripts"); // Copy textures listTextures(); if (!_textures.empty()) { QByteArray texdirField = _mapping.value(TEXDIR_FIELD).toByteArray(); _texDir = _modelFile.path() + "/" + texdirField; copyTextures(_texDir, texDir); } // Copy scripts QByteArray scriptField = _mapping.value(SCRIPT_FIELD).toByteArray(); _mapping.remove(SCRIPT_FIELD); if (scriptField.size() > 1) { tempDir.mkpath(nameField + "/scripts"); _scriptDir = _modelFile.path() + "/" + scriptField; QDir wdir = QDir(_scriptDir); _mapping.remove(SCRIPT_FIELD); wdir.setSorting(QDir::Name | QDir::Reversed); auto list = wdir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries); for (auto script : list) { auto sc = tempDir.relativeFilePath(scriptDir.path()) + "/" + QUrl(script).fileName(); _mapping.insertMulti(SCRIPT_FIELD, sc); } copyDirectoryContent(wdir, scriptDir); } // Copy LODs QVariantHash lodField = _mapping.value(LOD_FIELD).toHash(); if (!lodField.empty()) { for (auto it = lodField.constBegin(); it != lodField.constEnd(); ++it) { QString oldPath = _modelFile.path() + "/" + it.key(); QFile lod(oldPath); QString newPath = fbxDir.path() + "/" + QFileInfo(lod).fileName(); if (lod.exists()) { lod.copy(newPath); } } } // Copy FBX QFile fbx(_fbxInfo.filePath()); QByteArray filenameField = _mapping.value(FILENAME_FIELD).toByteArray(); QString newPath = fbxDir.path() + "/" + QFileInfo(filenameField).fileName(); fbx.copy(newPath); // Correct FST _mapping[FILENAME_FIELD] = tempDir.relativeFilePath(newPath); _mapping[TEXDIR_FIELD] = tempDir.relativeFilePath(texDir.path()); for (auto multi : _mapping.values(SCRIPT_FIELD)) { multi.fromValue(tempDir.relativeFilePath(scriptDir.path()) + multi.toString()); } // Copy FST QFile fst(tempDir.path() + "/" + nameField + ".fst"); if (fst.open(QIODevice::WriteOnly)) { fst.write(FSTReader::writeMapping(_mapping)); fst.close(); } else { qCDebug(interfaceapp) << "Couldn't write FST file" << fst.fileName(); return false; } QString saveDirPath = QFileDialog::getExistingDirectory(nullptr, "Save Model", "", QFileDialog::ShowDirsOnly); if (saveDirPath.isEmpty()) { qCDebug(interfaceapp) << "Invalid directory" << saveDirPath; return false; } QDir saveDir(saveDirPath); copyDirectoryContent(tempDir, saveDir); return true; }
void terrama2::core::DataRetrieverFTP::retrieveDataCallback(const std::string& mask, const Filter& filter, const std::string& timezone, std::shared_ptr<terrama2::core::FileRemover> remover, const std::string& temporaryFolderUri, const std::string& foldersMask, std::function<void(const std::string &, const std::string &, const std::string&)> processFile) const { try { // find valid directories std::vector< std::string > baseUriList; baseUriList.push_back(dataProvider_->uri); auto tz = timezone.empty() ? "UTC+00" : timezone; if(!foldersMask.empty()) { auto uriList = getFoldersList(baseUriList, foldersMask, tz, filter); if(uriList.empty()) { QString errMsg = QObject::tr("No files found!"); TERRAMA2_LOG_WARNING() << errMsg; throw terrama2::core::NoDataException() << ErrorDescription(errMsg); } baseUriList = uriList; } // Build URI to get PATH fragment te::core::URI dataProviderURI(dataProvider_->uri); // Set temporary directory. When empty, creates a new pointing to dataProvider Path. // In this way, we will have something like "temporaryDir/dataProviderPath" // It is important due the folder may contains temporal mask std::string temporaryDataDir = temporaryFolderUri; if (temporaryFolderUri.empty()) temporaryDataDir = getTemporaryFolder(remover, temporaryFolderUri) + dataProviderURI.path(); // flag if there is any files for the dataset bool hasData = false; // Get a file listing from server for(const auto& uri : baseUriList) { std::vector<std::string> vectorFiles = curlwrapper_->listFiles(normalizeURI(uri)); std::vector<std::string> vectorNames; // filter file names that should be downloaded. for(const std::string& fileName: vectorFiles) { // FIXME: use timestamp std::shared_ptr< te::dt::TimeInstantTZ > timestamp; if(terrama2::core::isValidDataSetName(mask,filter, tz, fileName,timestamp)) vectorNames.push_back(fileName); } if(vectorNames.empty()) { continue; } hasData = true; te::core::URI u(uri); std::string uriPath = QString::fromStdString(u.path()).replace(dataProviderURI.path().c_str(), "/").toStdString(); // Performs the download of files in the vectorNames for(const auto& file: vectorNames) { // Create directory struct QString saveDir(QString::fromStdString(temporaryDataDir+ "/" + uriPath)); QString savePath = QUrl(saveDir).toLocalFile(); QDir dir(savePath); if(!dir.exists()) dir.mkpath(savePath); std::string uriOrigin = uri + "/" + file; std::string filePath = savePath.toStdString() + "/" + file; remover->addTemporaryFolder(temporaryDataDir); remover->addTemporaryFile(filePath); try { curlwrapper_->downloadFile(normalizeURI(uriOrigin).uri(), filePath); TERRAMA2_LOG_WARNING() << QObject::tr("Finished downloading file: %1").arg(QString::fromStdString(file)); processFile(temporaryDataDir, file, uriPath); } catch(const te::Exception& e) { QString errMsg = QObject::tr("Error during download of file %1.\n").arg(QString::fromStdString(file)); auto errStr = boost::get_error_info<te::ErrorDescription>(e); if(errStr) errMsg.append(QString::fromStdString(*errStr)); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } } } if(!hasData) { QString errMsg = QObject::tr("No data in the remote server."); TERRAMA2_LOG_WARNING() << errMsg; throw NoDataException() << ErrorDescription(errMsg); } } catch(const NoDataException&) { throw; } catch(const DataRetrieverException&) { throw; } catch(const te::Exception& e) { QString errMsg = QObject::tr("Error during download.\n"); errMsg.append(boost::get_error_info<terrama2::ErrorDescription>(e)); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } catch(const std::exception& e) { QString errMsg = QObject::tr("Error during download.\n"); errMsg.append(e.what()); TERRAMA2_LOG_ERROR() << errMsg; throw DataRetrieverException() << ErrorDescription(errMsg); } catch(...) { throw DataRetrieverException() << ErrorDescription(QObject::tr("Unknown Error.")); } }