From: Andrzej Popowski Date: Mon, 23 Feb 2015 11:04:11 +0000 (+0100) Subject: [Archive] - removing try catch X-Git-Tag: submit/tizen_tv/20150603.064601~1^2~320 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=cb2d6cb8b36787e0895e5de3f793350f3d747a9d;p=platform%2Fcore%2Fapi%2Fwebapi-plugins.git [Archive] - removing try catch Change-Id: I6ebfc005dfb6e0429931da579c4d3718983225c1 Signed-off-by: Andrzej Popowski --- diff --git a/src/archive/archive_api.js b/src/archive/archive_api.js index 722bddde..fd476599 100644 --- a/src/archive/archive_api.js +++ b/src/archive/archive_api.js @@ -212,7 +212,7 @@ function ArchiveFileEntry(data, priv) { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } }, @@ -307,7 +307,7 @@ function ArchiveFile(data) { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } }, @@ -362,7 +362,7 @@ function ArchiveFile(data) { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } }, @@ -410,7 +410,7 @@ function ArchiveFile(data) { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } } @@ -446,7 +446,7 @@ function ArchiveFile(data) { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } } @@ -518,7 +518,7 @@ ArchiveManager.prototype.open = function () { if (args.onerror) { args.onerror.call( null, - new tizen.WebAPIException(e.code, e.message, e.name) + new tizen.WebAPIException(e) ); } } diff --git a/src/archive/archive_callback_data.cc b/src/archive/archive_callback_data.cc index 776fe2c0..a56fa29e 100755 --- a/src/archive/archive_callback_data.cc +++ b/src/archive/archive_callback_data.cc @@ -23,7 +23,6 @@ #include "common/logger.h" -//#include #include "archive_file.h" #include "archive_utils.h" #include "un_zip.h" @@ -60,13 +59,13 @@ OperationCallbackData::~OperationCallbackData() } } -void OperationCallbackData::setError(const std::string &err_name, +void OperationCallbackData::setError(const ErrorCode &err_code, const std::string &err_message) { LoggerD("Entered"); //store only first error if (!m_is_error) { - m_err_name = err_name; + m_err_code = err_code; m_err_message = err_message; m_is_error = true; } @@ -120,10 +119,10 @@ void OperationCallbackData::setIsCanceled(bool canceled) m_is_canceled = canceled; } -const std::string& OperationCallbackData::getErrorName() const +const ErrorCode& OperationCallbackData::getErrorCode() const { LoggerD("Entered"); - return m_err_name; + return m_err_code; } const std::string& OperationCallbackData::getErrorMessage() const @@ -163,22 +162,27 @@ OpenCallbackData::~OpenCallbackData() LoggerD("Entered"); } -void OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerE("Entered"); filesystem::FilePtr file = archive_file_ptr->getFile(); if (!file) { LoggerE("File is null"); - throw UnknownException("File is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is null"); } filesystem::NodePtr node = file->getNode(); if(!node) { LoggerE("Node is null"); - throw UnknownException("Node is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Node is null"); } const FileMode fm = archive_file_ptr->m_file_mode; - if (0 == node->getSize()) { + unsigned long long size = 0; + PlatformResult result = node->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + if (0 == size) { if(FileMode::READ_WRITE == fm || FileMode::WRITE == fm || FileMode::ADD == fm) { @@ -197,19 +201,23 @@ void OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) } else { LoggerE("The file is empty throwing: InvalidValuesException - Invalid ZIP archive"); - throw InvalidValuesException("Invalid ZIP archive"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Invalid ZIP archive"); } } else { archive_file_ptr->setIsOpen(true); - archive_file_ptr->updateListOfEntries(); + result = archive_file_ptr->updateListOfEntries(); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } } guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); if (!id) { LoggerE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- @@ -237,7 +245,7 @@ void GetEntriesCallbackData::setEntries(ArchiveFileEntryPtrMapPtr entries) m_entries = entries; } -void GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerD("Entered"); @@ -246,8 +254,9 @@ void GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) guint id = g_idle_add(ArchiveFile::getEntriesTaskCompleteCB, this); if (!id) { LoggerE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- @@ -287,7 +296,7 @@ void GetEntryByNameCallbackData::setFileEntry(ArchiveFileEntryPtr entry) m_file_entry = entry; } -void GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerD("Entered"); @@ -306,7 +315,7 @@ void GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_pt if (it == entries->end()) { LoggerE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); LoggerE("Throwing NotFoundException - Entry not found"); - throw NotFoundException("Entry not found"); + return PlatformResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); } setFileEntry(it->second); @@ -314,8 +323,9 @@ void GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_pt guint id = g_idle_add(ArchiveFile::getEntryByNameTaskCompleteCB, this); if (!id) { LoggerE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "g_idle_add fails"); } + return PlatformResult(ErrorCode::NO_ERROR); } //---------------------------------------------------------------------------------------- @@ -378,26 +388,18 @@ gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) std::unique_ptr cb_ptr(callback); - try { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - if (!callback->isError()) { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); + if (!callback->isError()) { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); - LoggerD("%s", val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } else { - LoggerW("Not calling error callback in such case"); - } - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occurred"); + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); + } else { + LoggerW("Not calling error callback in such case"); } callback->setArchiveFile(ArchiveFilePtr()); @@ -413,30 +415,22 @@ void BaseProgressCallback::callProgressCallback(long operationId, { LoggerD("Entered"); - try { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callbackId); - obj[JSON_DATA] = picojson::value(picojson::object()); - picojson::object& args = obj[JSON_DATA].get(); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callbackId); + obj[JSON_DATA] = picojson::value(picojson::object()); + picojson::object& args = obj[JSON_DATA].get(); - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_PROGRESS); - obj[JSON_CALLBACK_KEEP] = picojson::value(true); + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_PROGRESS); + obj[JSON_CALLBACK_KEEP] = picojson::value(true); - args[PARAM_OPERATION_ID] = picojson::value(static_cast(operationId)); - args[PARAM_VALUE] = picojson::value(value); - args[PARAM_FILENAME] = picojson::value(filename); + args[PARAM_OPERATION_ID] = picojson::value(static_cast(operationId)); + args[PARAM_VALUE] = picojson::value(value); + args[PARAM_FILENAME] = picojson::value(filename); - LoggerD("%s", val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occurred"); - } + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); } void BaseProgressCallback::callProgressCallbackOnMainThread(const double progress, @@ -477,22 +471,11 @@ gboolean BaseProgressCallback::callProgressCallbackCB(void* data) LoggerW("STUB Not checking if context is still alive"); - try { - //Error callback is being handled by ArchiveFile queue - see - //ArchiveFile::taskManagerThread function - // - ph->callback->callProgressCallback( - ph->callback->m_op_id, - ph->overall_progress, - ph->currently_processed_entry->getName(), - ph->callback->m_cid); - } - catch (const PlatformException &err) { - LoggerE("%s (%s)", err.name().c_str(), err.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occurs"); - } + ph->callback->callProgressCallback( + ph->callback->m_op_id, + ph->overall_progress, + ph->currently_processed_entry->getName(), + ph->callback->m_cid); return false; } @@ -552,27 +535,39 @@ const std::string& AddProgressCallback::getBaseVirtualPath() return m_base_virt_path; } -void AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerD("Entered"); if(!m_file_entry) { LoggerE("ArchiveFileEntry is not set in callback"); - throw UnknownException("Could not add file to archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive"); } if(!archive_file_ptr) { LoggerE("archive_file_ptr is NULL"); - throw UnknownException("Could not extract archive file entry"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry"); } AddProgressCallback* callback = this; - ZipPtr zip = archive_file_ptr->createZipObject(); - zip->addFile(callback); + ZipPtr zip; + PlatformResult result = archive_file_ptr->createZipObject(&zip); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + + result = zip->addFile(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + // Zip is no more needed but it locks file opening while // it is needed to read entries from file - zip->close(); + result = zip->close(); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } //We have just finished adding file to archive so now //this archive file should be valid .zip archive and @@ -583,11 +578,8 @@ void AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) // update informations about decompressed size and entry list // TODO FIXME need to resolve problem with access to file by // more than one thread - try{ - archive_file_ptr->updateListOfEntries(); - } catch(...){ - LoggerD("Unknown error during updating entries list inside archive"); - } + + return archive_file_ptr->updateListOfEntries(); } //---------------------------------------------------------------------------------------- @@ -672,10 +664,10 @@ double ExtractAllProgressCallback::getOverallProgress() const return m_progress_overall; } -void ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerD("Entered"); - archive_file_ptr->extractAllTask(this); + return archive_file_ptr->extractAllTask(this); } void ExtractAllProgressCallback::setExpectedDecompressedSize(unsigned long exp_dec_size) @@ -757,22 +749,27 @@ const std::string& ExtractEntryProgressCallback::getStripBasePath() const return m_strip_base_path; } -void ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) +PlatformResult ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) { LoggerD("Entered"); if(!m_archive_file_entry) { LoggerE("ArchiveFileEntry is not set in callback"); - throw UnknownException("Could not extract archive file entry"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry"); } if(!archive_file_ptr) { LoggerE("archive_file_ptr is NULL"); - throw UnknownException("Could not extract archive file entry"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry"); + } + + UnZipPtr unzip; + PlatformResult result = archive_file_ptr->createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - UnZipPtr unzip = archive_file_ptr->createUnZipObject(); - unzip->extractTo(this); + return unzip->extractTo(this); } } //namespace archive diff --git a/src/archive/archive_callback_data.h b/src/archive/archive_callback_data.h index a77c3539..44027572 100644 --- a/src/archive/archive_callback_data.h +++ b/src/archive/archive_callback_data.h @@ -26,11 +26,10 @@ #include #include -#include "common/platform_exception.h" +#include "common/platform_result.h" #include "filesystem_file.h" #include "archive_file_entry.h" - namespace extension { namespace archive { @@ -60,10 +59,10 @@ public: OperationCallbackData(ArchiveCallbackType callback_type); virtual ~OperationCallbackData(); - void setError(const std::string &err_name, + void setError(const ErrorCode &err_code, const std::string &err_message); bool isError() const; - const std::string& getErrorName() const; + const ErrorCode& getErrorCode() const; const std::string& getErrorMessage() const; void setOperationId(long op_id); @@ -75,7 +74,7 @@ public: ArchiveCallbackType getCallbackType() const; - virtual void executeOperation(ArchiveFilePtr archive_file_ptr) = 0; + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; ArchiveFilePtr getArchiveFile() const; void setArchiveFile(ArchiveFilePtr caller); @@ -92,7 +91,7 @@ protected: private: bool m_is_error; bool m_is_canceled; - std::string m_err_name; + ErrorCode m_err_code; std::string m_err_message; ArchiveFilePtr m_caller_instance; @@ -104,7 +103,7 @@ public: OpenCallbackData(ArchiveCallbackType callback_type = OPEN_CALLBACK_DATA); virtual ~OpenCallbackData(); - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); private: std::string m_filename; @@ -119,7 +118,7 @@ public: ArchiveFileEntryPtrMapPtr getEntries() const; void setEntries(ArchiveFileEntryPtrMapPtr entries); - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); private: ArchiveFileEntryPtrMapPtr m_entries; @@ -137,7 +136,7 @@ public: ArchiveFileEntryPtr getFileEntry() const; void setFileEntry(ArchiveFileEntryPtr entry); - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); private: std::string m_name; ArchiveFileEntryPtr m_file_entry; @@ -150,8 +149,6 @@ public: BaseProgressCallback(ArchiveCallbackType callback_type = BASE_PROGRESS_CALLBACK); virtual ~BaseProgressCallback(); - //void setProgressCallback(JSValueRef on_progress); - bool getOverwrite() const; void setOverwrite(bool overwrite); @@ -159,7 +156,7 @@ public: ArchiveFileEntryPtr current_entry); void callSuccessCallbackOnMainThread(); - virtual void executeOperation(ArchiveFilePtr archive_file_ptr) = 0; + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr) = 0; protected: void callProgressCallback(long operationId, @@ -180,7 +177,7 @@ public: AddProgressCallback(ArchiveCallbackType callback_type = ADD_PROGRESS_CALLBACK); virtual ~AddProgressCallback(); - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); void setBasePath(const std::string& path); const std::string& getBasePath(); @@ -212,7 +209,7 @@ public: double getCurrentFileProgress() const; double getOverallProgress() const; - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); void setExpectedDecompressedSize(unsigned long exp_dec_size); unsigned long getExpectedDecompressedSize() const; @@ -258,7 +255,7 @@ public: void setStripBasePath(const std::string& strip_base_path); const std::string& getStripBasePath() const; - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); + virtual PlatformResult executeOperation(ArchiveFilePtr archive_file_ptr); private: ArchiveFileEntryPtr m_archive_file_entry; diff --git a/src/archive/archive_file.cc b/src/archive/archive_file.cc index c728d761..f3088d5d 100644 --- a/src/archive/archive_file.cc +++ b/src/archive/archive_file.cc @@ -18,7 +18,6 @@ #include "common/picojson.h" #include "common/logger.h" -#include "common/platform_exception.h" #include "archive_manager.h" #include "archive_utils.h" @@ -93,43 +92,43 @@ gboolean ArchiveFile::openTaskCompleteCB(void *data) return false; } - try { - auto archive_file = callback->getArchiveFile(); + auto archive_file = callback->getArchiveFile(); - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - obj[JSON_DATA] = picojson::value(picojson::object()); - - picojson::object& args = obj[JSON_DATA].get(); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + obj[JSON_DATA] = picojson::value(picojson::object()); - if (!callback->isError()) { - long handle = ArchiveManager::getInstance().addPrivData(archive_file); + picojson::object& args = obj[JSON_DATA].get(); - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); + if (!callback->isError()) { + long handle = ArchiveManager::getInstance().addPrivData(archive_file); - args[ARCHIVE_FILE_ATTR_MODE] = picojson::value( - fileModeToString(archive_file->getFileMode())); - args[ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE] = picojson::value(); - args[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(handle)); - } else { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); - args[ERROR_CALLBACK_NAME] = picojson::value(callback->getErrorName()); - args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); + std::string fm_str; + PlatformResult result = fileModeToString(archive_file->getFileMode(), &fm_str); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("%s (%d)", result.message().c_str(), result.error_code()); + delete callback; + callback = NULL; + return false; } - LoggerD("%s", val.serialize().c_str()); + args[ARCHIVE_FILE_ATTR_MODE] = picojson::value(fm_str); + args[ARCHIVE_FILE_ATTR_DECOMPRESSED_SIZE] = picojson::value(); + args[ARCHIVE_FILE_HANDLE] = picojson::value(static_cast(handle)); + } else { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occurred"); + args[ERROR_CALLBACK_CODE] = picojson::value(static_cast(callback->getErrorCode())); + args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); } + LoggerD("%s", val.serialize().c_str()); + + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); + delete callback; callback = NULL; @@ -146,33 +145,25 @@ gboolean ArchiveFile::callErrorCallback(void* data) return false; } - try { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - obj[JSON_DATA] = picojson::value(picojson::object()); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + obj[JSON_DATA] = picojson::value(picojson::object()); - picojson::object& args = obj[JSON_DATA].get(); + picojson::object& args = obj[JSON_DATA].get(); - if (!callback->isError()) { - LoggerW("The success callback should be not be called in this case"); - } else { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); + if (!callback->isError()) { + LoggerW("The success callback should be not be called in this case"); + } else { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); - args[ERROR_CALLBACK_NAME] = picojson::value(callback->getErrorName()); - args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); - } + args[ERROR_CALLBACK_CODE] = picojson::value(static_cast(callback->getErrorCode())); + args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); + } - LoggerD("%s", val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occured"); - } + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); delete callback; callback = NULL; @@ -196,52 +187,43 @@ void* ArchiveFile::taskManagerThread(void *data) return NULL; } + PlatformResult result(ErrorCode::NO_ERROR); + while(true){ OperationCallbackData* callback = NULL; - bool call_error_callback = false; - try{ - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - if(archive_file_holder->ptr->m_task_queue.empty()){ - break; - } - callback = archive_file_holder->ptr->m_task_queue.back().second; - } - if(callback && !callback->isCanceled()){ - callback->executeOperation(archive_file_holder->ptr); - } - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } - } catch (const OperationCanceledException &err) { - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); + + result = PlatformResult(ErrorCode::NO_ERROR); + + { + std::lock_guard lock(archive_file_holder->ptr->m_mutex); + if(archive_file_holder->ptr->m_task_queue.empty()){ + break; } + callback = archive_file_holder->ptr->m_task_queue.back().second; + } + + if(callback && !callback->isCanceled()){ + result = callback->executeOperation(archive_file_holder->ptr); + } + + if (ErrorCode::OPERATION_CANCELED_ERR == result.error_code()) { delete callback; callback = NULL; - } catch (const PlatformException &err) { - LoggerE("taskManagerThread fails, %s: %s", err.name().c_str(), - err.message().c_str()); - callback->setError(err.name().c_str(), err.message().c_str()); - call_error_callback = true; - } catch (...) { - LoggerE("taskManagerThread fails"); - callback->setError("UnknownError", "UnknownError"); - call_error_callback = true; - } - if(call_error_callback) { - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } + } else if (ErrorCode::NO_ERROR != result.error_code()) { + LoggerE("taskManagerThread fails, %d: %s", result.error_code(), + result.message().c_str()); + callback->setError(result.error_code(), result.message().c_str()); if (!g_idle_add(callErrorCallback, static_cast(callback))) { LoggerE("g_idle_add fails"); delete callback; callback = NULL; } } + + { + std::lock_guard lock(archive_file_holder->ptr->m_mutex); + archive_file_holder->ptr->m_task_queue.pop_back(); + } } delete archive_file_holder; @@ -250,7 +232,7 @@ void* ArchiveFile::taskManagerThread(void *data) return NULL; } -void ArchiveFile::addOperation(OperationCallbackData* callback) +PlatformResult ArchiveFile::addOperation(OperationCallbackData* callback) { LoggerD("Entered callback type:%d", callback->getCallbackType()); @@ -267,7 +249,7 @@ void ArchiveFile::addOperation(OperationCallbackData* callback) ArchiveFileHolder* holder = new(std::nothrow) ArchiveFileHolder(); if(!holder) { LoggerE("Memory allocation error"); - throw UnknownException("Memory allocation error"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); } holder->ptr = shared_from_this(); if (pthread_create(&thread, NULL, taskManagerThread, @@ -275,43 +257,49 @@ void ArchiveFile::addOperation(OperationCallbackData* callback) LoggerE("Thread creation failed"); delete holder; holder = NULL; - throw UnknownException("Thread creation failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Thread creation failed"); } if (pthread_detach(thread)) { LoggerE("Thread detachment failed"); } } + return PlatformResult(ErrorCode::NO_ERROR); } -void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) +PlatformResult ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) { filesystem::FilePtr directory = callback->getDirectory(); if(!directory) { LoggerE("Directory is null"); - throw UnknownException("Directory is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Directory is null"); } else { if(!directory->getNode()){ LoggerE("Node in directory is null"); - throw UnknownException("Node is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Node is null"); } } if(!m_file) { LoggerE("File is null"); - throw UnknownException("File is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is null"); } else { if(!m_file->getNode()){ LoggerE("Node in file is null"); - throw UnknownException("Node in file is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Node in file is null"); } } // For explanation please see: // ArchiveFile.h m_created_as_new_empty_archive description // - if(m_file->getNode()->getSize() == 0) { + unsigned long long size = 0; + PlatformResult result = m_file->getNode()->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + if(size == 0) { LoggerD("Zip file: %s is empty", m_file->getNode()->getPath()->getFullPath().c_str()); @@ -319,30 +307,38 @@ void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) //We do not call progress callback since we do not have any ArchiveFileEntry callback->callSuccessCallbackOnMainThread(); callback = NULL; - return; + return PlatformResult(ErrorCode::NO_ERROR); } else { LoggerW("m_created_as_new_empty_archive is false"); LoggerE("Throwing InvalidStateException: File is not valid ZIP archive"); - throw InvalidStateException("File is not valid ZIP archive"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive"); } } - UnZipPtr unzip = createUnZipObject(); - unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); + UnZipPtr unzip; + result = createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + + return unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); } -void ArchiveFile::getEntries(GetEntriesCallbackData* callback) +PlatformResult ArchiveFile::getEntries(GetEntriesCallbackData* callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Could not get list of files in archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not get list of files in archive"); } - throwInvalidStateErrorIfArchiveFileIsClosed(); + if(!m_is_open){ + LoggerE("ArchiveFile closed - operation not permitted"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); + } - addOperation(callback); + return addOperation(callback); } gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) @@ -356,79 +352,74 @@ gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) return false; } - try { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - - if (!callback->isError()) { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); - obj[JSON_DATA] = picojson::value(picojson::array()); - picojson::array &arr = obj[JSON_DATA].get(); - - ArchiveFileEntryPtrMapPtr entries = callback->getEntries(); - for(auto it = entries->begin(); it != entries->end(); it++) { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - - obj[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value( - it->second->getName()); - obj[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( - static_cast(it->second->getSize())); - obj[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( - static_cast(it->second->getModified())); - obj[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( - static_cast(it->second->getCompressedSize())); - obj[ARCHIVE_FILE_HANDLE] = picojson::value( - static_cast(callback->getHandle())); - - arr.push_back(val); - } - } else { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); - obj[JSON_DATA] = picojson::value(picojson::object()); - picojson::object& args = obj[JSON_DATA].get(); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + + if (!callback->isError()) { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); + obj[JSON_DATA] = picojson::value(picojson::array()); + picojson::array &arr = obj[JSON_DATA].get(); + + ArchiveFileEntryPtrMapPtr entries = callback->getEntries(); + for(auto it = entries->begin(); it != entries->end(); it++) { + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + + obj[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value( + it->second->getName()); + obj[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( + static_cast(it->second->getSize())); + obj[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( + static_cast(it->second->getModified())); + obj[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( + static_cast(it->second->getCompressedSize())); + obj[ARCHIVE_FILE_HANDLE] = picojson::value( + static_cast(callback->getHandle())); - args[ERROR_CALLBACK_NAME] = picojson::value(callback->getErrorName()); - args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); + arr.push_back(val); } + } else { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); + obj[JSON_DATA] = picojson::value(picojson::object()); + picojson::object& args = obj[JSON_DATA].get(); - LoggerD("%s", val.serialize().c_str()); - - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occured"); + args[ERROR_CALLBACK_CODE] = picojson::value(static_cast(callback->getErrorCode())); + args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); } + LoggerD("%s", val.serialize().c_str()); + + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); + delete callback; callback = NULL; return false; } -void ArchiveFile::extractAll(ExtractAllProgressCallback *callback) +PlatformResult ArchiveFile::extractAll(ExtractAllProgressCallback *callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Could not extract all files from archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract all files from archive"); } - throwInvalidStateErrorIfArchiveFileIsClosed(); + if(!m_is_open){ + LoggerE("ArchiveFile closed - operation not permitted"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); + } - addOperation(callback); + return addOperation(callback); } -void ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) +PlatformResult ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Could not extract archive file entry"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry"); } // FIXME according to documentation: @@ -436,31 +427,33 @@ void ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) // but method extract() from ArchiveFileEntryObject is not permitted to throw above exception // uncomment in case when this method have permission to throwing InvalidStateError - // throwInvalidStateErrorIfArchiveFileisClosed(); if(!m_is_open) { LoggerE("Archive is not opened"); - throw UnknownException("Archive is not opened"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Archive is not opened"); } - addOperation(callback); + return addOperation(callback); } -void ArchiveFile::add(AddProgressCallback *callback) +PlatformResult ArchiveFile::add(AddProgressCallback *callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Could not add file to archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive"); } if(FileMode::READ == m_file_mode) { LoggerE("Trying to add file when READ access mode selected"); - throw InvalidAccessException("Add not allowed for \"r\" access mode"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Add not allowed for \"r\" access mode"); } - throwInvalidStateErrorIfArchiveFileIsClosed(); + if(!m_is_open){ + LoggerE("ArchiveFile closed - operation not permitted"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); + } - addOperation(callback); + return addOperation(callback); } void ArchiveFile::close() @@ -475,17 +468,20 @@ void ArchiveFile::close() return; } -void ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) +PlatformResult ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Could not get archive file entries by name"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not get archive file entries by name"); } - throwInvalidStateErrorIfArchiveFileIsClosed(); + if(!m_is_open){ + LoggerE("ArchiveFile closed - operation not permitted"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "ArchiveFile closed - operation not permitted"); + } - addOperation(callback); + return addOperation(callback); } gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) @@ -498,44 +494,36 @@ gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) return false; } - try { - picojson::value val = picojson::value(picojson::object()); - picojson::object& obj = val.get(); - obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); - obj[JSON_DATA] = picojson::value(picojson::object()); - picojson::object& args = obj[JSON_DATA].get(); + picojson::value val = picojson::value(picojson::object()); + picojson::object& obj = val.get(); + obj[JSON_CALLBACK_ID] = picojson::value(callback->getCallbackId()); + obj[JSON_DATA] = picojson::value(picojson::object()); + picojson::object& args = obj[JSON_DATA].get(); - if (!callback->isError()) { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); + if (!callback->isError()) { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_SUCCCESS); - ArchiveFileEntryPtr ent = callback->getFileEntry(); + ArchiveFileEntryPtr ent = callback->getFileEntry(); - args[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value(ent->getName()); - args[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( - static_cast(ent->getSize())); - args[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( - static_cast(ent->getModified())); - args[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( - static_cast(ent->getCompressedSize())); - args[ARCHIVE_FILE_HANDLE] = picojson::value( - static_cast(callback->getHandle())); - } else { - obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); + args[ARCHIVE_FILE_ENTRY_ATTR_NAME] = picojson::value(ent->getName()); + args[ARCHIVE_FILE_ENTRY_ATTR_SIZE] = picojson::value( + static_cast(ent->getSize())); + args[ARCHIVE_FILE_ENTRY_ATTR_MODIFIED] = picojson::value( + static_cast(ent->getModified())); + args[ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE] = picojson::value( + static_cast(ent->getCompressedSize())); + args[ARCHIVE_FILE_HANDLE] = picojson::value( + static_cast(callback->getHandle())); + } else { + obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); - args[ERROR_CALLBACK_NAME] = picojson::value(callback->getErrorName()); - args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); - } + args[ERROR_CALLBACK_CODE] = picojson::value(static_cast(callback->getErrorCode())); + args[ERROR_CALLBACK_MESSAGE] = picojson::value(callback->getErrorMessage()); + } - LoggerD("%s", val.serialize().c_str()); + LoggerD("%s", val.serialize().c_str()); - ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); - } - catch (const PlatformException& ex) { - LoggerE("%s (%s)", ex.name().c_str(), ex.message().c_str()); - } - catch (...) { - LoggerE("Unknown error occured"); - } + ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); delete callback; callback = NULL; @@ -619,51 +607,48 @@ void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) } } -UnZipPtr ArchiveFile::createUnZipObject() +PlatformResult ArchiveFile::createUnZipObject(UnZipPtr* unzip) { LoggerD("Entered"); if(!m_is_open) { LoggerE("File is not opened"); - throw UnknownException("File is not opened"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); } if (!m_file) { LoggerE("m_file is null"); - throw UnknownException("File is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is null"); } filesystem::NodePtr node = m_file->getNode(); if(!node) { LoggerE("Node is null"); - throw UnknownException("Node is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is null"); } - UnZipPtr unzip = UnZip::open(m_file->getNode()->getPath()->getFullPath()); - return unzip; + return UnZip::open(m_file->getNode()->getPath()->getFullPath(), unzip); } -ZipPtr ArchiveFile::createZipObject() +PlatformResult ArchiveFile::createZipObject(ZipPtr* zip) { LoggerD("Entered"); if(!m_is_open) { LoggerE("File is not opened"); - throw UnknownException("File is not opened"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is not opened"); } if (!m_file) { LoggerE("m_file is null"); - throw UnknownException("File is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "File is null"); } filesystem::NodePtr node = m_file->getNode(); if(!node) { LoggerE("Node is null"); - throw UnknownException("Node is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Node is null"); } - ZipPtr zip = Zip::open(m_file->getNode()->getPath()->getFullPath()); - return zip; - + return Zip::open(m_file->getNode()->getPath()->getFullPath(), zip); } bool ArchiveFile::isAllowedOperation(const std::string& method_name) @@ -688,15 +673,6 @@ void ArchiveFile::setFileMode(FileMode file_mode) m_file_mode = file_mode; } -void ArchiveFile::throwInvalidStateErrorIfArchiveFileIsClosed() const -{ - if(!m_is_open){ - LoggerE("ArchiveFile closed - operation not permitted"); - throw InvalidStateException( - "ArchiveFile closed - operation not permitted"); - } -} - void ArchiveFile::setCreatedAsNewEmptyArchive(bool new_and_empty) { m_created_as_new_empty_archive = new_and_empty; @@ -707,31 +683,48 @@ bool ArchiveFile::isCreatedAsNewEmptyArchive() const return m_created_as_new_empty_archive; } -void ArchiveFile::updateListOfEntries() +PlatformResult ArchiveFile::updateListOfEntries() { // For explanation please see: // ArchiveFile.h m_created_as_new_empty_archive description // - if(m_file->getNode()->getSize() == 0) { + unsigned long long size = 0; + PlatformResult result = m_file->getNode()->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + + if(size == 0) { LoggerD("Zip file: %s is empty", m_file->getNode()->getPath()->getFullPath().c_str()); if(m_created_as_new_empty_archive) { LoggerD("OK this is empty archive = nothing to do yet"); - return; + return PlatformResult(ErrorCode::NO_ERROR); } else { LoggerW("m_created_as_new_empty_archive is false"); LoggerE("Throwing InvalidStateException: File is not valid ZIP archive"); - throw InvalidStateException("File is not valid ZIP archive"); + return PlatformResult(ErrorCode::INVALID_STATE_ERR, "File is not valid ZIP archive"); } } - UnZipPtr unzip = createUnZipObject(); + UnZipPtr unzip; + result = createUnZipObject(&unzip); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + unsigned long decompressedSize = 0; - ArchiveFileEntryPtrMapPtr emap = unzip->listEntries(&decompressedSize); + ArchiveFileEntryPtrMapPtr emap; + result = unzip->listEntries(&decompressedSize, &emap); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + setEntryMap(emap); setDecompressedSize(decompressedSize); + return PlatformResult(ErrorCode::NO_ERROR); } bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, diff --git a/src/archive/archive_file.h b/src/archive/archive_file.h index 9efd712b..ea5bcf70 100755 --- a/src/archive/archive_file.h +++ b/src/archive/archive_file.h @@ -79,10 +79,10 @@ public: ArchiveFile(FileMode file_mode); virtual ~ArchiveFile(); - void getEntries(GetEntriesCallbackData* callback); - void getEntryByName(GetEntryByNameCallbackData* callback); - void extractAll(ExtractAllProgressCallback *callback); - void add(AddProgressCallback *callback); + common::PlatformResult getEntries(GetEntriesCallbackData* callback); + common::PlatformResult getEntryByName(GetEntryByNameCallbackData* callback); + common::PlatformResult extractAll(ExtractAllProgressCallback *callback); + common::PlatformResult add(AddProgressCallback *callback); void close(); filesystem::FilePtr getFile() const; @@ -100,27 +100,20 @@ public: bool* out_is_directory = NULL, std::string* out_matching_name = NULL); - //Used by ArchiveFileEntry - void extractEntryTo(ExtractEntryProgressCallback* callback); + common::PlatformResult extractEntryTo(ExtractEntryProgressCallback* callback); bool isAllowedOperation(const std::string& method_name); FileMode getFileMode() const; void setFileMode(FileMode file_mode); - /** - * \brief Throw InvalidStateError in case when ArchiveFile is closed - */ - void throwInvalidStateErrorIfArchiveFileIsClosed() const; - void setCreatedAsNewEmptyArchive(bool new_and_empty); bool isCreatedAsNewEmptyArchive() const; - - void updateListOfEntries(); + PlatformResult updateListOfEntries(); private: - UnZipPtr createUnZipObject(); - ZipPtr createZipObject(); + PlatformResult createUnZipObject(UnZipPtr* unzip); + PlatformResult createZipObject(ZipPtr* zip); std::deque m_task_queue; std::mutex m_mutex; @@ -140,7 +133,6 @@ private: bool m_overwrite; ArchiveFileEntryPtrMapPtr m_entry_map; - /** * If we execute tizen.open(destFile , "w"/"rw"/ "a", ..., {overwrite: true}), * destFile will be empty file with size = 0, which cannot be @@ -165,10 +157,10 @@ private: static gboolean getEntryByNameTaskCompleteCB(void *data); static void* taskManagerThread(void *data); - void addOperation(OperationCallbackData* callback); + common::PlatformResult addOperation(OperationCallbackData* callback); static gboolean callErrorCallback(void* data); - void extractAllTask(ExtractAllProgressCallback* callback); + PlatformResult extractAllTask(ExtractAllProgressCallback* callback); friend class ExtractAllProgressCallback; friend class UnZipExtractRequest; diff --git a/src/archive/archive_file_entry.cc b/src/archive/archive_file_entry.cc index 3715fec3..d293bc2f 100644 --- a/src/archive/archive_file_entry.cc +++ b/src/archive/archive_file_entry.cc @@ -137,11 +137,11 @@ ArchiveFile* ArchiveFileEntry::getArchiveFileNonProtectPtr() return m_archive; } -void ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) +PlatformResult ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) { if(!m_archive) { LOGE("m_archive is NULL"); - throw UnknownException("Could not extract archive file entry"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not extract archive file entry"); } //Callback should be associated with this instance of ArchiveFileEntry @@ -165,7 +165,7 @@ void ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) callback->setStripBasePath(base_path_name); } - m_archive->extractEntryTo(callback); + return m_archive->extractEntryTo(callback); } } // archive diff --git a/src/archive/archive_file_entry.h b/src/archive/archive_file_entry.h index 57831d9d..e2fb6d91 100755 --- a/src/archive/archive_file_entry.h +++ b/src/archive/archive_file_entry.h @@ -19,7 +19,7 @@ #define _TIZEN_ARCHIVE_ARCHIVE_FILE_ENTRY_H_ #include - +#include "common/platform_result.h" #include "filesystem_file.h" namespace extension { @@ -60,7 +60,7 @@ public: void setArchiveFileNonProtectPtr(ArchiveFile* ptr); ArchiveFile* getArchiveFileNonProtectPtr(); - void extractTo(ExtractEntryProgressCallback* callback); + common::PlatformResult extractTo(ExtractEntryProgressCallback* callback); private: filesystem::FilePtr m_file; diff --git a/src/archive/archive_instance.cc b/src/archive/archive_instance.cc index e76a7f96..137896a2 100644 --- a/src/archive/archive_instance.cc +++ b/src/archive/archive_instance.cc @@ -4,21 +4,17 @@ #include "archive/archive_instance.h" - //#include "archive_manager.h" #include #include - #include - #include "common/current_application.h" #include "common/picojson.h" #include "common/logger.h" #include "archive_callback_data.h" #include "archive_manager.h" #include "archive_utils.h" - #include "defs.h" namespace extension { @@ -62,8 +58,7 @@ ArchiveInstance::~ArchiveInstance() { LoggerD("Entered"); } - -void ArchiveInstance::PostError(const PlatformException& e, double callback_id) { +void ArchiveInstance::PostError(const PlatformResult& e, double callback_id) { picojson::value val = picojson::value(picojson::object()); picojson::object& obj = val.get(); obj[JSON_CALLBACK_ID] = picojson::value(callback_id); @@ -72,7 +67,7 @@ void ArchiveInstance::PostError(const PlatformException& e, double callback_id) picojson::object& args = obj[JSON_DATA].get(); obj[JSON_ACTION] = picojson::value(JSON_CALLBACK_ERROR); - args[ERROR_CALLBACK_NAME] = picojson::value(e.name()); + args[ERROR_CALLBACK_CODE] = picojson::value(static_cast(e.error_code())); args[ERROR_CALLBACK_MESSAGE] = picojson::value(e.message()); ArchiveInstance::getInstance().PostMessage(val.serialize().c_str()); @@ -90,107 +85,118 @@ void ArchiveInstance::Open(const picojson::value& args, picojson::object& out) { picojson::value v_overwrite = options.at(PARAM_OVERWRITE); const double callbackId = args.get(JSON_CALLBACK_ID).get(); const long operationId = static_cast(v_op_id.get()); - FileMode fm = stringToFileMode(v_mode.get()); + FileMode fm; + PlatformResult result = stringToFileMode(v_mode.get(), &fm); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("File mode conversions error"); + PostError(result, callbackId); + return; + } OpenCallbackData *callback = new OpenCallbackData(); - try { - FilePtr file_ptr; + FilePtr file_ptr; - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - bool overwrite = false; - if(v_overwrite.is()) { - overwrite = v_overwrite.get(); - } + bool overwrite = false; + if(v_overwrite.is()) { + overwrite = v_overwrite.get(); + } - std::string location_full_path = v_file.get(); - PathPtr path = Path::create(location_full_path); + std::string location_full_path = v_file.get(); + PathPtr path = Path::create(location_full_path); + + struct stat info; + if (lstat(path->getFullPath().c_str(), &info) == 0) { + NodePtr node; + result = Node::resolve(path, &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } - struct stat info; - if (lstat(path->getFullPath().c_str(), &info) == 0) { - NodePtr node; - try { - node = Node::resolve(path); - } catch (PlatformException& e) { - LoggerE("Filesystem exception - calling error callback"); - PostError(e, callbackId); + file_ptr = FilePtr(new File(node, File::PermissionList())); + LoggerD("open: %s mode: 0x%x overwrite: %d", location_full_path.c_str(), fm, overwrite); + if (FileMode::WRITE == fm || FileMode::READ_WRITE == fm) { + if (overwrite) { + LoggerD("Deleting existing file: %s", location_full_path.c_str()); + result = file_ptr->getNode()->remove(OPT_RECURSIVE); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Couldn't remove existing file: %s", location_full_path.c_str()); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } + file_ptr.reset(); //We need to create new empty file + } else if (FileMode::WRITE == fm) { + LoggerE("open: %s with mode: \"w\" file exists and overwrite is FALSE!" + " throwing InvalidModificationException", location_full_path.c_str()); + PostError(PlatformResult(ErrorCode::INVALID_MODIFICATION_ERR, + "Zip archive already exists"), callbackId); delete callback; callback = NULL; return; } - try { - file_ptr = FilePtr(new File(node, File::PermissionList())); - LoggerD("open: %s mode: 0x%x overwrite: %d", location_full_path.c_str(), fm, overwrite); - if(FileMode::WRITE == fm || FileMode::READ_WRITE == fm) { - if(overwrite) { - try { - LoggerD("Deleting existing file: %s", location_full_path.c_str()); - file_ptr->getNode()->remove(OPT_RECURSIVE); - file_ptr.reset(); //We need to create new empty file - } catch(...) { - LoggerE("Couldn't remove existing file: %s", location_full_path.c_str()); - throw IOException("Could not remove existing file"); - } - } - else if(FileMode::WRITE == fm) { - LoggerE("open: %s with mode: \"w\" file exists and overwrite is FALSE!" - " throwing InvalidModificationException", location_full_path.c_str()); - throw InvalidModificationException("Zip archive already exists"); - } - } - } catch (const NotFoundException& nfe) { - LoggerD("location_string: %s is not file reference", location_full_path.c_str()); - file_ptr.reset(); - } } + } - if (!file_ptr) { - NodePtr node_ptr; - - if(FileMode::WRITE == fm || - FileMode::READ_WRITE == fm || - FileMode::ADD == fm) { - LoggerD("Archive file not found - trying to create new one at: " - "full: %s", location_full_path.c_str()); + if (!file_ptr) { + NodePtr node_ptr; + if (FileMode::WRITE == fm || + FileMode::READ_WRITE == fm || + FileMode::ADD == fm) { + LoggerD("Archive file not found - trying to create new one at: " + "full: %s", location_full_path.c_str()); - std::string parent_path_string = path->getPath(); - PathPtr parent_path = Path::create(parent_path_string); - LoggerD("Parent path: %s", parent_path_string.c_str()); + std::string parent_path_string = path->getPath(); + PathPtr parent_path = Path::create(parent_path_string); + LoggerD("Parent path: %s", parent_path_string.c_str()); - NodePtr parent_node = Node::resolve(parent_path); - parent_node->setPermissions(PERM_READ | PERM_WRITE); - std::string filename = path->getName(); - LoggerD("File name: %s", filename.c_str()); - node_ptr = parent_node->createChild(Path::create(filename), NT_FILE); + NodePtr parent_node; + PlatformResult result = Node::resolve(parent_path, &parent_node); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; } - else { - LoggerE("Archive file not found"); - throw NotFoundException("Archive file not found"); + + parent_node->setPermissions(PERM_READ | PERM_WRITE); + std::string filename = path->getName(); + LoggerD("File name: %s", filename.c_str()); + result = parent_node->createChild(Path::create(filename), NT_FILE, &node_ptr); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Filesystem exception - calling error callback"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; } - file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); + } else { + LoggerE("Archive file not found"); + LoggerE("Filesystem exception - calling error callback"); + PostError(PlatformResult(ErrorCode::NOT_FOUND_ERR, "Archive file not found"), callbackId); + delete callback; + callback = NULL; + return; } + file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); + } - ArchiveFilePtr afp = ArchiveFilePtr(new ArchiveFile(fm)); - afp->setFile(file_ptr); - afp->setOverwrite(overwrite); - callback->setArchiveFile(afp); + ArchiveFilePtr afp = ArchiveFilePtr(new ArchiveFile(fm)); + afp->setFile(file_ptr); + afp->setOverwrite(overwrite); + callback->setArchiveFile(afp); - ArchiveManager::getInstance().open(callback); - } catch (PlatformException& e) { - LoggerE("Filesystem exception - calling error callback"); - PostError(e, callbackId); - delete callback; - callback = NULL; - return; - } catch (...) { - LoggerE("Exception occurred"); - delete callback; - callback = NULL; - throw; - } + ArchiveManager::getInstance().open(callback); } void ArchiveInstance::Abort(const picojson::value& args, picojson::object& out) @@ -226,41 +232,48 @@ void ArchiveInstance::Add(const picojson::value& args, picojson::object& out) AddProgressCallback *callback = new AddProgressCallback(); NodePtr node; - try { - node = Node::resolve(Path::create(v_source.get())); - } catch (PlatformException& e) { + PlatformResult result = Node::resolve(Path::create(v_source.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Filesystem exception - calling error callback"); - PostError(e, callbackId); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; + } + + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); + ArchiveFileEntryPtr afep = ArchiveFileEntryPtr(new ArchiveFileEntry(file_ptr)); + + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setFileEntry(afep); + + callback->setBasePath(file_ptr->getNode()->getPath()->getPath()); + LoggerD("base path:%s base virt:%s", callback->getBasePath().c_str(), + callback->getBaseVirtualPath().c_str()); + + ArchiveFilePtr priv; + result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); delete callback; callback = NULL; return; } - try { - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - ArchiveFileEntryPtr afep = ArchiveFileEntryPtr( - new ArchiveFileEntry(file_ptr)); - - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setFileEntry(afep); - - callback->setBasePath(file_ptr->getNode()->getPath()->getPath()); - LoggerD("base path:%s base virt:%s", callback->getBasePath().c_str(), - callback->getBaseVirtualPath().c_str()); - - ArchiveFilePtr priv = ArchiveManager::getInstance().getPrivData(handle); - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD)) { - LoggerE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - priv->add(callback); + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; } - catch (...) { + + result = priv->add(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Exception occurred"); delete callback; callback = NULL; - throw; + return; } } @@ -282,38 +295,47 @@ void ArchiveInstance::ExtractAll(const picojson::value& args, picojson::object& ExtractAllProgressCallback *callback = new ExtractAllProgressCallback(); NodePtr node; - try { - node = Node::resolve(Path::create(v_dest_dir.get())); - } catch (PlatformException& e) { + PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Filesystem exception - calling error callback"); - PostError(e, callbackId); + PostError(result, callbackId); delete callback; callback = NULL; return; } - try { - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - callback->setDirectory(file_ptr); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - if (v_overwrite.is()) { - callback->setOverwrite(v_overwrite.get()); - } + callback->setDirectory(file_ptr); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - ArchiveFilePtr priv = ArchiveManager::getInstance().getPrivData(handle); - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL)) { - LoggerE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - priv->extractAll(callback); + if (v_overwrite.is()) { + callback->setOverwrite(v_overwrite.get()); + } + + ArchiveFilePtr priv; + result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; } - catch (...) { + + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; + } + + result = priv->extractAll(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Exception occurred"); delete callback; callback = NULL; - throw; + return; } } @@ -332,24 +354,32 @@ void ArchiveInstance::GetEntries(const picojson::value& args, picojson::object& GetEntriesCallbackData *callback = new GetEntriesCallbackData(); - try { - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setHandle(handle); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setHandle(handle); - ArchiveFilePtr priv = ArchiveManager::getInstance().getPrivData(handle); - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES)) { - LoggerE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - priv->getEntries(callback); + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; } - catch (...) { + + result = priv->getEntries(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Exception occurred"); delete callback; callback = NULL; - throw; + return; } } @@ -369,25 +399,33 @@ void ArchiveInstance::GetEntryByName(const picojson::value& args, picojson::obje GetEntryByNameCallbackData *callback = new GetEntryByNameCallbackData(); - try { - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); - callback->setName(v_name.get()); - callback->setHandle(handle); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); + callback->setName(v_name.get()); + callback->setHandle(handle); - ArchiveFilePtr priv = ArchiveManager::getInstance().getPrivData(handle); - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME)) { - LoggerE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("Exception occurred"); + delete callback; + callback = NULL; + return; + } - priv->getEntryByName(callback); + if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME)) { + LoggerE("Not allowed operation"); + delete callback; + callback = NULL; + return; } - catch (...) { + + result = priv->getEntryByName(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Exception occurred"); delete callback; callback = NULL; - throw; + return; } } @@ -401,13 +439,16 @@ void ArchiveInstance::Close(const picojson::value& args, picojson::object& out) const long handle = static_cast(v_handle.get()); - try { - ArchiveFilePtr priv = ArchiveManager::getInstance().getPrivData(handle); - priv->close(); - ArchiveManager::getInstance().erasePrivData(handle); - } catch (...) { + ArchiveFilePtr priv; + PlatformResult result = ArchiveManager::getInstance().getPrivData(handle, &priv); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerD("Close method was called on already closed archive. Just end execution"); + LoggerD("%s", result.message().c_str()); } + + priv->close(); + ArchiveManager::getInstance().erasePrivData(handle); + ReportSuccess(out); } @@ -431,48 +472,55 @@ void ArchiveInstance::Extract(const picojson::value& args, picojson::object& out ExtractEntryProgressCallback *callback = new ExtractEntryProgressCallback(); NodePtr node; - try { - node = Node::resolve(Path::create(v_dest_dir.get())); - } catch (PlatformException& e) { + PlatformResult result = Node::resolve(Path::create(v_dest_dir.get()), &node); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Filesystem exception - calling error callback"); - PostError(e, callbackId); + PostError(result, callbackId); delete callback; callback = NULL; return; } - try { - FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - callback->setDirectory(file_ptr); - callback->setOperationId(operationId); - callback->setCallbackId(callbackId); + FilePtr file_ptr = FilePtr(new File(node, File::PermissionList())); - if (v_overwrite.is()) { - callback->setOverwrite(v_overwrite.get()); - } - if (v_strip_name.is()) { - callback->setStripName(v_strip_name.get()); - } - ArchiveFilePtr archive_file_ptr = ArchiveManager::getInstance().getPrivData(handle); - ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); - auto it = entries->find(v_entry_name.get()); - - //Not found but if our name does not contain '/' - //try looking for directory with such name - // - if (it == entries->end() && !isDirectoryPath(v_entry_name.get())) { - const std::string try_directory = v_entry_name.get() + "/"; - LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); - it = entries->find(try_directory); - } + callback->setDirectory(file_ptr); + callback->setOperationId(operationId); + callback->setCallbackId(callbackId); - it->second->extractTo(callback); + if (v_overwrite.is()) { + callback->setOverwrite(v_overwrite.get()); } - catch (...) { + if (v_strip_name.is()) { + callback->setStripName(v_strip_name.get()); + } + + ArchiveFilePtr archive_file_ptr; + result = ArchiveManager::getInstance().getPrivData(handle, &archive_file_ptr); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("Exception occurred"); delete callback; callback = NULL; - throw; + return; + } + + ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); + auto it = entries->find(v_entry_name.get()); + + //Not found but if our name does not contain '/' + //try looking for directory with such name + if (it == entries->end() && !isDirectoryPath(v_entry_name.get())) { + const std::string try_directory = v_entry_name.get() + "/"; + LoggerD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); + it = entries->find(try_directory); + } + + result = it->second->extractTo(callback); + if (result.error_code() != ErrorCode::NO_ERROR) { + LoggerE("ArchiveFileEntry.extractTo error"); + PostError(result, callbackId); + delete callback; + callback = NULL; + return; } } @@ -482,11 +530,13 @@ void ArchiveInstance::GetWidgetPaths(const picojson::value& args, picojson::obje pkgmgrinfo_pkginfo_h handle = NULL; if (PMINFO_R_OK != pkgmgrinfo_pkginfo_get_pkginfo(pkg_id.c_str(), &handle)) { - throw UnknownException("Error while getting package info"); + ReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Error while getting package info"), &out); + return; } if (PMINFO_R_OK != pkgmgrinfo_pkginfo_get_root_path(handle, &root_path)) { - throw UnknownException("Error while getting package info"); + ReportError(PlatformResult(ErrorCode::UNKNOWN_ERR, "Error while getting package info"), &out); + return; } // Construction of the response diff --git a/src/archive/archive_instance.h b/src/archive/archive_instance.h index 648f1188..635a4070 100644 --- a/src/archive/archive_instance.h +++ b/src/archive/archive_instance.h @@ -7,6 +7,7 @@ #include "common/extension.h" #include "common/platform_exception.h" +#include "common/platform_result.h" namespace extension { namespace archive { @@ -39,6 +40,7 @@ private: void GetWidgetPaths(const picojson::value& args, picojson::object& out); void PostError(const common::PlatformException& e, double callback_id); + void PostError(const common::PlatformResult& e, double callback_id); }; } // namespace archive diff --git a/src/archive/archive_manager.cc b/src/archive/archive_manager.cc index 3cf818a8..8fc24282 100644 --- a/src/archive/archive_manager.cc +++ b/src/archive/archive_manager.cc @@ -15,9 +15,7 @@ // limitations under the License. // #include "archive_manager.h" - #include - #include "common/logger.h" #include "filesystem_file.h" @@ -83,13 +81,14 @@ long ArchiveManager::addPrivData(ArchiveFilePtr archive_file_ptr) return handle; } -ArchiveFilePtr ArchiveManager::getPrivData(long handle) +PlatformResult ArchiveManager::getPrivData(long handle, ArchiveFilePtr* archive_file) { ArchiveFileMap::iterator it = m_priv_map.find(handle); if (it != m_priv_map.end()) { - return it->second; + *archive_file = it->second; + return PlatformResult(ErrorCode::NO_ERROR); } - throw UnknownException("Priv is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Priv is null"); } long ArchiveManager::open(OpenCallbackData* callback) diff --git a/src/archive/archive_manager.h b/src/archive/archive_manager.h index 1644a00e..4f6a0714 100755 --- a/src/archive/archive_manager.h +++ b/src/archive/archive_manager.h @@ -40,7 +40,7 @@ public: void eraseElementFromArchiveFileMap(long operation_id); void erasePrivData(long handle); long addPrivData(ArchiveFilePtr archive_file_ptr); - ArchiveFilePtr getPrivData(long handle); + common::PlatformResult getPrivData(long handle, ArchiveFilePtr* archive_file); long open(OpenCallbackData* callback); private: diff --git a/src/archive/archive_utils.cc b/src/archive/archive_utils.cc index 0b773d6c..09ed34d3 100644 --- a/src/archive/archive_utils.cc +++ b/src/archive/archive_utils.cc @@ -16,10 +16,8 @@ // #include "archive_utils.h" - #include #include - #include "common/logger.h" //TODO: @@ -50,39 +48,48 @@ std::string bytesToReadableString(const size_t num_bytes) return ss.str(); } -std::string fileModeToString(FileMode fm) +PlatformResult fileModeToString(FileMode fm, std::string* fm_str) { switch(fm) { case FileMode::READ: - return "r"; + *fm_str = "r"; + break; case FileMode::WRITE: - return "w"; + *fm_str = "w"; + break; case FileMode::READ_WRITE: - return "rw"; + *fm_str = "rw"; + break; case FileMode::ADD: - return "a"; + *fm_str = "a"; + break; default: - throw UnknownException("Unknown file mode"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Unknown file mode"); } + return PlatformResult(ErrorCode::NO_ERROR); } -FileMode stringToFileMode(std::string fmString) +PlatformResult stringToFileMode(std::string fmString, FileMode* fm) { if (!fmString.compare("r")) { - return FileMode::READ; + *fm = FileMode::READ; + return PlatformResult(ErrorCode::NO_ERROR); } else if (!fmString.compare("w")) { - return FileMode::WRITE; + *fm = FileMode::WRITE; + return PlatformResult(ErrorCode::NO_ERROR); } else if(!fmString.compare("rw")) { - return FileMode::READ_WRITE; + *fm = FileMode::READ_WRITE; + return PlatformResult(ErrorCode::NO_ERROR); } else if(!fmString.compare("a")) { - return FileMode::ADD; + *fm = FileMode::ADD; + return PlatformResult(ErrorCode::NO_ERROR); } // In widl it's "TypeMismatchError" so this exception used // instead of InvalidValues - throw TypeMismatchException("Invalid FileMode"); + return PlatformResult(ErrorCode::TYPE_MISMATCH_ERR, "Invalid FileMode"); } // FilePtr fileReferenceToFile(JSContextRef context, JSValueRef fileReference) diff --git a/src/archive/archive_utils.h b/src/archive/archive_utils.h index 1f618646..2bd090b4 100644 --- a/src/archive/archive_utils.h +++ b/src/archive/archive_utils.h @@ -20,8 +20,7 @@ #include -#include "common/platform_exception.h" - +#include "common/platform_result.h" #include "filesystem_file.h" #include "archive_file.h" @@ -29,8 +28,8 @@ namespace extension { namespace archive { std::string bytesToReadableString(const size_t num_bytes); -std::string fileModeToString(FileMode fm); -FileMode stringToFileMode(std::string fmString); +common::PlatformResult fileModeToString(FileMode fm, std::string* fm_str); +common::PlatformResult stringToFileMode(std::string fmString, FileMode* fm); //extern Filesystem::FilePtr fileReferenceToFile( // JSContextRef context, JSValueRef fileReference); @@ -111,14 +110,6 @@ std::string getBasePathFromPath(const std::string& fullpath); std::string getArchiveLogMessage(const int errorCode, const std::string &hint); -template -void throwArchiveException(const int errorCode, const std::string &hint) -{ - std::string log = getArchiveLogMessage(errorCode, hint); - LOGE("%s", log.c_str()); - throw T(log.c_str()); -} - } //namespace archive } //namespace extension diff --git a/src/archive/defs.h b/src/archive/defs.h index fa0aae89..2c127ca1 100755 --- a/src/archive/defs.h +++ b/src/archive/defs.h @@ -61,7 +61,7 @@ #define ARCHIVE_FILE_ENTRY_ATTR_COMPRESSED_SIZE "compressedSize" #define ARCHIVE_FILE_ENTRY_ATTR_MODIFIED "modified" -#define ERROR_CALLBACK_NAME "name" +#define ERROR_CALLBACK_CODE "code" #define ERROR_CALLBACK_MESSAGE "message" #endif // _ARCHIVE_PLUGIN_DEFS_H_ diff --git a/src/archive/filesystem_file.cc b/src/archive/filesystem_file.cc index 15eea840..b7140870 100644 --- a/src/archive/filesystem_file.cc +++ b/src/archive/filesystem_file.cc @@ -15,9 +15,7 @@ // limitations under the License. // #include "filesystem_file.h" - #include "common/logger.h" -#include "common/platform_exception.h" using namespace common; diff --git a/src/archive/filesystem_node.cc b/src/archive/filesystem_node.cc index 1784d7ca..ed9f6538 100755 --- a/src/archive/filesystem_node.cc +++ b/src/archive/filesystem_node.cc @@ -20,7 +20,6 @@ */ #include "filesystem_node.h" - #include #include #include @@ -34,8 +33,8 @@ #include #include "filesystem_path.h" +#include "filesystem_node.h" #include "common/logger.h" -#include "common/platform_exception.h" namespace extension { namespace filesystem { @@ -43,8 +42,10 @@ namespace filesystem { using namespace common; #define MAX_NODE_LENGTH 256 -bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeType type) +PlatformResult Node::checkPermission(const PathPtr &path, const std::string &mode, NodeType type, bool* granted) { + *granted = false; + switch (type) { case NT_DIRECTORY: @@ -53,16 +54,18 @@ bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeTyp if (!dir) { LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("Node has been deleted from platform."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Node has been deleted from platform."); } if (closedir(dir) != 0) { LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("Could not close platform node."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Could not close platform node."); } - if (mode == "r") - return true; + if (mode == "r") { + *granted = true; + return PlatformResult(ErrorCode::NO_ERROR); + } std::stringstream ss; time_t now; @@ -70,22 +73,23 @@ bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeTyp ss << now; PathPtr tempFilePath = Path::create(path->getFullPath()); tempFilePath->append(ss.str()); - try - { - createAsFileInternal(tempFilePath); - removeAsFile(tempFilePath); + + PlatformResult result = createAsFileInternal(tempFilePath); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - catch (const PlatformException& ex) - { - LoggerW("Exception: %s", ex.message().c_str()); - return false; + + result = removeAsFile(tempFilePath); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } if (mode == "rw" || mode == "w" || mode == "a") { - return true; + *granted = true; + return PlatformResult(ErrorCode::NO_ERROR); } LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("invalid mode"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); } break; case NT_FILE: @@ -104,7 +108,7 @@ bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeTyp else { LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("invalid mode"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "invalid mode"); } stream.open(path->getFullPath().c_str(), modeBit); @@ -112,16 +116,16 @@ bool Node::checkPermission(const PathPtr &path, const std::string &mode, NodeTyp if (stream.is_open()) { stream.close(); - return true; + *granted = true; } - return false; + return PlatformResult(ErrorCode::NO_ERROR); } break; } - return false; + return PlatformResult(ErrorCode::NO_ERROR); } -NodePtr Node::resolve(const PathPtr& path) +PlatformResult Node::resolve(const PathPtr& path, NodePtr* node) { LoggerD("Entered path:[%s]", path->getFullPath().c_str()); @@ -135,37 +139,41 @@ NodePtr Node::resolve(const PathPtr& path) { case EACCES: LoggerW("throw InvalidValuesException for file:[%s]", path->getFullPath().c_str()); - throw InvalidValuesException("Node access denied"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Node access denied"); break; case ENOENT: LoggerW("throw NotFoundException for file:[%s]", path->getFullPath().c_str()); - throw NotFoundException("NotFoundError"); + return PlatformResult(ErrorCode::NOT_FOUND_ERR, "NotFoundError"); break; default: LoggerW("throw IOException for file:[%s]", path->getFullPath().c_str()); - throw IOException("Platform exception fail"); + return PlatformResult(ErrorCode::IO_ERR, "Platform exception fail"); } } if (!S_ISDIR(info.st_mode) & !S_ISREG(info.st_mode) && !S_ISLNK(info.st_mode)) { LoggerW("throw IOException for file:[%s]", path->getFullPath().c_str()); - throw IOException("Platform node is of unsupported type."); + return PlatformResult(ErrorCode::IO_ERR, "Platform node is of unsupported type."); } NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; if (S_ISLNK(info.st_mode)) { - syminfo = stat(path); + PlatformResult result = stat(path, &syminfo); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } type = S_ISDIR(syminfo.st_mode) ? NT_DIRECTORY : NT_FILE; LoggerD("%x", type); } - auto result = std::shared_ptr(new Node(path, type)); + *node = std::shared_ptr(new Node(path, type)); LoggerD("Finished execution for file:[%s] type:%s", path->getFullPath().c_str(), type == NT_DIRECTORY ? "directory" : "file"); - return result; + + return PlatformResult(ErrorCode::NO_ERROR); } PathPtr Node::getPath() const @@ -173,13 +181,13 @@ PathPtr Node::getPath() const return Path::create(m_path->getFullPath()); } -NodePtr Node::getChild(const PathPtr& path) +PlatformResult Node::getChild(const PathPtr& path, NodePtr* node) { if (m_type != NT_DIRECTORY) { LoggerW("throw IOException"); - throw IOException("Not a directory."); + return PlatformResult(ErrorCode::IO_ERR, "Not a directory."); } - return Node::resolve(*m_path + *path); + return Node::resolve(*m_path + *path, node); } NodeType Node::getType() const @@ -197,187 +205,218 @@ void Node::setPermissions(int perms) m_perms = perms; } -Node::NameList Node::getChildNames() const +PlatformResult Node::getChildNames(Node::NameList* out_name_list) const { if (m_type != NT_DIRECTORY) { LoggerW("throw IOException"); - throw IOException("Node is not directory."); + return PlatformResult(ErrorCode::IO_ERR, "Node is not directory."); } if ((m_perms & PERM_READ) == 0) { LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("No permission."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); } DIR* dir = opendir(m_path->getFullPath().c_str()); if (!dir) { LoggerW("throw IOException"); - throw IOException("Node has been deleted from platform."); + return PlatformResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); } - NameList result; errno = 0; struct dirent *entry = NULL; + NameList name_list; while ((entry = readdir(dir))) { if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { continue; } - result.push_back(entry->d_name); + name_list.push_back(entry->d_name); } if (errno != 0) { LoggerW("throw IOException"); - throw IOException("Error while reading directory."); + return PlatformResult(ErrorCode::IO_ERR, "Error while reading directory."); } if (closedir(dir) != 0) { LoggerW("throw IOException"); - throw IOException("Could not close platform node."); + return PlatformResult(ErrorCode::IO_ERR, "Could not close platform node."); } - return result; + *out_name_list = name_list; + return PlatformResult(ErrorCode::NO_ERROR); } -NodeList Node::getChildNodes() const +PlatformResult Node::getChildNodes(NodeList* out_node_list) const { if (m_type != NT_DIRECTORY) { LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); LoggerW("throw IOException"); - throw IOException("Node is not directory."); LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); + return PlatformResult(ErrorCode::IO_ERR, "Node is not directory."); } if ((m_perms & PERM_READ) == 0) { LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("No permission."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "No permission."); } DIR* dir = opendir(m_path->getFullPath().c_str()); if (!dir) { LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); LoggerW("throw IOException"); - throw IOException("Node has been deleted from platform."); + return PlatformResult(ErrorCode::IO_ERR, "Node has been deleted from platform."); } errno = 0; - NodeList result; struct dirent *entry = NULL; + NodeList node_list; while ((entry = readdir(dir))) { if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { continue; } - try { - NodePtr node = Node::resolve(*m_path + entry->d_name); - node->setPermissions(getPermissions()); // inherit access rights - result.push_back(node); - } - catch (const PlatformException& ex) - { - LoggerW("caught BasePlatformException ignored"); - } + + NodePtr node; + Node::resolve(*m_path + entry->d_name, &node); + node->setPermissions(getPermissions()); // inherit access rights + node_list.push_back(node); } if (errno != 0) { LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); LoggerW("throw IOException"); - throw IOException("Error while reading directory."); + return PlatformResult(ErrorCode::IO_ERR, "Error while reading directory."); } if (closedir(dir) != 0) { LoggerW("Path %s Perm %d", m_path->getFullPath().c_str(), m_perms); LoggerW("throw IOException"); - throw IOException("Could not close platform node."); + return PlatformResult(ErrorCode::IO_ERR, "Could not close platform node."); } - return result; + *out_node_list = node_list; + + return PlatformResult(ErrorCode::NO_ERROR); } -NodePtr Node::createChild( +PlatformResult Node::createChild( const PathPtr& path, NodeType type, + NodePtr* node, int options) { if (m_type != NT_DIRECTORY) { LoggerW("throw IOException"); - throw IOException("Parent node is not a directory."); + return PlatformResult(ErrorCode::IO_ERR, "Parent node is not a directory."); } if ((m_perms & PERM_WRITE) == 0) { LoggerW("throw InvalidValuesException"); - throw InvalidValuesException("Not enough permissions."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Not enough permissions."); } PathPtr childPath = *m_path + *path; - if (exists(childPath)) { + bool existed; + PlatformResult result = exists(childPath, &existed); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + if (existed) { LoggerW("throw IOException"); - throw IOException("Node already exists."); + return PlatformResult(ErrorCode::IO_ERR, "Node already exists."); } - NodePtr result; switch (type) { case NT_FILE: - result = createAsFile(childPath, options); + result = createAsFile(childPath, node, options); break; case NT_DIRECTORY: - result = createAsDirectory(childPath, options); + result = createAsDirectory(childPath, node, options); break; default: LoggerW("throw IOException"); - throw IOException("Unsupported node type."); + return PlatformResult(ErrorCode::IO_ERR, "Unsupported node type."); + } + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - if (!!result) { - result->m_perms = m_perms; + + if (!!(*node)) { + (*node)->m_perms = m_perms; } else { LoggerW("throw IOException"); - throw IOException("Node creation error"); + return PlatformResult(ErrorCode::IO_ERR, "Node creation error"); } - return result; + return PlatformResult(ErrorCode::NO_ERROR); } -void Node::remove(int options) +PlatformResult Node::remove(int options) { + PlatformResult result(ErrorCode::NO_ERROR); switch (m_type) { case NT_FILE: - removeAsFile(m_path); + result = removeAsFile(m_path); break; case NT_DIRECTORY: - removeAsDirectory(m_path, (options & OPT_RECURSIVE)); + result = removeAsDirectory(m_path, (options & OPT_RECURSIVE)); break; default: LoggerE("throw UnknownError"); - throw UnknownException("Not supported value of m_type"); + result = PlatformResult(ErrorCode::UNKNOWN_ERR, "Not supported value of m_type"); } + return result; } -unsigned long long Node::getSize() const +PlatformResult Node::getSize(unsigned long long* size) const { if (m_type == NT_DIRECTORY) { + LoggerW("Getting size for directories is not supported."); LoggerW("throw IOException"); - throw IOException("Getting size for directories is not supported."); + return PlatformResult(ErrorCode::IO_ERR, "Getting size for directories is not supported."); + } + + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - struct stat info = stat(m_path); if (!S_ISREG(info.st_mode)) { + LoggerW("Specified node is not a regular file."); LoggerW("throw IOException"); - throw IOException("Specified node is not a regular file."); + return PlatformResult(ErrorCode::IO_ERR, "Specified node is not a regular file."); } - return info.st_size; + *size = info.st_size; + + return PlatformResult(ErrorCode::NO_ERROR); } -std::time_t Node::getCreated() const +PlatformResult Node::getCreated(std::time_t* time) const { - return stat(m_path).st_ctime; + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + *time = info.st_ctime; + return PlatformResult(ErrorCode::NO_ERROR); } -std::time_t Node::getModified() const +PlatformResult Node::getModified(std::time_t* time) const { - return stat(m_path).st_mtime; + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + *time = info.st_mtime; + return PlatformResult(ErrorCode::NO_ERROR); } // TODO Optimize it, maybe store a flag indicating that node is a root. -NodePtr Node::getParent() const +PlatformResult Node::getParent(NodePtr* node) const { // LocationPaths roots = Manager::getInstance().getLocationPaths(); // for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { @@ -385,61 +424,72 @@ NodePtr Node::getParent() const // return NodePtr(); // } // } - NodePtr parent = Node::resolve(Path::create(m_path->getPath())); - parent->setPermissions(getPermissions()); - return parent; + PlatformResult result = Node::resolve(Path::create(m_path->getPath()), node); + if (result.error_code() == ErrorCode::NO_ERROR) { + (*node)->setPermissions(getPermissions()); + } + + return result; } -int Node::getMode() const +PlatformResult Node::getMode(int* mode) const { - int result = 0; - struct stat info = stat(m_path); - if (info.st_mode & S_IRUSR) { result |= PM_USER_READ; } - if (info.st_mode & S_IWUSR) { result |= PM_USER_WRITE; } - if (info.st_mode & S_IXUSR) { result |= PM_USER_EXEC; } - if (info.st_mode & S_IRGRP) { result |= PM_GROUP_READ; } - if (info.st_mode & S_IWGRP) { result |= PM_GROUP_WRITE; } - if (info.st_mode & S_IXGRP) { result |= PM_GROUP_EXEC; } - if (info.st_mode & S_IROTH) { result |= PM_OTHER_READ; } - if (info.st_mode & S_IWOTH) { result |= PM_OTHER_WRITE; } - if (info.st_mode & S_IXOTH) { result |= PM_OTHER_EXEC; } + struct stat info; + PlatformResult result = stat(m_path, &info); + if (result.error_code() == ErrorCode::NO_ERROR) { + *mode = 0; + if (info.st_mode & S_IRUSR) { *mode |= PM_USER_READ; } + if (info.st_mode & S_IWUSR) { *mode |= PM_USER_WRITE; } + if (info.st_mode & S_IXUSR) { *mode |= PM_USER_EXEC; } + if (info.st_mode & S_IRGRP) { *mode |= PM_GROUP_READ; } + if (info.st_mode & S_IWGRP) { *mode |= PM_GROUP_WRITE; } + if (info.st_mode & S_IXGRP) { *mode |= PM_GROUP_EXEC; } + if (info.st_mode & S_IROTH) { *mode |= PM_OTHER_READ; } + if (info.st_mode & S_IWOTH) { *mode |= PM_OTHER_WRITE; } + if (info.st_mode & S_IXOTH) { *mode |= PM_OTHER_EXEC; } + } return result; } -bool Node::exists(const PathPtr& path) +PlatformResult Node::exists(const PathPtr& path, bool* existed) { struct stat info; memset(&info, 0, sizeof(struct stat)); int status = lstat(path->getFullPath().c_str(), &info); + *existed = false; + if (0 == status) { - return true; + *existed = true; + return PlatformResult(ErrorCode::NO_ERROR); } else if (ENAMETOOLONG == errno) { LoggerW("throw IOException"); - throw IOException("file name is too long"); + return PlatformResult(ErrorCode::IO_ERR, "file name is too long"); } else if (errno != ENOENT) { - return true; + *existed = true; + return PlatformResult(ErrorCode::NO_ERROR); } - return false; + return PlatformResult(ErrorCode::NO_ERROR); } -struct stat Node::stat(const PathPtr& path) +PlatformResult Node::stat(const PathPtr& path, struct stat* out_info) { - struct stat result; - memset(&result, 0, sizeof(struct stat)); - if (::stat(path->getFullPath().c_str(), - &result) != 0) + struct stat info; + memset(&info, 0, sizeof(struct stat)); + + if (::stat(path->getFullPath().c_str(), &info) != 0) { LoggerE("File: %s", path->getFullPath().c_str()); LoggerW("throw IOException"); - throw IOException("Node does not exist or no access"); + return PlatformResult(ErrorCode::IO_ERR, "Node does not exist or no access"); } - return result; + *out_info = info; + return PlatformResult(ErrorCode::NO_ERROR); } Node::Node(const PathPtr& path, NodeType type): @@ -449,26 +499,28 @@ Node::Node(const PathPtr& path, NodeType type): { } -NodePtr Node::createAsFile(const PathPtr& path, - int /* options */) +PlatformResult Node::createAsFile(const PathPtr& path, NodePtr* node, int /* options */) { - createAsFileInternal(path); - return std::shared_ptr(new Node(path, NT_FILE)); + PlatformResult result = createAsFileInternal(path); + if (result.error_code() == ErrorCode::NO_ERROR) { + node->reset(new Node(path, NT_FILE)); + } + return result; } -void Node::createAsFileInternal(const PathPtr& path) +PlatformResult Node::createAsFileInternal(const PathPtr& path) { FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); if (!file) { LoggerW("fopen fails IOException throw for path [%s]", path->getFullPath().c_str()); - throw IOException("Platform node could not be created."); + return PlatformResult(ErrorCode::IO_ERR, "Platform node could not be created."); } std::fclose(file); + return PlatformResult(ErrorCode::NO_ERROR); } -NodePtr Node::createAsDirectory(const PathPtr& path, - int options) +PlatformResult Node::createAsDirectory(const PathPtr& path, NodePtr* node, int options) { // if (options & OPT_RECURSIVE) { // auto parts = Utils::getParts(path); @@ -476,41 +528,46 @@ NodePtr Node::createAsDirectory(const PathPtr& path, // if (!exists(*it)) { createAsDirectoryInternal(*it); } // } // } - createAsDirectoryInternal(path); - return std::shared_ptr(new Node(path, NT_DIRECTORY)); + PlatformResult result = createAsDirectoryInternal(path); + if (result.error_code() == ErrorCode::NO_ERROR) { + node->reset(new Node(path, NT_DIRECTORY)); + } + return result; } -void Node::createAsDirectoryInternal(const PathPtr& path) +PlatformResult Node::createAsDirectoryInternal(const PathPtr& path) { if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) { LoggerW("throw IOException"); - throw IOException("Platform node could not be created."); + return PlatformResult(ErrorCode::IO_ERR, "Platform node could not be created."); } + return PlatformResult(ErrorCode::NO_ERROR); } -void Node::removeAsFile(const PathPtr& path) +PlatformResult Node::removeAsFile(const PathPtr& path) { auto fullPath = path->getFullPath(); if (unlink(fullPath.c_str()) != 0) { LoggerW("remove [%s]", fullPath.c_str()); LoggerW("throw IOException"); - throw IOException("Error while removing platform node."); + return PlatformResult(ErrorCode::IO_ERR, "Error while removing platform node."); } + return PlatformResult(ErrorCode::NO_ERROR); } -void Node::removeAsDirectory(const PathPtr& path, - bool recursive) +PlatformResult Node::removeAsDirectory(const PathPtr& path, bool recursive) { if (recursive) { DIR* dir = opendir(path->getFullPath().c_str()); if (!dir) { LoggerW("File %s", path->getFullPath().c_str()); LoggerW("throw IOException"); - throw IOException("Node does not exist or access denied."); + return PlatformResult(ErrorCode::IO_ERR, "Node does not exist or access denied."); } errno = 0; struct dirent *entry = NULL; + PlatformResult result(ErrorCode::NO_ERROR); while ((entry = readdir(dir))) { if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { continue; @@ -519,17 +576,14 @@ void Node::removeAsDirectory(const PathPtr& path, struct stat info; memset(&info, 0, sizeof(struct stat)); if (lstat(subPath->getFullPath().c_str(), &info) == 0) { - try { - if (S_ISDIR(info.st_mode)) { - removeAsDirectory(subPath, true); - } else if (S_ISREG(info.st_mode)) { - removeAsFile(subPath); - } + if (S_ISDIR(info.st_mode)) { + result = removeAsDirectory(subPath, true); + } else if (S_ISREG(info.st_mode)) { + result = removeAsFile(subPath); } - catch (const PlatformException& ex) - { + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - // TODO: Not sure if above exception should be swallowed. } } closedir(dir); @@ -539,11 +593,13 @@ void Node::removeAsDirectory(const PathPtr& path, if (rmdir(path->getFullPath().c_str()) != 0) { if (errno == EEXIST) { LoggerW("throw IOException"); - throw IOException("Node has child nodes."); + return PlatformResult(ErrorCode::IO_ERR, "Node has child nodes."); } LoggerW("throw IOException"); - throw IOException("Error while removing platform node."); + return PlatformResult(ErrorCode::IO_ERR, "Error while removing platform node."); } + + return PlatformResult(ErrorCode::NO_ERROR); } std::string Node::toUri(int /*widgetId*/) const @@ -572,21 +628,5 @@ bool Node::isSubPath(std::string aDirPath, PathPtr aFilePath) return isSubP; } -bool Node::isSubPath(PathPtr aPath) const -{ - LoggerD("Entered thisPath:%s aPath: %s", - this->getPath()->getFullPath().c_str(), - aPath->getFullPath().c_str()); - - resolve(aPath); - - bool isSubP = isSubPath(m_path->getFullPath(), aPath); - LoggerD("thisPath:%s aPath: %s isSubP:%d", - this->getPath()->getFullPath().c_str(), - aPath->getFullPath().c_str(), - isSubP); - return isSubP; -} - -} -} +} // filesystem +} // extension diff --git a/src/archive/filesystem_node.h b/src/archive/filesystem_node.h index 04109a7a..6767733e 100644 --- a/src/archive/filesystem_node.h +++ b/src/archive/filesystem_node.h @@ -33,6 +33,8 @@ #include #include +#include "common/platform_result.h" + namespace extension { namespace filesystem { @@ -137,8 +139,10 @@ public: //! //! This function creates Node wich represent folder or file //! in file system. - //! @return Node smart pointer - static NodePtr resolve(const PathPtr& path); + //! @param path virtual path in filesystem + //! @param node output pointer + //! @return a platform result + static common::PlatformResult resolve(const PathPtr& path, NodePtr* node); //! \brief Checks if path can be accessed //! //! Function opens path and base at reqested mode and type verifies access @@ -151,10 +155,12 @@ public: //! @param path virtual path in filesystem //! @param mode access mode: "r", "rw" //! @param type folder or file - //! @return true if access is granted, false if not - bool checkPermission(const PathPtr& path, - const std::string& mode, - NodeType type); + //! @param granted true if access is granted, false if not + //! @return a platform result + common::PlatformResult checkPermission(const PathPtr& path, + const std::string& mode, + NodeType type, + bool* granted); //! \brief Gets path of current node. //! @return Node's path. PathPtr getPath() const; @@ -168,75 +174,81 @@ public: //! @param perms Node's permissions @see Api::Filesystem::Permissions. void setPermissions(int perms); //! \brief Gets size of this node. - //! @return Size. - unsigned long long getSize() const; + //! @param size output size of a file. + //! @return a platform result. + common::PlatformResult getSize(unsigned long long* size) const; //! \brief Gets creation date of this node. - //! @return Date. - std::time_t getCreated() const; + //! @param time output date. + //! @return a platform result. + common::PlatformResult getCreated(std::time_t* time) const; //! \brief Gets last modification date of this node. - //! @return Date. - std::time_t getModified() const; + //! @param time output date. + //! @return a platform result. + common::PlatformResult getModified(std::time_t* time) const; //! \brief Gets parent of this node. - //! @return Parent node or NULL if no parent (e.g. in case of a root node). - NodePtr getParent() const; + //! @param node the output node pointer or NULL if no parent (e.g. in case of a root node). + //! @return a platform result + common::PlatformResult getParent(NodePtr* node) const; //! \brief Gets platform permissions. - //! @return Platform permissions (set of flags from @see Permissions enum). - int getMode() const; + //! @param mode output Platform permissions (set of flags from @see Permissions enum). + //! @return a platform result + common::PlatformResult getMode(int* mode) const; //! \brief Gets direct child of this node. //! @param path Path to the child node. - //! @return Ptr to the child node. + //! @param output Ptr to the child node. + //! @return a platform result //! @remarks Ownership passed to the caller. - NodePtr getChild(const PathPtr& path); + common::PlatformResult getChild(const PathPtr& path, NodePtr* node); //! \brief Gets list of names of direct child nodes. - //! @return Names of child nodes. - NameList getChildNames() const; + //! @param out_name_list the pointer to the list of nodes + //! @return a platform result + common::PlatformResult getChildNames(NameList* out_name_list) const; //! \brief Gets list of direct child nodes. - //! @return Child nodes. + //! @param out_node_list the pointer to the list of nodes + //! @return a platform result //! @remarks Ownership passed to the caller. //! @deprecated - NodeList getChildNodes() const; + common::PlatformResult getChildNodes(NodeList* out_node_list) const; //! \brief Creates child of current node. //! @param path Path to the node to create. //! @param type Type of the node @see Api::Filesystem::NodeType. + //! @param node of the created file or directory //! @param options Additional options see remarks (no options by default). //! @return Ptr to newly created node. //! @remarks //! Valid options: //! - OPT_RECURSIVE - attempt to create all necessary sub-directories - NodePtr createChild( + common::PlatformResult createChild( const PathPtr& path, NodeType, + NodePtr* node, int options = OPT_NONE); //! \brief Removes underlying filesystem node. //! @param options Removal options (by default removal is recursive). + //! @return a platform result //! @remarks Synchronous. //! Valid options: //! - OPT_RECURSIVE - remove node recursively. - void remove(int options); + common::PlatformResult remove(int options); std::string toUri(int widgetId) const; - bool isSubPath(PathPtr aPath) const; static bool isSubPath(std::string aDirPath, PathPtr aFilePath); private: - static bool exists(const PathPtr& path); - static struct stat stat(const PathPtr& path); + static common::PlatformResult exists(const PathPtr& path, bool* existed); + static common::PlatformResult stat(const PathPtr& path, struct stat* out_info); - Node(const PathPtr& path, - NodeType type); + Node(const PathPtr& path, NodeType type); - NodePtr createAsFile(const PathPtr& path, - int options); - void createAsFileInternal(const PathPtr& path); + common::PlatformResult createAsFile(const PathPtr& path, NodePtr* node, int options); + common::PlatformResult createAsFileInternal(const PathPtr& path); - NodePtr createAsDirectory(const PathPtr& path, - int options); - void createAsDirectoryInternal(const PathPtr& path); + common::PlatformResult createAsDirectory(const PathPtr& path, NodePtr* node, int options); + common::PlatformResult createAsDirectoryInternal(const PathPtr& path); - void removeAsFile(const PathPtr& path); - void removeAsDirectory(const PathPtr& path, - bool recursive); + common::PlatformResult removeAsFile(const PathPtr& path); + common::PlatformResult removeAsDirectory(const PathPtr& path, bool recursive); PathPtr m_path; NodeType m_type; diff --git a/src/archive/filesystem_path.cc b/src/archive/filesystem_path.cc index c234b781..0e39694a 100755 --- a/src/archive/filesystem_path.cc +++ b/src/archive/filesystem_path.cc @@ -26,15 +26,11 @@ #include #include "filesystem_path.h" - -#include "common/platform_exception.h" #include "common/logger.h" namespace extension { namespace filesystem { -using namespace common; - const Path::SeparatorType Path::m_pathSeparator = '/'; PathPtr Path::create(const std::string& path) @@ -100,7 +96,10 @@ void Path::reset(const std::string& str) if (!isValid(str)) { LoggerD("Invalid string %s", str.c_str()); LoggerW("throw NotFoundException"); - throw NotFoundException("Invalid path"); + // The only way to remove throw statement from here is to just return, because + // this function is used in the operator functions and they're not able + // to handle a PlatformResult value; + return; } // std::string tmp = Commons::String::unique(/*Commons::String::trim*/( // str), m_pathSeparator); diff --git a/src/archive/old/ArchiveCallbackData.cpp b/src/archive/old/ArchiveCallbackData.cpp deleted file mode 100755 index ee962262..00000000 --- a/src/archive/old/ArchiveCallbackData.cpp +++ /dev/null @@ -1,804 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** - * @file ArchiveCallbackData.cpp - */ - -#include -#include "ArchiveCallbackData.h" -#include -#include -#include -#include -#include "ArchiveFile.h" -#include "JSArchiveFileEntry.h" -#include "ArchiveUtils.h" -#include "JSArchiveFileEntry.h" -#include "UnZip.h" -#include "Zip.h" -#include "Path.h" - -namespace DeviceAPI { -namespace Archive { - -using namespace DeviceAPI::Common; - -namespace { -const char* CALLBACK_SUCCESS = "success"; -const char* CALLBACK_ERROR = "error"; -const char* CALLBACK_PROGRESS = "progress"; -} //anonymous namespace - -//---------------------------------------------------------------------------------------- -//OperationCallbackData -//---------------------------------------------------------------------------------------- - -OperationCallbackData::OperationCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type) : - MultiCallbackUserData(globalCtx), - m_callback_type(callback_type), - m_op_id(0), - m_is_error(false), - m_is_canceled(false) -{ - LOGD("Entered"); -} - -OperationCallbackData::~OperationCallbackData() -{ - LOGD("Entered"); - if(m_op_id > 0){ - ArchiveManager::getInstance().eraseElementFromArchiveFileMap(m_op_id); - } -} - -void OperationCallbackData::setError(const std::string &err_name, - const std::string &err_message) -{ - LOGD("Entered"); - //store only first error - if (!m_is_error) { - m_err_name = err_name; - m_err_message = err_message; - m_is_error = true; - } -} - -bool OperationCallbackData::isError() const -{ - LOGD("Entered"); - return m_is_error; -} - -bool OperationCallbackData::isCanceled() const -{ - return m_is_canceled; -} - -void OperationCallbackData::setOperationId(long op_id) -{ - LOGD("Entered"); - m_op_id = op_id; -} - -long OperationCallbackData::getOperationId() const -{ - LOGD("Entered"); - return m_op_id; -} - -void OperationCallbackData::setIsCanceled(bool canceled) -{ - m_is_canceled = canceled; -} - -const std::string& OperationCallbackData::getErrorName() const -{ - LOGD("Entered"); - return m_err_name; -} - -const std::string& OperationCallbackData::getErrorMessage() const -{ - LOGD("Entered"); - return m_err_message; -} - -ArchiveCallbackType OperationCallbackData::getCallbackType() const -{ - LOGD("Entered"); - return m_callback_type; -} - -ArchiveFilePtr OperationCallbackData::getArchiveFile() const -{ - return m_caller_instance; -} - -void OperationCallbackData::setArchiveFile(ArchiveFilePtr caller) -{ - m_caller_instance = caller; -} - -void OperationCallbackData::setSuccessCallback(JSValueRef on_success) -{ - LOGD("Entered"); - auto ctx = getContext(); - if(on_success && JSValueIsObject(ctx, on_success)) { - JSObjectRef success = JSValueToObject(ctx, on_success, NULL); - this->setCallback(CALLBACK_SUCCESS, success); - } -} - -void OperationCallbackData::setErrorCallback(JSValueRef on_error) -{ - LOGD("Entered"); - auto ctx = getContext(); - if(on_error && JSValueIsObject(ctx, on_error)) { - JSObjectRef error = JSValueToObject(ctx, on_error, NULL); - this->setCallback(CALLBACK_ERROR, error); - } -} - -void OperationCallbackData::callSuccessCallback() -{ - LOGD("Entered"); - this->invokeCallback(CALLBACK_SUCCESS, 0, NULL); -} - -void OperationCallbackData::callSuccessCallback(JSValueRef success) -{ - LOGD("Entered"); - this->invokeCallback(CALLBACK_SUCCESS, success); -} - -void OperationCallbackData::callErrorCallback(JSValueRef err) -{ - LOGD("Entered"); - this->invokeCallback(CALLBACK_ERROR, err); -} - -//---------------------------------------------------------------------------------------- -//OpenCallbackData -//---------------------------------------------------------------------------------------- - -OpenCallbackData::OpenCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - OperationCallbackData(globalCtx, callback_type) -{ - LOGD("Entered"); -} - -OpenCallbackData::~OpenCallbackData() -{ - LOGD("Entered"); -} - -void OpenCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGE("Entered"); - - Filesystem::FilePtr file = archive_file_ptr->getFile(); - if (!file) { - LOGE("File is null"); - throw UnknownException("File is null"); - } - Filesystem::NodePtr node = file->getNode(); - if(!node) { - LOGE("Node is null"); - throw UnknownException("Node is null"); - } - const FileMode fm = archive_file_ptr->m_file_mode; - if (0 == node->getSize()) { - if(FileMode::READ_WRITE == fm || - FileMode::WRITE == fm || - FileMode::ADD == fm) { - LOGD("Empty file obtained for writing/appending"); - - // Do not create empty archive with minizip library - it will not be loaded - // by unzip. - // - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - archive_file_ptr->setCreatedAsNewEmptyArchive(true); - archive_file_ptr->setEntryMap(ArchiveFileEntryPtrMapPtr( - new ArchiveFileEntryPtrMap())); - archive_file_ptr->setIsOpen(true); - } - else { - LOGE("The file is empty throwing: InvalidValuesException - Invalid ZIP archive"); - throw InvalidValuesException("Invalid ZIP archive"); - } - } - else { - archive_file_ptr->setIsOpen(true); - archive_file_ptr->updateListOfEntries(); - } - - guint id = g_idle_add(ArchiveFile::openTaskCompleteCB, this); - if (!id) { - LOGE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); - } -} - -//---------------------------------------------------------------------------------------- -//GetEntriesCallbackData -//---------------------------------------------------------------------------------------- - -GetEntriesCallbackData::GetEntriesCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - OperationCallbackData(globalCtx, callback_type) -{ - LOGD("Entered"); -} -GetEntriesCallbackData::~GetEntriesCallbackData() -{ - LOGD("Entered"); -} - -ArchiveFileEntryPtrMapPtr GetEntriesCallbackData::getEntries() const -{ - return m_entries; -} - -void GetEntriesCallbackData::setEntries(ArchiveFileEntryPtrMapPtr entries) -{ - m_entries = entries; -} - -void GetEntriesCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - - setEntries(archive_file_ptr->getEntryMap()); - - guint id = g_idle_add(ArchiveFile::getEntriesTaskCompleteCB, this); - if (!id) { - LOGE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); - } -} - -//---------------------------------------------------------------------------------------- -//GetEntryByNameCallbackData -//---------------------------------------------------------------------------------------- - -GetEntryByNameCallbackData::GetEntryByNameCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - OperationCallbackData(globalCtx, callback_type) -{ - LOGD("Entered"); -} - -GetEntryByNameCallbackData::~GetEntryByNameCallbackData() -{ - LOGD("Entered"); -} - -const std::string& GetEntryByNameCallbackData::getName() const -{ - LOGD("Entered"); - return m_name; -} - -void GetEntryByNameCallbackData::setName(const std::string& name) -{ - LOGD("Entered"); - m_name = name; -} - -ArchiveFileEntryPtr GetEntryByNameCallbackData::getFileEntry() const -{ - return m_file_entry; -} - -void GetEntryByNameCallbackData::setFileEntry(ArchiveFileEntryPtr entry) -{ - m_file_entry = entry; -} - -void GetEntryByNameCallbackData::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - - ArchiveFileEntryPtrMapPtr entries = archive_file_ptr->getEntryMap(); - auto it = entries->find(getName()); - - //Not found but if our name does not contain '/' - //try looking for directory with such name - // - if (it == entries->end() && !isDirectoryPath(getName())) { - const std::string try_directory = getName() + "/"; - LOGD("GetEntryByName Trying directory: [%s]", try_directory.c_str()); - it = entries->find(try_directory); - } - - if (it == entries->end()) { - LOGE("GetEntryByName Entry with name: [%s] not found", getName().c_str()); - LOGE("Throwing NotFoundException - Entry not found"); - throw Common::NotFoundException("Entry not found"); - } - - setFileEntry(it->second); - - guint id = g_idle_add(ArchiveFile::getEntryByNameTaskCompleteCB, this); - if (!id) { - LOGE("g_idle_add fails"); - throw UnknownException("g_idle_add fails"); - } -} - -//---------------------------------------------------------------------------------------- -//BaseProgressCallback -//---------------------------------------------------------------------------------------- - -BaseProgressCallback::BaseProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - OperationCallbackData(globalCtx, callback_type), - m_overwrite(false) -{ - LOGD("Entered"); -} - -BaseProgressCallback::~BaseProgressCallback() -{ - LOGD("Entered"); -} - -bool BaseProgressCallback::getOverwrite() const -{ - LOGD("Entered"); - return m_overwrite; -} - -void BaseProgressCallback::setOverwrite(bool overwrite) -{ - LOGD("Entered"); - m_overwrite = overwrite; -} - -struct ProgressHolder -{ - ProgressHolder() : - callback(NULL) - { - }; - - double overall_progress; - ArchiveFileEntryPtr currently_processed_entry; - BaseProgressCallback* callback; -}; - -void BaseProgressCallback::callSuccessCallbackOnMainThread() -{ - guint id = g_idle_add(BaseProgressCallback::callSuccessCallbackCB, - static_cast(this)); - if (!id) { - LOGE("g_idle_add fails - success callback will not be called"); - } -} - -gboolean BaseProgressCallback::callSuccessCallbackCB(void* data) -{ - BaseProgressCallback* callback = static_cast(data); - if (!callback) { - LOGE("callback pointer is NULL"); - return false; - } - - std::unique_ptr cb_ptr(callback); - - JSContextRef context = callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context closed - unable to call success callback"); - return false; - } - - try { - callback->callSuccessCallback(); - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - callback->setArchiveFile(ArchiveFilePtr()); - ArchiveManager::getInstance().eraseElementFromArchiveFileMap(callback->m_op_id); - - return false; -} - -void BaseProgressCallback::setProgressCallback(JSValueRef on_progress) -{ - LOGD("Entered"); - auto ctx = getContext(); - if(on_progress && JSValueIsObject(ctx, on_progress)) { - JSObjectRef progress = JSValueToObject(ctx, on_progress, NULL); - this->setCallback(CALLBACK_PROGRESS, progress); - } -} - -void BaseProgressCallback::callProgressCallback(long operationId, - double value, - const std::string& filename) -{ - LOGD("Entered"); - auto ctx = getContext(); - const int SIZE = 3; - JSValueRef parameters[SIZE] = { - JSUtil::toJSValueRef(ctx, operationId), - JSUtil::toJSValueRef(ctx, value), - JSUtil::toJSValueRef(ctx, filename) - }; - - this->invokeCallback(CALLBACK_PROGRESS, SIZE, parameters); -} - -void BaseProgressCallback::callProgressCallbackOnMainThread(const double progress, - ArchiveFileEntryPtr current_entry) -{ - ProgressHolder* ph = new(std::nothrow) ProgressHolder(); - - if(ph) { - ph->overall_progress = progress; - ph->currently_processed_entry = current_entry; - ph->callback = this; - - guint id = g_idle_add(BaseProgressCallback::callProgressCallbackCB, - static_cast(ph)); - if (!id) { - LOGE("g_idle_add fails"); - delete ph; - ph = NULL; - } - } else { - LOGE("Couldn't allocate ProgressHolder"); - } -} - -gboolean BaseProgressCallback::callProgressCallbackCB(void* data) -{ - ProgressHolder* ph = static_cast(data); - if (!ph) { - LOGE("ph is null"); - return false; - } - - std::unique_ptr ph_ptr(ph); - if (!ph->callback) { - LOGE("ph->callback is null"); - return false; - } - - JSContextRef context = ph->callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context was closed"); - return false; - } - try { - //Error callback is being handled by ArchiveFile queue - see - //ArchiveFile::taskManagerThread function - // - ph->callback->callProgressCallback( - ph->callback->m_op_id, - ph->overall_progress, - ph->currently_processed_entry->getName()); - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - return false; -} - -//---------------------------------------------------------------------------------------- -//AddProgressCallback -//---------------------------------------------------------------------------------------- - -AddProgressCallback::AddProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - BaseProgressCallback(globalCtx, callback_type) -{ - LOGD("Entered"); -} - -AddProgressCallback::~AddProgressCallback() -{ - LOGD("Entered"); -} - -ArchiveFileEntryPtr AddProgressCallback::getFileEntry() const -{ - LOGD("Entered"); - return m_file_entry; -} - -void AddProgressCallback::setFileEntry(ArchiveFileEntryPtr file_entry) -{ - LOGD("Entered"); - m_file_entry = file_entry; -} - -void AddProgressCallback::setBasePath(const std::string& path) -{ - LOGD("Entered"); - m_base_path = path; - m_base_virt_path = Filesystem::External::toVirtualPath(m_base_path); - std::string::size_type pos = m_base_virt_path.find(DeviceAPI::Filesystem::Path::getSeparator()); - if (pos != std::string::npos) - { - m_base_virt_path = m_base_virt_path.substr(pos + 1); - } - else - { - m_base_virt_path = ""; - } -} - -const std::string& AddProgressCallback::getBasePath() -{ - LOGD("Entered"); - return m_base_path; -} - -const std::string& AddProgressCallback::getBaseVirtualPath() -{ - LOGD("Entered"); - return m_base_virt_path; -} - -void AddProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - - if(!m_file_entry) { - LOGE("ArchiveFileEntry is not set in callback"); - throw UnknownException("Could not add file to archive"); - } - - if(!archive_file_ptr) { - LOGE("archive_file_ptr is NULL"); - throw UnknownException("Could not extract archive file entry"); - } - - AddProgressCallback* callback = this; - - ZipPtr zip = archive_file_ptr->createZipObject(); - zip->addFile(callback); - // Zip is no more needed but it locks file opening while - // it is needed to read entries from file - zip->close(); - - //We have just finished adding file to archive so now - //this archive file should be valid .zip archive and - //we can remove CreatedAsNewEmptyArchive flag - archive_file_ptr->setCreatedAsNewEmptyArchive(false); - - LOGD("Update decompressed size and entry list"); - // update informations about decompressed size and entry list - // TODO FIXME need to resolve problem with access to file by - // more than one thread - try{ - archive_file_ptr->updateListOfEntries(); - } catch(...){ - LOGD("Unknown error during updating entries list inside archive"); - } -} - -//---------------------------------------------------------------------------------------- -//ExtractAllProgressCallback -//---------------------------------------------------------------------------------------- - -ExtractAllProgressCallback::ExtractAllProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type): - BaseProgressCallback(globalCtx, callback_type), - m_files_to_extract(0), - m_files_extracted(0), - m_current_file_size(0), - m_current_file_extracted_bytes(0), - m_progress_overall(0), - m_overall_decompressed(0) -{ - LOGD("Entered"); -} - -ExtractAllProgressCallback::~ExtractAllProgressCallback() -{ - LOGD("Entered"); -} - -Filesystem::FilePtr ExtractAllProgressCallback::getDirectory() const -{ - return m_directory; -} - -void ExtractAllProgressCallback::setDirectory(Filesystem::FilePtr directory) -{ - m_directory = directory; -} - -void ExtractAllProgressCallback::startedExtractingFile(unsigned long current_file_size) -{ - m_current_file_size = current_file_size; - m_current_file_extracted_bytes = 0; -} - -void ExtractAllProgressCallback::extractedPartOfFile(unsigned long bytes_decompressed) -{ - m_current_file_extracted_bytes += bytes_decompressed; - updateOverallProgress(bytes_decompressed); -} - -void ExtractAllProgressCallback::finishedExtractingFile() -{ - m_current_file_size = 0; - m_current_file_extracted_bytes = 0; - ++m_files_extracted; - updateOverallProgress(0); -} - -void ExtractAllProgressCallback::updateOverallProgress(unsigned long bytes_decompressed) -{ - m_overall_decompressed += bytes_decompressed; - m_progress_overall = - static_cast(m_overall_decompressed + m_files_extracted) / - static_cast(m_expected_decompressed_size + m_files_to_extract); - - LOGD("%s of %s - %f%% (%d/%d files)", - bytesToReadableString(m_overall_decompressed).c_str(), - bytesToReadableString(m_expected_decompressed_size).c_str(), - m_progress_overall * 100.0, - m_files_extracted, m_files_to_extract); -} - -double ExtractAllProgressCallback::getCurrentFileProgress() const -{ - if(m_current_file_size > 0) { - return static_cast(m_current_file_extracted_bytes) / - static_cast(m_current_file_size); - } - else { - return 1.0; - } -} - -double ExtractAllProgressCallback::getOverallProgress() const -{ - return m_progress_overall; -} - -void ExtractAllProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - archive_file_ptr->extractAllTask(this); -} - -void ExtractAllProgressCallback::setExpectedDecompressedSize(unsigned long exp_dec_size) -{ - m_expected_decompressed_size = exp_dec_size; -} - -unsigned long ExtractAllProgressCallback::getExpectedDecompressedSize() const -{ - return m_expected_decompressed_size; -} - -void ExtractAllProgressCallback::setNumberOfFilesToExtract(unsigned long files_count) -{ - m_files_to_extract = files_count; -} - -unsigned long ExtractAllProgressCallback::getNumberOfFilesToExtract() const -{ - return m_files_to_extract; -} - -//---------------------------------------------------------------------------------------- -//OperationCanceledException -//---------------------------------------------------------------------------------------- - -const char* OPERATION_CANCELED_EXCEPTION = "OperationCanceledException"; - -OperationCanceledException::OperationCanceledException(const char* message): - BasePlatformException(OPERATION_CANCELED_EXCEPTION, message) -{ - LOGD("Entered"); -} - -OperationCanceledException::OperationCanceledException(JSContextRef ctx, - JSValueRef exception): - BasePlatformException(ctx, exception) -{ - mName = OPERATION_CANCELED_EXCEPTION; -} - -//---------------------------------------------------------------------------------------- -//ExtractEntryProgressCallback -//---------------------------------------------------------------------------------------- - -ExtractEntryProgressCallback::ExtractEntryProgressCallback(JSContextRef globalCtx): - ExtractAllProgressCallback(globalCtx), - m_strip_name(false) -{ - LOGD("Entered"); - m_callback_type = EXTRACT_ENTRY_PROGRESS_CALLBACK; -} - -ExtractEntryProgressCallback::~ExtractEntryProgressCallback() -{ - LOGD("Entered"); -} - -ArchiveFileEntryPtr ExtractEntryProgressCallback::getArchiveFileEntry() -{ - return m_archive_file_entry; -} - -void ExtractEntryProgressCallback::setArchiveFileEntry(ArchiveFileEntryPtr afentry) -{ - m_archive_file_entry = afentry; -} - -void ExtractEntryProgressCallback::setStripName(bool strip_name) -{ - m_strip_name = strip_name; -} - -bool ExtractEntryProgressCallback::getStripName() const -{ - return m_strip_name; -} - -void ExtractEntryProgressCallback::setStripBasePath( - const std::string& strip_base_path) -{ - m_strip_base_path = strip_base_path; -} - -const std::string& ExtractEntryProgressCallback::getStripBasePath() const -{ - return m_strip_base_path; -} - -void ExtractEntryProgressCallback::executeOperation(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - - if(!m_archive_file_entry) { - LOGE("ArchiveFileEntry is not set in callback"); - throw UnknownException("Could not extract archive file entry"); - } - - if(!archive_file_ptr) { - LOGE("archive_file_ptr is NULL"); - throw UnknownException("Could not extract archive file entry"); - } - - UnZipPtr unzip = archive_file_ptr->createUnZipObject(); - unzip->extractTo(this); -} - -} -} diff --git a/src/archive/old/ArchiveCallbackData.h b/src/archive/old/ArchiveCallbackData.h deleted file mode 100644 index 3e95194a..00000000 --- a/src/archive/old/ArchiveCallbackData.h +++ /dev/null @@ -1,280 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -/** - * @file ArchiveCallbackData.h - */ - -#ifndef __ARCHIVE_CALLBACK_DATA_H__ -#define __ARCHIVE_CALLBACK_DATA_H__ - -#include -#include - -#include -#include - -#include //File from filesystem - -#include "ArchiveFileEntry.h" - -namespace DeviceAPI { -namespace Archive { - -class ArchiveFileEntry; -typedef std::shared_ptr ArchiveFileEntryPtr; - -enum ArchiveCallbackType { - OPERATION_CALLBACK_DATA = 0, - OPEN_CALLBACK_DATA = 1, - GET_ENTRIES_CALLBACK_DATA = 2, - GET_ENTRY_BY_NAME_CALLBACK_DATA = 3, - BASE_PROGRESS_CALLBACK = 4, - EXTRACT_ALL_PROGRESS_CALLBACK = 5, - EXTRACT_ENTRY_PROGRESS_CALLBACK = 6, - ADD_PROGRESS_CALLBACK = 7 -}; - -class ArchiveFile; -typedef std::shared_ptr ArchiveFilePtr; - -class OperationCallbackData : public Common::MultiCallbackUserData -{ -public: - OperationCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type = OPERATION_CALLBACK_DATA); - virtual ~OperationCallbackData(); - - void setSuccessCallback(JSValueRef on_success); - void setErrorCallback(JSValueRef on_error); - - void callSuccessCallback(); - void callSuccessCallback(JSValueRef err); - void callErrorCallback(JSValueRef err); - - void setError(const std::string &err_name, - const std::string &err_message); - bool isError() const; - const std::string& getErrorName() const; - const std::string& getErrorMessage() const; - - void setOperationId(long op_id); - long getOperationId() const; - - ArchiveCallbackType getCallbackType() const; - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - - bool isCanceled() const; - void setIsCanceled(bool is_cancel); - - ArchiveFilePtr getArchiveFile() const; - void setArchiveFile(ArchiveFilePtr caller); - -protected: - ArchiveCallbackType m_callback_type; - long m_op_id; - -private: - bool m_is_error; - bool m_is_canceled; - std::string m_err_name; - std::string m_err_message; - - ArchiveFilePtr m_caller_instance; -}; - -class OpenCallbackData : public OperationCallbackData -{ -public: - OpenCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type = OPEN_CALLBACK_DATA); - virtual ~OpenCallbackData(); - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); -}; - -class GetEntriesCallbackData : public OperationCallbackData -{ -public: - GetEntriesCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type = GET_ENTRIES_CALLBACK_DATA); - virtual ~GetEntriesCallbackData(); - - ArchiveFileEntryPtrMapPtr getEntries() const; - void setEntries(ArchiveFileEntryPtrMapPtr entries); - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - -private: - ArchiveFileEntryPtrMapPtr m_entries; -}; - -class GetEntryByNameCallbackData : public OperationCallbackData -{ -public: - GetEntryByNameCallbackData(JSContextRef globalCtx, - ArchiveCallbackType callback_type = GET_ENTRY_BY_NAME_CALLBACK_DATA); - virtual ~GetEntryByNameCallbackData(); - - const std::string& getName() const; - void setName(const std::string& name); - - ArchiveFileEntryPtr getFileEntry() const; - void setFileEntry(ArchiveFileEntryPtr entry); - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); -private: - std::string m_name; - ArchiveFileEntryPtr m_file_entry; - -}; - -class BaseProgressCallback : public OperationCallbackData -{ -public: - BaseProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type = BASE_PROGRESS_CALLBACK); - virtual ~BaseProgressCallback(); - - void setProgressCallback(JSValueRef on_progress); - - bool getOverwrite() const; - void setOverwrite(bool overwrite); - - void callProgressCallbackOnMainThread(const double progress, - ArchiveFileEntryPtr current_entry); - void callSuccessCallbackOnMainThread(); - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - -protected: - void callProgressCallback(long operationId, - double value, - const std::string& filename); - -private: - static gboolean callProgressCallbackCB(void* data); - static gboolean callSuccessCallbackCB(void* data); - - bool m_overwrite; -}; - -class AddProgressCallback : public BaseProgressCallback -{ -public: - AddProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type = ADD_PROGRESS_CALLBACK); - virtual ~AddProgressCallback(); - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - - void setBasePath(const std::string& path); - const std::string& getBasePath(); - const std::string& getBaseVirtualPath(); - - ArchiveFileEntryPtr getFileEntry() const; - void setFileEntry(ArchiveFileEntryPtr file_entry); - -private: - ArchiveFileEntryPtr m_file_entry; - ArchiveFileEntryPtrMapPtr m_entry_map; - std::string m_base_path; - std::string m_base_virt_path; -}; - -class ExtractAllProgressCallback : public BaseProgressCallback -{ -public: - ExtractAllProgressCallback(JSContextRef globalCtx, - ArchiveCallbackType callback_type = EXTRACT_ALL_PROGRESS_CALLBACK); - virtual ~ExtractAllProgressCallback(); - - Filesystem::FilePtr getDirectory() const; - void setDirectory(Filesystem::FilePtr directory); - - void startedExtractingFile(unsigned long current_file_size); - void extractedPartOfFile(unsigned long bytes_decompressed); - void finishedExtractingFile(); - - double getCurrentFileProgress() const; - double getOverallProgress() const; - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - - void setExpectedDecompressedSize(unsigned long exp_dec_size); - unsigned long getExpectedDecompressedSize() const; - - void setNumberOfFilesToExtract(unsigned long files_count); - unsigned long getNumberOfFilesToExtract() const; - -private: - void updateOverallProgress(unsigned long bytes_decompressed); - - Filesystem::FilePtr m_directory; - - // - // Constant values set before extracting entries: - // - unsigned long m_files_to_extract; - unsigned long m_expected_decompressed_size; - - // - // Values updated during extraction - // - - unsigned long m_current_file_size; - unsigned long m_current_file_extracted_bytes; - unsigned long m_files_extracted; - - double m_progress_overall; - unsigned long m_overall_decompressed; -}; - -class ExtractEntryProgressCallback : public ExtractAllProgressCallback -{ -public: - ExtractEntryProgressCallback(JSContextRef globalCtx); - virtual ~ExtractEntryProgressCallback(); - - ArchiveFileEntryPtr getArchiveFileEntry(); - void setArchiveFileEntry(ArchiveFileEntryPtr afentry); - - void setStripName(bool strip_name); - bool getStripName() const; - - void setStripBasePath(const std::string& strip_base_path); - const std::string& getStripBasePath() const; - - virtual void executeOperation(ArchiveFilePtr archive_file_ptr); - -private: - ArchiveFileEntryPtr m_archive_file_entry; - bool m_strip_name; - std::string m_strip_base_path; -}; - -class OperationCanceledException : public Common::BasePlatformException { -public: - OperationCanceledException(const char* message = "Operation Canceled"); - OperationCanceledException(JSContextRef ctx, JSValueRef exception); -}; - -} -} - -#endif //__ARCHIVE_CALLBACK_DATA_H__ diff --git a/src/archive/old/ArchiveFile.cpp b/src/archive/old/ArchiveFile.cpp deleted file mode 100644 index acea0a3b..00000000 --- a/src/archive/old/ArchiveFile.cpp +++ /dev/null @@ -1,748 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "ArchiveFile.h" - -#include -#include -#include -#include - -#include "ArchiveManager.h" -#include "JSArchiveFileEntry.h" -#include "JSArchiveFile.h" -#include "ArchiveUtils.h" -#include "plugin_config_impl.h" -#include "UnZip.h" -#include "Zip.h" - -namespace DeviceAPI { -namespace Archive { - -using namespace Common; - -Permission::Permission(bool r, bool w, bool rw, bool a){ - permission[0] = r; - permission[1] = w; - permission[2] = rw; - permission[3] = a; -} - -PermissionMap ArchiveFile::s_permission_map = { - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, - Permission(NOT_ALLOWED, ALLOWED, ALLOWED, ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)}, - {ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, - Permission(ALLOWED, NOT_ALLOWED, ALLOWED, NOT_ALLOWED)} -}; - -ArchiveFile::ArchiveFile() : - enable_shared_from_this(), - m_decompressed_size(0), - m_is_open(false), - m_overwrite(false), - m_created_as_new_empty_archive(false) -{ - LOGD("Entered"); -} - -ArchiveFile::ArchiveFile(FileMode file_mode) : - enable_shared_from_this(), - m_decompressed_size(0), - m_is_open(false), - m_overwrite(false) -{ - m_file_mode = file_mode; -} - -ArchiveFile::~ArchiveFile() -{ - LOGD("Entered"); - - if(m_entry_map) { - LOGD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(NULL); - } - } - } -} - -gboolean ArchiveFile::openTaskCompleteCB(void *data) -{ - LOGD("Entered"); - auto callback = static_cast(data); - if (!callback) { - LOGE("callback is null"); - return false; - } - - JSContextRef context = callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context was closed"); - delete callback; - callback = NULL; - return false; - } - try { - if (callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - } - else { - JSObjectRef result = JSArchiveFile::makeJSObject(context, - callback->getArchiveFile()); - callback->callSuccessCallback(result); - } - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - delete callback; - callback = NULL; - - return false; -} - -gboolean ArchiveFile::callErrorCallback(void* data) -{ - LOGD("Entered"); - auto callback = static_cast(data); - if (!callback) { - LOGE("callback is null"); - return false; - } - - JSContextRef context = callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context was closed"); - delete callback; - callback = NULL; - return false; - } - - try { - if (callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - } - else { - LOGW("The success callback should be not be called in this case"); - } - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - delete callback; - callback = NULL; - - return false; -} - -void* ArchiveFile::taskManagerThread(void *data) -{ - LOGD("Entered"); - ArchiveFileHolder* archive_file_holder = static_cast(data); - if (!archive_file_holder) { - LOGE("archive_file_holder is null"); - return NULL; - } - - if (!archive_file_holder->ptr){ - LOGE("archive_file is null"); - delete archive_file_holder; - archive_file_holder = NULL; - return NULL; - } - - while(true){ - OperationCallbackData* callback = NULL; - bool call_error_callback = false; - try{ - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - if(archive_file_holder->ptr->m_task_queue.empty()){ - break; - } - callback = archive_file_holder->ptr->m_task_queue.back().second; - } - if(callback && !callback->isCanceled()){ - callback->executeOperation(archive_file_holder->ptr); - } - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } - } catch (const OperationCanceledException &err) { - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } - delete callback; - callback = NULL; - } catch (const BasePlatformException &err) { - LOGE("taskManagerThread fails, %s: %s", err.getName().c_str(), - err.getMessage().c_str()); - callback->setError(err.getName().c_str(), err.getMessage().c_str()); - call_error_callback = true; - } catch (...) { - LOGE("taskManagerThread fails"); - callback->setError(JSWebAPIErrorFactory::UNKNOWN_ERROR, "UnknownError."); - call_error_callback = true; - } - if(call_error_callback) { - { - std::lock_guard lock(archive_file_holder->ptr->m_mutex); - archive_file_holder->ptr->m_task_queue.pop_back(); - } - if (!g_idle_add(callErrorCallback, static_cast(callback))) { - LOGE("g_idle_add fails"); - delete callback; - callback = NULL; - } - } - } - - delete archive_file_holder; - archive_file_holder = NULL; - - return NULL; -} - -long ArchiveFile::addOperation(OperationCallbackData* callback) -{ - LOGD("Entered callback type:%d", callback->getCallbackType()); - - const long operation_id = - ArchiveManager::getInstance().getNextOperationId(shared_from_this()); - callback->setOperationId(operation_id); - callback->setArchiveFile(shared_from_this()); - std::size_t size = 0; - { - std::lock_guard lock(m_mutex); - m_task_queue.push_front(CallbackPair(operation_id, callback)); - size = m_task_queue.size(); - } - if(1 == size){ - pthread_t thread; - ArchiveFileHolder* holder = new(std::nothrow) ArchiveFileHolder(); - if(!holder){ - LOGE("Memory allocation error"); - throw UnknownException("Memory allocation error"); - } - holder->ptr = shared_from_this(); - if (pthread_create(&thread, NULL, taskManagerThread, - static_cast(holder))) { - LOGE("Thread creation failed"); - delete holder; - holder = NULL; - throw UnknownException("Thread creation failed"); - } - - if (pthread_detach(thread)) { - LOGE("Thread detachment failed"); - } - } - return operation_id; -} - -void ArchiveFile::extractAllTask(ExtractAllProgressCallback* callback) -{ - Filesystem::FilePtr directory = callback->getDirectory(); - - if(!directory) { - LOGE("Directory is null"); - throw UnknownException("Directory is null"); - } else { - if(!directory->getNode()){ - LOGE("Node in directory is null"); - throw UnknownException("Node is null"); - } - } - - if(!m_file) { - LOGE("File is null"); - throw UnknownException("File is null"); - } else { - if(!m_file->getNode()){ - LOGE("Node in file is null"); - throw UnknownException("Node in file is null"); - } - } - - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - if(m_file->getNode()->getSize() == 0) { - LOGD("Zip file: %s is empty", - m_file->getNode()->getPath()->getFullPath().c_str()); - - if(m_created_as_new_empty_archive) { - //We do not call progress callback since we do not have any ArchiveFileEntry - callback->callSuccessCallbackOnMainThread(); - callback = NULL; - return; - } - else { - LOGW("m_created_as_new_empty_archive is false"); - LOGE("Throwing InvalidStateException: File is not valid ZIP archive"); - throw InvalidStateException("File is not valid ZIP archive"); - } - } - - UnZipPtr unzip = createUnZipObject(); - unzip->extractAllFilesTo(directory->getNode()->getPath()->getFullPath(), callback); -} - -long ArchiveFile::getEntries(GetEntriesCallbackData* callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Could not get list of files in archive"); - } - - throwInvalidStateErrorIfArchiveFileIsClosed(); - - return addOperation(callback); -} - -gboolean ArchiveFile::getEntriesTaskCompleteCB(void *data) -{ - auto callback = static_cast(data); - if (!callback) { - LOGE("callback is null"); - return false; - } - - JSContextRef context = callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context was closed"); - delete callback; - callback = NULL; - return false; - } - - try { - ArchiveFileEntryPtrMapPtr entries = callback->getEntries(); - unsigned int size = entries->size(); - - JSObjectRef objArray[size]; - int i = 0; - for(auto it = entries->begin(); it != entries->end(); it++) { - objArray[i] = JSArchiveFileEntry::makeJSObject(context, it->second); - i++; - } - - JSValueRef exception = NULL; - JSObjectRef jsResult = JSObjectMakeArray(context, size, - size > 0 ? objArray : NULL, &exception); - if (exception != NULL) { - throw Common::UnknownException(context, exception); - } - - callback->callSuccessCallback(jsResult); - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - delete callback; - callback = NULL; - - return false; -} - -long ArchiveFile::extractAll(ExtractAllProgressCallback *callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Could not extract all files from archive"); - } - - throwInvalidStateErrorIfArchiveFileIsClosed(); - - return addOperation(callback); -} - -long ArchiveFile::extractEntryTo(ExtractEntryProgressCallback* callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Could not extract archive file entry"); - } - - // FIXME according to documentation: - // if archive was closed, any further operation attempt will make InvalidStateError - // but method extract() from ArchiveFileEntryObject is not permitted to throw above exception - - // uncomment in case when this method have permission to throwing InvalidStateError - // throwInvalidStateErrorIfArchiveFileisClosed(); - if(!m_is_open) { - LOGE("Archive is not opened"); - throw UnknownException("Archive is not opened"); - } - - return addOperation(callback); -} - - -long ArchiveFile::add(AddProgressCallback *callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Could not add file to archive"); - } - if(FileMode::READ == m_file_mode) { - LOGE("Trying to add file when READ access mode selected"); - throw InvalidAccessException("Add not allowed for \"r\" access mode"); - } - - throwInvalidStateErrorIfArchiveFileIsClosed(); - - return addOperation(callback); -} - -void ArchiveFile::close() -{ - LOGD("Entered"); - - if(!m_is_open){ - LOGD("Archive already closed"); - } - m_is_open = false; - - return; -} - -long ArchiveFile::getEntryByName(GetEntryByNameCallbackData* callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Could not get archive file entries by name"); - } - - throwInvalidStateErrorIfArchiveFileIsClosed(); - - return addOperation(callback); -} - -gboolean ArchiveFile::getEntryByNameTaskCompleteCB(void *data) -{ - auto callback = static_cast(data); - if (!callback) { - LOGE("callback is null"); - return false; - } - - JSContextRef context = callback->getContext(); - if (!GlobalContextManager::getInstance()->isAliveGlobalContext(context)) { - LOGE("context was closed"); - delete callback; - callback = NULL; - return false; - } - try { - if (callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - } - else { - JSObjectRef entry = JSArchiveFileEntry::makeJSObject(context, - callback->getFileEntry()); - callback->callSuccessCallback(entry); - } - } - catch (const BasePlatformException &err) { - LOGE("%s (%s)", err.getName().c_str(), err.getMessage().c_str()); - } - catch (...) { - LOGE("Unknown error occurs"); - } - - delete callback; - callback = NULL; - - return false; -} - -Filesystem::FilePtr ArchiveFile::getFile() const -{ - LOGD("Entered"); - return m_file; -} - -void ArchiveFile::setFile(Filesystem::FilePtr file) -{ - LOGD("Entered"); - m_file = file; -} - -bool ArchiveFile::isOverwrite() const -{ - return m_overwrite; -} - -void ArchiveFile::setOverwrite(bool overwrite) -{ - LOGD("Entered"); - m_overwrite = overwrite; -} - -unsigned long ArchiveFile::getDecompressedSize() const -{ - LOGD("Entered"); - return m_decompressed_size; -} - -void ArchiveFile::setDecompressedSize(unsigned long decompressed_size) -{ - LOGD("Entered"); - m_decompressed_size = decompressed_size; -} - -bool ArchiveFile::isOpen() const -{ - LOGD("Entered"); - return m_is_open; -} - -void ArchiveFile::setIsOpen(bool is_open) -{ - LOGD("Entered"); - m_is_open = is_open; -} - -ArchiveFileEntryPtrMapPtr ArchiveFile::getEntryMap() const -{ - return m_entry_map; -} - -void ArchiveFile::setEntryMap(ArchiveFileEntryPtrMapPtr entries) -{ - LOGD("Entered"); - - if(m_entry_map) { - LOGD("Unlinking old m_entry_map: %d ArchiveFileEntries", m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(NULL); - } - } - } - - m_entry_map = entries; - - LOGD("Linking new m_entry_map ArchiveFileEntries (%d) with ArchiveFile object", - m_entry_map->size()); - for(auto it = m_entry_map->begin(); it != m_entry_map->end(); ++it) { - if(it->second) { - it->second->setArchiveFileNonProtectPtr(this); - } - } -} - -UnZipPtr ArchiveFile::createUnZipObject() -{ - LOGD("Entered"); - if(!m_is_open) { - LOGE("File is not opened"); - throw UnknownException("File is not opened"); - } - - if (!m_file) { - LOGE("m_file is null"); - throw UnknownException("File is null"); - } - - Filesystem::NodePtr node = m_file->getNode(); - if(!node) { - LOGE("Node is null"); - throw UnknownException("Node is null"); - } - - UnZipPtr unzip = UnZip::open(node->getPath()->getFullPath()); - return unzip; -} - -ZipPtr ArchiveFile::createZipObject() -{ - LOGD("Entered"); - if(!m_is_open) { - LOGE("File is not opened"); - throw UnknownException("File is not opened"); - } - - if (!m_file) { - LOGE("m_file is null"); - throw UnknownException("File is null"); - } - - Filesystem::NodePtr node = m_file->getNode(); - if(!node) { - LOGE("Node is null"); - throw UnknownException("Node is null"); - } - - ZipPtr zip = Zip::open(node->getPath()->getFullPath()); - return zip; - -} - -bool ArchiveFile::isAllowedOperation(const std::string& method_name) -{ - LOGD("Entered"); - PermissionMap::iterator it = s_permission_map.find(method_name); - if (it != s_permission_map.end()) { - return it->second.permission[m_file_mode]; - } - return false; -} - -FileMode ArchiveFile::getFileMode() const -{ - LOGD("Entered"); - return m_file_mode; -} - -void ArchiveFile::setFileMode(FileMode file_mode) -{ - LOGD("Entered"); - m_file_mode = file_mode; -} - -void ArchiveFile::throwInvalidStateErrorIfArchiveFileIsClosed() const -{ - if(!m_is_open){ - LOGE("ArchiveFile closed - operation not permitted"); - throw InvalidStateException( - "ArchiveFile closed - operation not permitted"); - } -} - -void ArchiveFile::setCreatedAsNewEmptyArchive(bool new_and_empty) -{ - m_created_as_new_empty_archive = new_and_empty; -} - -bool ArchiveFile::isCreatedAsNewEmptyArchive() const -{ - return m_created_as_new_empty_archive; -} - -void ArchiveFile::updateListOfEntries() -{ - // For explanation please see: - // ArchiveFile.h m_created_as_new_empty_archive description - // - if(m_file->getNode()->getSize() == 0) { - LOGD("Zip file: %s is empty", - m_file->getNode()->getPath()->getFullPath().c_str()); - - if(m_created_as_new_empty_archive) { - LOGD("OK this is empty archive = nothing to do yet"); - return; - } - else { - LOGW("m_created_as_new_empty_archive is false"); - LOGE("Throwing InvalidStateException: File is not valid ZIP archive"); - throw InvalidStateException("File is not valid ZIP archive"); - } - } - - UnZipPtr unzip = createUnZipObject(); - unsigned long decompressedSize = 0; - ArchiveFileEntryPtrMapPtr emap = unzip->listEntries(&decompressedSize); - setEntryMap(emap); - setDecompressedSize(decompressedSize); -} - -bool ArchiveFile::isEntryWithNameInArchive(const std::string& name_in_zip, - bool* out_is_directory, - std::string* out_matching_name) -{ - if(!m_entry_map) { - LOGW("m_entry_map is NULL"); - return false; - } - - const bool name_in_zip_is_dir = isDirectoryPath(name_in_zip); - bool set_is_directory = false; - bool set_name_exists = false; - - //Try exact name: - auto it = m_entry_map->find(name_in_zip); - if(it != m_entry_map->end()) { - set_is_directory = name_in_zip_is_dir; - set_name_exists = true; - } - else { - if(name_in_zip_is_dir) { - //If name_in_zip is pointing at directory try file - it = m_entry_map->find(removeTrailingDirectorySlashFromPath(name_in_zip)); - set_is_directory = false; - } else { - //If name_in_zip is pointing at file try directory - it = m_entry_map->find(name_in_zip + "/"); - set_is_directory = true; - } - - if(it != m_entry_map->end()) { - set_name_exists = true; - } - } - - if(!set_name_exists) { - return false; - } - - if(out_is_directory) { - *out_is_directory = set_is_directory; - } - if(out_matching_name) { - *out_matching_name = it->first; - } - - return true; -} - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/ArchiveFile.h b/src/archive/old/ArchiveFile.h deleted file mode 100755 index b18b9fbe..00000000 --- a/src/archive/old/ArchiveFile.h +++ /dev/null @@ -1,188 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#ifndef _TIZEN_ARCHIVE_ARCHIVE_FILE_H_ -#define _TIZEN_ARCHIVE_ARCHIVE_FILE_H_ - -#include -#include -#include -#include // from filesystem - -#include "ArchiveCallbackData.h" -#include "UnZip.h" -#include "Zip.h" -#include "ArchiveManager.h" - - -namespace DeviceAPI { -namespace Archive { - -class ArchiveFile; -class ArchiveManager; -class OperationCallbackData; -class OpenCallbackData; -class GetEntriesCallbackData; -class GetEntryByNameCallbackData; -class BaseProgressCallback; -class AddProgressCallback; -class ExtractAllProgressCallback; -class UnZipExtractRequest; -class ExtractEntryProgressCallback; -class Zip; -class ZipAddRequest; - -enum FileMode { - READ = 0, - WRITE, - READ_WRITE, - ADD -}; - -enum IsAllowed { - NOT_ALLOWED = false, - ALLOWED = true -}; - -struct Permission { - Permission(bool r, bool w, bool rw, bool a); - bool permission[4]; -}; - -typedef std::shared_ptr ArchiveFilePtr; -typedef std::pair CallbackPair; -typedef std::vector ArchiveFileEntryPtrVector; -typedef std::map PermissionMap; -typedef std::pair PermissionPair; - -struct ArchiveFileHolder{ - ArchiveFilePtr ptr; -}; - -class ArchiveFile : public std::enable_shared_from_this { -public: - ArchiveFile(); - ArchiveFile(FileMode file_mode); - virtual ~ArchiveFile(); - - long getEntries(GetEntriesCallbackData* callback); - long getEntryByName(GetEntryByNameCallbackData* callback); - long extractAll(ExtractAllProgressCallback *callback); - long add(AddProgressCallback *callback); - void close(); - - Filesystem::FilePtr getFile() const; - void setFile(Filesystem::FilePtr file); - bool isOverwrite() const; - void setOverwrite(bool overwrite); - unsigned long getDecompressedSize() const; - void setDecompressedSize(unsigned long decompressed_size); - bool isOpen() const; - void setIsOpen(bool is_open); - - ArchiveFileEntryPtrMapPtr getEntryMap() const; - void setEntryMap(ArchiveFileEntryPtrMapPtr entries); - bool isEntryWithNameInArchive(const std::string& name_in_zip, - bool* out_is_directory = NULL, - std::string* out_matching_name = NULL); - - - //Used by ArchiveFileEntry - long extractEntryTo(ExtractEntryProgressCallback* callback); - - bool isAllowedOperation(const std::string& method_name); - FileMode getFileMode() const; - void setFileMode(FileMode file_mode); - - /** - * \brief Throw InvalidStateError in case when ArchiveFile is closed - */ - void throwInvalidStateErrorIfArchiveFileIsClosed() const; - - void setCreatedAsNewEmptyArchive(bool new_and_empty); - bool isCreatedAsNewEmptyArchive() const; - - - void updateListOfEntries(); -private: - UnZipPtr createUnZipObject(); - ZipPtr createZipObject(); - - std::deque m_task_queue; - std::mutex m_mutex; - - Filesystem::FilePtr m_file; - - FileMode m_file_mode; - static PermissionMap s_permission_map; - - unsigned long m_decompressed_size; - bool m_is_open; - /** - * If set to true, during decompression archive will had permission to overwriting files. - * Warning: If decompressing file have got the same name as existing directory - * in place where file should be decompressed, directory will be deleted. - */ - bool m_overwrite; - ArchiveFileEntryPtrMapPtr m_entry_map; - - - /** - * If we execute tizen.open(destFile , "w"/"rw"/ "a", ..., {overwrite: true}), - * destFile will be empty file with size = 0, which cannot be - * opened with minizip library. - * - * Zip file format restricts that at least one file / folder is compressed, - * threfore after creating new empty archive we cannot save it. - * Until we execute archive.add destFile is empty file with size 0 bytes. - * - * Unfortunately if we try to execute archive.getEntries or archive.extractAll - * minizip library will fail to open empty archive. To fix this issue we will - * use flag "created_as_new_empty_archive" which informs that this is new and - * empty archive threfore we should not try to open it. - * - * In extractAll we will just call success callback - there was nothing to extract - * but no error occured. In get entries we just should return empty list of entries. - */ - bool m_created_as_new_empty_archive; - - static gboolean openTaskCompleteCB(void *data); - static gboolean getEntriesTaskCompleteCB(void *data); - static gboolean getEntryByNameTaskCompleteCB(void *data); - - static void* taskManagerThread(void *data); - long addOperation(OperationCallbackData* callback); - static gboolean callErrorCallback(void* data); - - void extractAllTask(ExtractAllProgressCallback* callback); - - friend class ExtractAllProgressCallback; - friend class UnZipExtractRequest; - friend class OpenCallbackData; - friend class GetEntriesCallbackData; - friend class GetEntryByNameCallbackData; - friend class ExtractEntryProgressCallback; - friend class ArchiveManager; - friend class AddProgressCallback; - friend class Zip; - friend class ZipAddRequest; - friend class BaseProgressCallback; -}; - -} // Archive -} // DeviceAPI - -#endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/old/ArchiveFileEntry.cpp b/src/archive/old/ArchiveFileEntry.cpp deleted file mode 100644 index ce74e375..00000000 --- a/src/archive/old/ArchiveFileEntry.cpp +++ /dev/null @@ -1,175 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "ArchiveFileEntry.h" - -#include -#include -#include -#include - -#include "ArchiveCallbackData.h" -#include "ArchiveFile.h" -#include "ArchiveUtils.h" - -namespace DeviceAPI { - -using namespace DeviceAPI::Common; - -namespace Archive { - -static const unsigned int s_default_compression_level = 5; - -ArchiveFileEntry::ArchiveFileEntry(Filesystem::FilePtr file) : - std::enable_shared_from_this(), - m_file(file), - m_archive(NULL), - m_striped(false), - m_size(0), - m_compressed_size(0), - m_modified(0), - m_compression_level(s_default_compression_level) -{ - LOGD("Entered"); -} - -ArchiveFileEntry::~ArchiveFileEntry() -{ - LOGD("Entered"); -} - -unsigned long ArchiveFileEntry::getCompressedSize() const -{ - return m_compressed_size; -} - -void ArchiveFileEntry::setCompressedSize(unsigned long compressed_size) -{ - m_compressed_size = compressed_size; -} - -Filesystem::FilePtr ArchiveFileEntry::getFile() const -{ - return m_file; -} - -void ArchiveFileEntry::setFile(Filesystem::FilePtr file) -{ - m_file = file; -} - -unsigned long ArchiveFileEntry::getSize() const -{ - return m_size; -} - -void ArchiveFileEntry::setSize(unsigned long size) -{ - m_size = size; -} - -const std::string& ArchiveFileEntry::getName() const -{ - return m_name; -} - -void ArchiveFileEntry::setName(const std::string& name) -{ - m_name = name; -} - -void ArchiveFileEntry::setModified(time_t time) -{ - m_modified = time; -} - -time_t ArchiveFileEntry::getModified() const -{ - return m_modified; -} - -const std::string& ArchiveFileEntry::getDestination() const -{ - return m_destination; -} - -void ArchiveFileEntry::setDestination(const std::string& destination) -{ - m_destination = destination; -} - -bool ArchiveFileEntry::getStriped() const -{ - return m_striped; -} - -void ArchiveFileEntry::setStriped(bool striped) -{ - m_striped = striped; -} - -void ArchiveFileEntry::setCompressionLevel(unsigned int level) -{ - m_compression_level = level; -} -unsigned int ArchiveFileEntry::getCompressionLevel() const -{ - return m_compression_level; -} - -void ArchiveFileEntry::setArchiveFileNonProtectPtr(ArchiveFile* ptr) -{ - m_archive = ptr; -} - -ArchiveFile* ArchiveFileEntry::getArchiveFileNonProtectPtr() -{ - return m_archive; -} - -long ArchiveFileEntry::extractTo(ExtractEntryProgressCallback* callback) -{ - if(!m_archive) { - LOGE("m_archive is NULL"); - throw UnknownException("Could not extract archive file entry"); - } - - //Callback should be associated with this instance of ArchiveFileEntry - callback->setArchiveFileEntry(shared_from_this()); - - // - // If strip name was set in JS layer we need to generate srip base path - // - if(callback->getStripName()) { - - //Get base path - left side of last slash - std::string base_path_name = getBasePathFromPath(m_name); - if(!isDirectoryPath(base_path_name) && !base_path_name.empty()) { - base_path_name += "/"; - } - - LOGD("strip name is: true; archive file entry name is: [%s]; " - "stripBasePath will be: [%s]", - m_name.c_str(), base_path_name.c_str()); - - callback->setStripBasePath(base_path_name); - } - - return m_archive->extractEntryTo(callback); -} - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/ArchiveFileEntry.h b/src/archive/old/ArchiveFileEntry.h deleted file mode 100755 index 51bf1c08..00000000 --- a/src/archive/old/ArchiveFileEntry.h +++ /dev/null @@ -1,81 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef _TIZEN_ARCHIVE_ARCHIVE_FILE_ENTRY_H_ -#define _TIZEN_ARCHIVE_ARCHIVE_FILE_ENTRY_H_ - -#include -#include // from filesystem - - - -namespace DeviceAPI { -namespace Archive { - -class ArchiveFile; - -class ArchiveFileEntry; -typedef std::shared_ptr ArchiveFileEntryPtr; - -class ExtractEntryProgressCallback; - -typedef std::map ArchiveFileEntryPtrMap; -typedef std::shared_ptr ArchiveFileEntryPtrMapPtr; - -class ArchiveFileEntry : public std::enable_shared_from_this { -public: - ArchiveFileEntry(Filesystem::FilePtr file = Filesystem::FilePtr()); - ~ArchiveFileEntry(); - - unsigned long getCompressedSize() const; - void setCompressedSize(unsigned long compressedSize); - Filesystem::FilePtr getFile() const; - void setFile(Filesystem::FilePtr file); - unsigned long getSize() const; - void setSize(unsigned long size); - const std::string& getName() const; - void setName(const std::string& name); - void setModified(time_t time); - time_t getModified() const; - const std::string& getDestination() const; - void setDestination(const std::string& destination); - bool getStriped() const; - void setStriped(bool striped); - void setCompressionLevel(unsigned int level); - unsigned int getCompressionLevel() const; - - void setArchiveFileNonProtectPtr(ArchiveFile* ptr); - ArchiveFile* getArchiveFileNonProtectPtr(); - - long extractTo(ExtractEntryProgressCallback* callback); - -private: - Filesystem::FilePtr m_file; - ArchiveFile* m_archive; - std::string m_name; - std::string m_destination; - bool m_striped; - unsigned long m_size; - unsigned long m_compressed_size; - time_t m_modified; - unsigned int m_compression_level; -}; - -} // Archive -} // DeviceAPI - -#endif /* _TIZEN_ARCHIVE_FILE_ENTRY_H_ */ diff --git a/src/archive/old/ArchiveManager.cpp b/src/archive/old/ArchiveManager.cpp deleted file mode 100644 index ef57ab8b..00000000 --- a/src/archive/old/ArchiveManager.cpp +++ /dev/null @@ -1,88 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include "ArchiveManager.h" - -#include - -namespace DeviceAPI { -namespace Archive { - -ArchiveManager::ArchiveManager(): - m_next_unique_id(0) -{ - LOGD("Initialize ArchiveManager"); -} - -ArchiveManager::~ArchiveManager() -{ - LOGD("Deinitialize ArchiveManager"); -} - -ArchiveManager& ArchiveManager::getInstance() -{ - LOGD("Entered"); - static ArchiveManager instance; - return instance; -} - -void ArchiveManager::abort(long operation_id) -{ - LOGD("Entered"); - ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); - if (it != m_archive_file_map.end()) { - ArchiveFilePtr archive_file_ptr = it->second; - std::lock_guard lock(archive_file_ptr->m_mutex); - - std::size_t size = archive_file_ptr->m_task_queue.size(); - for(int i = 0; i < size; ++i){ - if(operation_id == archive_file_ptr->m_task_queue[i].first){ - archive_file_ptr->m_task_queue[i].second->setIsCanceled(true); - return; - } - } - } - LOGD("The Operation Identifier not found"); -} - -long ArchiveManager::open(OpenCallbackData* callback) -{ - LOGD("Entered"); - - ArchiveFilePtr a_ptr = callback->getArchiveFile(); - return a_ptr->addOperation(callback); -} - - -long ArchiveManager::getNextOperationId(ArchiveFilePtr archive_file_ptr) -{ - LOGD("Entered"); - long op_id = ++m_next_unique_id; - m_archive_file_map.insert(ArchiveFilePair(op_id, archive_file_ptr)); - return op_id; -} - -void ArchiveManager::eraseElementFromArchiveFileMap(long operation_id) -{ - LOGD("Entered"); - ArchiveFileMap::iterator it = m_archive_file_map.find(operation_id); - if (it != m_archive_file_map.end()) { - m_archive_file_map.erase(it); - } -} - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/ArchiveManager.h b/src/archive/old/ArchiveManager.h deleted file mode 100755 index 322e19a2..00000000 --- a/src/archive/old/ArchiveManager.h +++ /dev/null @@ -1,56 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ -#define _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ - -#include -#include "ArchiveFile.h" -#include "ArchiveCallbackData.h" - - -namespace DeviceAPI { -namespace Archive { - -typedef std::map ArchiveFileMap; -typedef std::pair ArchiveFilePair; - -class ArchiveManager { -public: - static ArchiveManager& getInstance(); - ~ArchiveManager(); - - void abort(long operation_id); - long getNextOperationId(ArchiveFilePtr archive_file_ptr); - void eraseElementFromArchiveFileMap(long operation_id); - long open(OpenCallbackData* callback); - -private: - ArchiveManager(); - ArchiveManager(ArchiveManager const&); - void operator=(ArchiveManager const&); - - ArchiveFileMap m_archive_file_map; - - long m_next_unique_id; - -}; - -} // Archive -} // DeviceAPI - -#endif /* _TIZEN_ARCHIVE_ARCHIVE_MANAGER_H_ */ diff --git a/src/archive/old/ArchiveUtils.cpp b/src/archive/old/ArchiveUtils.cpp deleted file mode 100644 index 5e3a6f3e..00000000 --- a/src/archive/old/ArchiveUtils.cpp +++ /dev/null @@ -1,258 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "ArchiveUtils.h" -#include -#include -#include -#include -#include -#include - -#include -#include - -namespace DeviceAPI { -namespace Archive { - -using namespace DeviceAPI::Common; -using namespace DeviceAPI::Filesystem; - -std::string bytesToReadableString(const size_t num_bytes) -{ - std::stringstream ss; - static const size_t one_mb = 1024 * 1024; - static const size_t one_kb = 1024; - ss << std::setprecision(2) << std::fixed; - - if(num_bytes >= one_mb) { - ss << (float)num_bytes / one_mb << " MB"; - } else if(num_bytes >= one_kb) { - ss << (float)num_bytes / one_kb << " KB"; - } else { - ss << num_bytes << " B"; - } - - return ss.str(); -} - -std::string fileModeToString(FileMode fm) -{ - switch(fm) { - case FileMode::READ: - return "r"; - case FileMode::WRITE: - return "w"; - case FileMode::READ_WRITE: - return "rw"; - case FileMode::ADD: - return "a"; - default: - throw UnknownException("Unknown file mode"); - } -} - -FileMode stringToFileMode(std::string fmString) -{ - if (!fmString.compare("r")) { - return FileMode::READ; - } - else if (!fmString.compare("w")) { - return FileMode::WRITE; - } - else if(!fmString.compare("rw")) { - return FileMode::READ_WRITE; - } - else if(!fmString.compare("a")) { - return FileMode::ADD; - } - // In widl it's "TypeMismatchError" so this exception used - // instead of InvalidValues - throw TypeMismatchException("Invalid FileMode"); -} - -FilePtr fileReferenceToFile(JSContextRef context, JSValueRef fileReference) -{ - auto g_ctx = GlobalContextManager::getInstance()->getGlobalContext(context); - - FilePtr file_ptr; - try { - file_ptr = JSFile::getPrivateObject(context, fileReference); - } catch (const TypeMismatchException &tme) { - LOGD("Use virtual path."); - std::string virtual_path = - JSUtil::JSValueToString(context, fileReference); - if (!External::isVirtualPath(virtual_path)) { - LOGE("FileReference can be File object or a virtual path"); - throw TypeMismatchException( - "FileReference can be File object or a virtual path"); - } - std::string string_path = - External::fromVirtualPath(virtual_path, g_ctx); - LOGD("Path: %s", string_path.c_str()); - - PathPtr path = Path::create(string_path); - NodePtr node_ptr = Node::resolve(path); - file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); - } - - return file_ptr; -} - -void getBasePathAndName(const std::string& filepath, - std::string& out_basepath, - std::string& out_name) -{ - const size_t filepath_len = filepath.length(); - - size_t name_end_index = filepath_len; - size_t name_start_index = 0; - - for(int i = filepath_len - 1; i >= 0; --i) { - const char& cur = filepath[i]; - if(cur == '/' || cur == '\\') { - if( (filepath_len-1) == i ) { - name_end_index = i; - } else { - name_start_index = i+1; - out_name = filepath.substr(name_start_index, - name_end_index - name_start_index); - - out_basepath = filepath.substr(0, name_start_index); - return; - } - } - } - - // \ / is not found - out_basepath = ""; - out_name = filepath.substr(0, name_end_index); -} - -std::string removeDuplicatedSlashesFromPath(const std::string& path) -{ - const size_t path_len = path.length(); - - std::string out; - out.reserve(path_len); - - bool prev_is_dir = false; - for(size_t i = 0; i < path_len; ++i) { - const char& cur = path[i]; - if(cur == '/' || cur == '\\') { - if(!prev_is_dir) { - out += cur; - } - prev_is_dir = true; - } else { - prev_is_dir = false; - out += cur; - } - } - - return out; -} - -bool isDirectoryPath(const std::string& path) -{ - if(path.empty()) { - return false; - } - - const char last_char = path[path.length() - 1]; - return last_char == '\\' || last_char == '/'; -} - -std::string removeTrailingDirectorySlashFromPath(const std::string& path) -{ - if(!isDirectoryPath(path)) { - return path; - } - - return path.substr(0, path.length() - 1); -} - -std::string stripBasePathFromPath(const std::string& fullpath) -{ - const size_t location = fullpath.find_last_of("/\\"); - if(std::string::npos == location) { - return fullpath; - } - - return fullpath.substr(location + 1); -} - -namespace{ -static std::string errErrno = "ERRNO"; -static std::string errEndOfListOfFile = "End list of file"; -static std::string errParamater = "Invalid parameter"; -static std::string errBadFile = "Incorrect file"; -static std::string errInternal = "Internal error"; -static std::string errCRC = "CRC error"; -static std::string errUnknown = "Unknown error"; - -const std::string& getArchiveErrorMessage(int errorCode) -{ - /** - * All errors are defined in minizip library in files: - * zip.h and unzip.h - */ - switch (errorCode) { - // ZIP_ERRNO & UNZ_ERRNO both value Z_ERRNO - case ZIP_ERRNO: - return errErrno; - // UNZ_END_OF_LIST_OF_FILE both value -100 - case UNZ_END_OF_LIST_OF_FILE: - return errEndOfListOfFile; - // ZIP_PARAMERROR & UNZ_PARAMERROR both value -102 - case ZIP_PARAMERROR: - return errParamater; - // ZIP_BADZIPFILE & UNZ_BADZIPFILE both value -103 - case ZIP_BADZIPFILE: - return errBadFile; - // ZIP_INTERNALERROR & UNZ_INTERNALERROR bot value -104 - case ZIP_INTERNALERROR: - return errInternal; - // UNZ_CRCERROR -105 - case UNZ_CRCERROR: - return errCRC; - default: - return errUnknown; - } -} -} - -extern std::string getBasePathFromPath(const std::string& fullpath) -{ - const std::string tmp_path = removeTrailingDirectorySlashFromPath(fullpath); - const size_t location = tmp_path.find_last_of("/\\"); - if(std::string::npos == location) { - return std::string(); - } - - return tmp_path.substr(0, location + 1); -} - -extern std::string getArchiveLogMessage(const int errorCode, const std::string &hint) -{ - std::stringstream ss; - ss << "Failed " << hint << " : " << getArchiveErrorMessage(errorCode) << ", " << errorCode; - return std::string(ss.str()); -} - -} //namespace Archive -} //namespace DeviceAPI diff --git a/src/archive/old/ArchiveUtils.h b/src/archive/old/ArchiveUtils.h deleted file mode 100644 index 140f7f0c..00000000 --- a/src/archive/old/ArchiveUtils.h +++ /dev/null @@ -1,124 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ -#define __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ - -#include -#include -#include - -#include -#include "ArchiveFile.h" - -namespace DeviceAPI { -namespace Archive { - -extern std::string bytesToReadableString(const size_t num_bytes); -extern std::string fileModeToString(FileMode fm); -extern FileMode stringToFileMode(std::string fmString); -extern Filesystem::FilePtr fileReferenceToFile( - JSContextRef context, JSValueRef fileReference); - -/** - * Gets base path and name from full path string, example cases: - * full path | base path | name - * ----------------------+-------------------+------------------ - * "" | "" | "" - * "/opt/usr/media/TEST" | "/opt/usr/media/" | "TEST" - * "/opt/usr/media/TEST/"| "/opt/usr/media/" | "TEST" - * "opt/usr/media/TEST" | "opt/usr/media/" | "TEST" - * "opt/usr/media/TEST/" | "opt/usr/media/" | "TEST" - * "TEST" | "" | "TEST" - * "TEST/" | "" | "TEST" - * "/TEST/" | "/" | "TEST" - */ -extern void getBasePathAndName(const std::string& filepath, - std::string& out_basepath, - std::string& out_name); - -/** - * If path contains duplicated slashes they will be removed - * - * Note this function does not fix slash style '/', '\' - * (Linux/Windows) - * - * Example path: | Result: - * ---------------------------+------------------------------ - * "my/a//b/c/d/e" | "my/a/b/c/d/e" - * "add\ff\\\g" | "add\f\g" - * "first//second\\a\/" | "first/second\a" (mixed / with \) - */ -extern std::string removeDuplicatedSlashesFromPath(const std::string& path); - -/** - * Return true if last character of string is '/' or '\' - */ -extern bool isDirectoryPath(const std::string& path); - -/** - * If path contains trailing '/' or '\' it will be removed. - * - * Example path: | Result: - * ---------------------------+------------------------------ - * "documents/someName/" | "documents/someName" - * "documents/yetAnotherName" | "documents/yetAnotherName" - */ -extern std::string removeTrailingDirectorySlashFromPath(const std::string& path); - -/** - * Returns FILE name without leading base path: - * - * Example path: | Result: - * ---------------------------+------------------------------ - * "documents/ABC/a.txt" | "a.txt" - * "documents/A/X/Y/Z/my.log" | "my.log" - * - * "documents/A/B/C/" | "" (fullpath is directory) - * "a.txt" | "a.txt" - * "A/" | "" (fullpath is directory) - */ -extern std::string stripBasePathFromPath(const std::string& fullpath); - -/** - * Returns path without last directory or file part - * - * Example path: | Result: | Extracted ending: - * ---------------------------+-----------------------+-------------- - * "documents/ABC/a.txt" | "documents/ABC/" | "a.txt" - * "documents/A/X/Y/Z/my.log" | "documents/A/X/Y/Z/" | "my.log" - * - * "documents/A/B/C/" | "documents/A/B/" | "C/" - * "a.txt" | "" | "a.txt" - * "A/" | "" | "A/" - */ -extern std::string getBasePathFromPath(const std::string& fullpath); - -extern std::string getArchiveLogMessage(const int errorCode, const std::string &hint); - -template -void throwArchiveException(const int errorCode, const std::string &hint) -{ - std::string log = getArchiveLogMessage(errorCode, hint); - LOGE("%s", log.c_str()); - throw T(log.c_str()); -} - -} //namespace Archive -} //namespace DeviceAPI - -#endif // __TIZEN_ARCHIVE_ARCHIVE_UTILS_H__ diff --git a/src/archive/old/JSArchiveFile.cpp b/src/archive/old/JSArchiveFile.cpp deleted file mode 100755 index 6ac4e94e..00000000 --- a/src/archive/old/JSArchiveFile.cpp +++ /dev/null @@ -1,535 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "JSArchiveFile.h" -#include "JSArchiveFileEntry.h" -#include "JSFile.h" -#include "ArchiveCallbackData.h" -#include "ArchiveUtils.h" -#include "plugin_config.h" -#include - -namespace DeviceAPI { -namespace Archive { - -using namespace WrtDeviceApis::Commons; -using namespace DeviceAPI::Common; -using namespace DeviceAPI::Filesystem; - -namespace { -const char* ARCHIVE_FILE = "ArchiveFile"; -const char* ARCHIVE_FILE_MODE = "mode"; -const char* ARCHIVE_FILE_DECOMPRESSED_SIZE = "decompressedSize"; -} - -JSClassDefinition JSArchiveFile::m_classInfo = { - 0, // version - kJSClassAttributeNone, // attributes - ARCHIVE_FILE, // class name - NULL, // parent class - m_property, // static values - m_function, // static functions - initialize, // initialize - finalize, // finalize - NULL, // hasProperty - NULL, // getProperty - NULL, // setProperty - NULL, // deleteProperty - NULL, // getPropertyNames - NULL, // callAsFunctionvalidator - NULL, // constructor - NULL, - NULL // convertToType -}; - -const JSClassDefinition* JSArchiveFile::getClassInfo() -{ - return &m_classInfo; -} - -JSStaticFunction JSArchiveFile::m_function[] = { - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, add, kJSPropertyAttributeNone }, - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, extractAll, kJSPropertyAttributeNone }, - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, getEntries, kJSPropertyAttributeNone }, - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, getEntryByName, kJSPropertyAttributeNone }, - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_CLOSE, close, kJSPropertyAttributeNone }, - { 0, 0, 0 } -}; - -JSStaticValue JSArchiveFile::m_property[] = -{ - {ARCHIVE_FILE_MODE, getMode, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - {ARCHIVE_FILE_DECOMPRESSED_SIZE, getDecompressedSize, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - { 0, 0, 0, 0 } -}; - -JSClassRef JSArchiveFile::m_jsClassRef = JSClassCreate(JSArchiveFile::getClassInfo()); - -const DLL_EXPORT JSClassRef JSArchiveFile::getClassRef() -{ - if (!m_jsClassRef) { - m_jsClassRef = JSClassCreate(&m_classInfo); - } - return m_jsClassRef; -} - -void JSArchiveFile::initialize(JSContextRef context, JSObjectRef object) -{ - LOGD("Entered"); -} - -void JSArchiveFile::finalize(JSObjectRef object) -{ - LOGD("Entered"); - ArchiveFileHolder* priv = - static_cast(JSObjectGetPrivate(object)); - if (priv) { - JSObjectSetPrivate(object, NULL); - delete priv; - priv = NULL; - } -} - -ArchiveFilePtr JSArchiveFile::getPrivateObject(JSContextRef context, - JSValueRef value_ref) -{ - if (!JSValueIsObjectOfClass(context, value_ref, getClassRef())) { - LOGE("TypeMismatch"); - throw TypeMismatchException("TypeMismatch"); - } - - JSObjectRef object = JSUtil::JSValueToObject(context, value_ref); - ArchiveFileHolder* priv = static_cast(JSObjectGetPrivate(object)); - if (!priv) { - LOGE("Priv is null"); - throw UnknownException("Priv is null"); - } - - if (!(priv->ptr)) { - LOGE("Native is null"); - throw UnknownException("Native is null"); - } - - return priv->ptr; -} - -JSObjectRef JSArchiveFile::makeJSObject(JSContextRef context, - ArchiveFilePtr native) -{ - if (!native) { - LOGE("Native is null"); - throw TypeMismatchException("Native is null"); - } - - ArchiveFileHolder* priv = new ArchiveFileHolder; - if(!priv){ - LOGE("Priv is null"); - throw UnknownException("Priv is null"); - } - priv->ptr = native; - - JSObjectRef obj = JSObjectMake(context, - getClassRef(), static_cast(priv)); - return obj; -} - -JSValueRef JSArchiveFile::getMode(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - std::string fm_string = fileModeToString(priv->getFileMode()); - return JSUtil::toJSValueRef(context, fm_string); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFile::getDecompressedSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - return JSUtil::toJSValueRef(context, priv->getDecompressedSize()); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFile::add(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - AddProgressCallback *callback = NULL; - - try { - ArchiveFilePtr priv = JSArchiveFile::getPrivateObject(context, thisObject); - ArgumentValidator validator(context, argumentCount, arguments); - - auto g_ctx = GlobalContextManager::getInstance()->getGlobalContext(context); - callback = new(std::nothrow) AddProgressCallback(g_ctx); - if(!callback) { - LOGE("Couldn't allocate AddProgressCallback"); - throw UnknownException("Memory allocation error"); - } - - // set all callbacks - callback->setSuccessCallback(validator.toFunction(1, true)); - callback->setErrorCallback(validator.toFunction(2, true)); - callback->setProgressCallback(validator.toFunction(3, true)); - - // process sourceFile argument (File or path) - if (validator.isOmitted(0)) { - LOGE("FileReference not given"); - throw TypeMismatchException("Missing argument"); - } - FilePtr file_ptr = fileReferenceToFile(context, arguments[0]); - - // prepare empty archive file and assign File pointer - ArchiveFileEntryPtr afep = ArchiveFileEntryPtr( - new ArchiveFileEntry(file_ptr)); - callback->setFileEntry(afep); - - callback->setBasePath(file_ptr->getNode()->getPath()->getPath()); - LOGD("base path:%s base virt:%s", callback->getBasePath().c_str(), - callback->getBaseVirtualPath().c_str()); - - // check and set options - if(!validator.isOmitted(4)){ - if(validator.isUndefined(4)){ - LOGE("Type mismath error"); - throw TypeMismatchException("ArchiveFileEntryOptions is undefined"); - } - LOGD("Processing dictionary"); - JSObjectRef dictionary = validator.toObject(4,true); - JSValueRef dic_destination = JSUtil::getProperty( - context, dictionary, ARCHIVE_FILE_ENTRY_OPT_DEST); - if (!JSValueIsUndefined(context, dic_destination)) { - LOGD("Setting destination path"); - afep->setDestination( - JSUtil::JSValueToString(context, dic_destination)); - } - JSValueRef dic_strip = JSUtil::getProperty( - context, dictionary, ARCHIVE_FILE_ENTRY_OPT_STRIP); - if (!JSValueIsUndefined(context, dic_strip)) { - LOGD("Setting strip option"); - afep->setStriped( - JSUtil::JSValueToBoolean(context, dic_strip)); - } - JSValueRef dic_compression_level = JSUtil::getProperty( - context, dictionary, ARCHIVE_FILE_ENTRY_OPT_COMPRESSION_LEVEL); - if (!JSValueIsUndefined(context, dic_compression_level)) { - LOGD("Setting compression level"); - afep->setCompressionLevel( - JSUtil::JSValueToULong(context, dic_compression_level)); - } - } - - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD)) { - LOGE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - - long op_id = priv->add(callback); - LOGD("Run add request with op_id: %d", op_id); - - return JSUtil::toJSValueRef(context, op_id); - } - catch (const NotFoundException &nfe) { - callback->setError(nfe.getName(), nfe.getMessage()); - } - catch (const IOException &ioe) { - callback->setError(ioe.getName(), ioe.getMessage()); - } - catch (const BasePlatformException &err) { - LOGE("add BasePlarformException caught: name: %s, msg: %s", - err.getName().c_str(), err.getMessage().c_str()); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, err); - } - catch (...) { - LOGE("add fails"); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "add fails"); - } - - if (callback && callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject( - context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - delete callback; - callback = NULL; - } - - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFile::extractAll(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - ExtractAllProgressCallback *callback = NULL; - - try { - ArchiveFilePtr priv = JSArchiveFile::getPrivateObject(context, thisObject); - ArgumentValidator validator(context, argumentCount, arguments); - - auto g_ctx = GlobalContextManager::getInstance()->getGlobalContext(context); - callback = new ExtractAllProgressCallback(g_ctx); - callback->setSuccessCallback(validator.toFunction(1, true)); - callback->setErrorCallback(validator.toFunction(2, true)); - callback->setProgressCallback(validator.toFunction(3, true)); - - // process destinationDirectory (File or path) - if (validator.isOmitted(0)) { - LOGE("FileReference not given"); - throw TypeMismatchException("Missing argument"); - } - FilePtr file_ptr = fileReferenceToFile(context, arguments[0]); - - // prepare empty archive file and assign File pointer - callback->setDirectory(file_ptr); - - // overwrite is optional - if not given use default (false) - bool opt_overwrite = validator.toBool(4, true, false); - callback->setOverwrite(opt_overwrite); - - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL)) { - LOGE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - - long op_id = priv->extractAll(callback); - LOGD("Run extract all request with op_id: %d", op_id); - - return JSUtil::toJSValueRef(context, op_id); - } - catch (const NotFoundException &nfe) { - callback->setError(nfe.getName(), nfe.getMessage()); - } - catch (const IOException &ioe) { - callback->setError(ioe.getName(), ioe.getMessage()); - } - catch (const BasePlatformException &err) { - LOGE("extractAll BasePlarformException caught: name: %s, msg: %s", - err.getName().c_str(), err.getMessage().c_str()); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, err); - } - catch (...) { - LOGE("extractAll fails"); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "extractAll fails"); - } - - if (callback && callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject( - context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - delete callback; - callback = NULL; - } - - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFile::getEntries(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = - ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - GetEntriesCallbackData *callback = NULL; - - try { - ArchiveFilePtr priv = JSArchiveFile::getPrivateObject(context, thisObject); - ArgumentValidator validator(context, argumentCount, arguments); - - callback = new GetEntriesCallbackData( - GlobalContextManager::getInstance()->getGlobalContext(context)); - - callback->setSuccessCallback(validator.toFunction(0)); - callback->setErrorCallback(validator.toFunction(1, true)); - - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES)) { - LOGE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - - long op_id = priv->getEntries(callback); - LOGD("Run get entries request with op_id: %d", op_id); - - return JSUtil::toJSValueRef(context, op_id); - } - catch (const BasePlatformException &err) { - LOGE("getEntries BasePlarformException caught: name: %s, msg: %s", - err.getName().c_str(), err.getMessage().c_str()); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, err); - } - catch (...) { - LOGE("getEntries fails"); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "getEntries fails"); - } -} - -JSValueRef JSArchiveFile::getEntryByName(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = - ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - GetEntryByNameCallbackData *callback = NULL; - - try { - ArchiveFilePtr priv = JSArchiveFile::getPrivateObject(context, thisObject); - ArgumentValidator validator(context, argumentCount, arguments); - - callback = new GetEntryByNameCallbackData( - GlobalContextManager::getInstance()->getGlobalContext(context)); - - callback->setName(validator.toString(0)); - callback->setSuccessCallback(validator.toFunction(1)); - callback->setErrorCallback(validator.toFunction(2, true)); - - if (!priv->isAllowedOperation(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME)) { - LOGE("Not allowed operation"); - throw InvalidAccessException("Not allowed operation"); - } - - long op_id = priv->getEntryByName(callback); - LOGD("Run get entry by name request with op_id: %d", op_id); - - return JSUtil::toJSValueRef(context, op_id); - } - catch (const BasePlatformException &err) { - LOGE("getEntryByName BasePlarformException caught: name: %s, msg: %s", - err.getName().c_str(), err.getMessage().c_str()); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, err); - } - catch (...) { - LOGE("getEntryByName fails"); - delete callback; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "getEntryByName fails"); - } -} - -JSValueRef JSArchiveFile::close(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - try{ - ArchiveFilePtr priv = JSArchiveFile::getPrivateObject(context, thisObject); - - priv->close(); - } - catch (const BasePlatformException &error) { - LOGE("close failed: %s", error.getMessage().c_str()); - return JSWebAPIErrorFactory::postException(context, exception, error); - } - catch (...) { - LOGE("close failed"); - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); - } - - return JSValueMakeUndefined(context); -} - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/JSArchiveFile.h b/src/archive/old/JSArchiveFile.h deleted file mode 100644 index 72bf13a9..00000000 --- a/src/archive/old/JSArchiveFile.h +++ /dev/null @@ -1,121 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#ifndef _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_H_ -#define _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_H_ -#include - -#include "ArchiveFile.h" -#include "plugin_config.h" - -namespace DeviceAPI { -namespace Archive { - - -class JSArchiveFile { -public: - static const JSClassDefinition* getClassInfo(); - static const JSClassRef getClassRef(); - - static ArchiveFilePtr getPrivateObject(JSContextRef context, - JSValueRef value_ref); - - static JSObjectRef makeJSObject(JSContextRef context, - ArchiveFilePtr native); - -private: - - /** - * This member variable contains the values which has to be passed - * when the this class is embedded into JS Engine. - */ - static JSClassDefinition m_classInfo; - - /** - * This structure describes a statically declared function property. - */ - static JSStaticFunction m_function[]; - - /** - * This member variable contains the initialization values - * for the static properties of this class. - * The values are given according to the data structure JSPropertySpec - */ - static JSStaticValue m_property[]; - - static JSClassRef m_jsClassRef; - - /** - * The callback invoked when an object is first created. - */ - static void initialize(JSContextRef context, JSObjectRef object); - - /** - * The callback invoked when an object is finalized. - */ - static void finalize(JSObjectRef object); - - static JSValueRef getMode(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef getDecompressedSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef add(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - - static JSValueRef extractAll(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - - static JSValueRef getEntries(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - - static JSValueRef getEntryByName(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - - static JSValueRef close(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - -}; - -} // Archive -} // DeviceAPI - -#endif // _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_H_ diff --git a/src/archive/old/JSArchiveFileEntry.cpp b/src/archive/old/JSArchiveFileEntry.cpp deleted file mode 100755 index 16976826..00000000 --- a/src/archive/old/JSArchiveFileEntry.cpp +++ /dev/null @@ -1,331 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "ArchiveCallbackData.h" -#include "ArchiveFile.h" -#include "JSArchiveFileEntry.h" -#include "ArchiveUtils.h" -#include "plugin_config.h" - -namespace DeviceAPI { -namespace Archive { - -using namespace WrtDeviceApis::Commons; -using namespace DeviceAPI::Common; -using namespace DeviceAPI::Filesystem; - -namespace { -const char* ARCHIVE_FILE_ENTRY = "ArchiveFileEntry"; -const char* ARCHIVE_FILE_ENTRY_NAME = "name"; -const char* ARCHIVE_FILE_ENTRY_SIZE = "size"; -const char* ARCHIVE_FILE_ENTRY_COMPRESSED_SIZE = "compressedSize"; -const char* ARCHIVE_FILE_ENTRY_MODIFIED = "modified"; -} - -const char* ARCHIVE_FILE_ENTRY_OPT_DEST = "destination"; -const char* ARCHIVE_FILE_ENTRY_OPT_STRIP = "stripSourceDirectory"; -const char* ARCHIVE_FILE_ENTRY_OPT_COMPRESSION_LEVEL = "compressionLevel"; - -struct ArchiveFileEntryHolder{ - ArchiveFileEntryPtr ptr; -}; - -JSClassDefinition JSArchiveFileEntry::m_classInfo = { - 0, // version - kJSClassAttributeNone, // attributes - ARCHIVE_FILE_ENTRY, // class name - NULL, // parent class - m_property, // static values - m_function, // static functions - initialize, // initialize - finalize, // finalize - NULL, // hasProperty - NULL, // getProperty - NULL, // setProperty - NULL, // deleteProperty - NULL, // getPropertyNames - NULL, // callAsFunctionvalidator - NULL, // constructor - NULL, // hasInstance - NULL // convertToType -}; - -const JSClassDefinition* JSArchiveFileEntry::getClassInfo() -{ - return &m_classInfo; -} - -JSStaticFunction JSArchiveFileEntry::m_function[] = { - { ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT, extract, kJSPropertyAttributeNone }, - { 0, 0, 0 } -}; - -JSStaticValue JSArchiveFileEntry::m_property[] = -{ - {ARCHIVE_FILE_ENTRY_NAME, getName, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - {ARCHIVE_FILE_ENTRY_SIZE, getSize, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - {ARCHIVE_FILE_ENTRY_COMPRESSED_SIZE, getCompressedSize, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - {ARCHIVE_FILE_ENTRY_MODIFIED, getModified, NULL, - kJSPropertyAttributeDontDelete | kJSPropertyAttributeReadOnly}, - { 0, 0, 0, 0 } -}; - -JSClassRef JSArchiveFileEntry::m_jsClassRef = JSClassCreate(JSArchiveFileEntry::getClassInfo()); - -const JSClassRef DLL_EXPORT JSArchiveFileEntry::getClassRef() -{ - if (!m_jsClassRef) { - m_jsClassRef = JSClassCreate(&m_classInfo); - } - return m_jsClassRef; -} - -void JSArchiveFileEntry::initialize(JSContextRef context, JSObjectRef object) -{ - LOGD("Entered"); -} - -void JSArchiveFileEntry::finalize(JSObjectRef object) -{ - LOGD("Entered"); - ArchiveFileEntryHolder* priv = - static_cast(JSObjectGetPrivate(object)); - if (priv) { - JSObjectSetPrivate(object, NULL); - delete priv; - priv = NULL; - } -} - -ArchiveFileEntryPtr JSArchiveFileEntry::getPrivateObject(JSContextRef context, - JSValueRef value_ref) -{ - if (!JSValueIsObjectOfClass(context, value_ref, getClassRef())) { - LOGE("TypeMismatch"); - throw TypeMismatchException("TypeMismatch"); - } - - JSObjectRef object = JSUtil::JSValueToObject(context, value_ref); - ArchiveFileEntryHolder* priv = static_cast(JSObjectGetPrivate(object)); - if (!priv) { - LOGE("Priv is null"); - throw UnknownException("Priv is null"); - } - - if (!(priv->ptr)) { - LOGE("Native is null"); - throw UnknownException("Native is null"); - } - - return priv->ptr; -} - -JSObjectRef JSArchiveFileEntry::makeJSObject(JSContextRef context, - ArchiveFileEntryPtr native) -{ - if (!native) { - LOGE("Native is null"); - throw TypeMismatchException("Native is null"); - } - - ArchiveFileEntryHolder* priv = new ArchiveFileEntryHolder; - if(!priv){ - LOGE("Priv is null"); - throw UnknownException("Priv is null"); - } - priv->ptr = native; - - JSObjectRef obj = JSObjectMake(context, - getClassRef(), static_cast(priv)); - return obj; -} - -JSValueRef JSArchiveFileEntry::getName(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - return JSUtil::toJSValueRef(context, priv->getName()); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFileEntry::getSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - return JSUtil::toJSValueRef(context, priv->getSize()); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFileEntry::getCompressedSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - return JSUtil::toJSValueRef(context, priv->getCompressedSize()); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFileEntry::getModified(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception) -{ - LOGD("Entered"); - try { - auto priv = getPrivateObject(context, object); - return JSUtil::makeDateObject(context, priv->getModified()); - } - catch (const BasePlatformException &error) { - LOGE("Attribute get failed: %s", error.getMessage().c_str()); - } - catch (...) { - LOGE("Attribute get failed"); - } - return JSValueMakeUndefined(context); -} - -JSValueRef JSArchiveFileEntry::extract(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = - ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - ExtractEntryProgressCallback *callback = NULL; - - try { - ArchiveFileEntryPtr priv = JSArchiveFileEntry::getPrivateObject(context, thisObject); - ArgumentValidator validator(context, argumentCount, arguments); - - callback = new(std::nothrow) ExtractEntryProgressCallback( - GlobalContextManager::getInstance()->getGlobalContext(context)); - if(!callback) { - LOGD("Couldn't allocate ExtractEntryProgressCallback"); - throw UnknownException("Memory allocation error"); - } - - callback->setSuccessCallback(validator.toFunction(1, true)); - callback->setErrorCallback(validator.toFunction(2, true)); - callback->setProgressCallback(validator.toFunction(3, true)); - callback->setStripName(validator.toBool(4,true)); - callback->setOverwrite(validator.toBool(5,true)); - - if (validator.isOmitted(0)) { - LOGE("FileReference not given"); - throw TypeMismatchException("Missing argument"); - } - - FilePtr file_ptr = fileReferenceToFile(context, arguments[0]); - callback->setDirectory(file_ptr); - - long op_id = priv->extractTo(callback); - LOGD("Run extract request with op_id: %d", op_id); - - return JSUtil::toJSValueRef(context, op_id); - } - catch (const NotFoundException &nfe) { - callback->setError(nfe.getName(), nfe.getMessage()); - } - catch (const IOException &ioe) { - callback->setError(ioe.getName(), ioe.getMessage()); - } - catch (const BasePlatformException &err) { - LOGE("extract caught: name: %s, msg: %s", - err.getName().c_str(), err.getMessage().c_str()); - delete callback; - callback = NULL; - return JSWebAPIErrorFactory::postException(context, exception, err); - } - catch (...) { - LOGE("extract fails"); - delete callback; - callback = NULL; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "extract fails"); - } - - if (callback && callback->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject( - context, - callback->getErrorName(), - callback->getErrorMessage()); - callback->callErrorCallback(errobj); - delete callback; - callback = NULL; - } - - return JSValueMakeUndefined(context); -} - - - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/JSArchiveFileEntry.h b/src/archive/old/JSArchiveFileEntry.h deleted file mode 100644 index c893e4b5..00000000 --- a/src/archive/old/JSArchiveFileEntry.h +++ /dev/null @@ -1,105 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#ifndef _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_ENTRY_H_ -#define _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_ENTRY_H_ -#include - -#include "ArchiveFileEntry.h" - -namespace DeviceAPI { -namespace Archive { - -// these constants are used in JSArchiveFile.cpp and JSArchiveFileEntry.cpp -extern const char* ARCHIVE_FILE_ENTRY_OPT_DEST; -extern const char* ARCHIVE_FILE_ENTRY_OPT_STRIP; -extern const char* ARCHIVE_FILE_ENTRY_OPT_COMPRESSION_LEVEL; - -class JSArchiveFileEntry { -public: - static const JSClassDefinition* getClassInfo(); - static const JSClassRef getClassRef(); - - static ArchiveFileEntryPtr getPrivateObject(JSContextRef context, - JSValueRef velue_ref); - - static JSObjectRef makeJSObject(JSContextRef context, - ArchiveFileEntryPtr native); - -private: - - /** - * This member variable contains the values which has to be passed - * when the this class is embedded into JS Engine. - */ - static JSClassDefinition m_classInfo; - - /** - * This structure describes a statically declared function property. - */ - static JSStaticFunction m_function[]; - - /** - * This member variable contains the initialization values - * for the static properties of this class. - * The values are given according to the data structure JSPropertySpec - */ - static JSStaticValue m_property[]; - - static JSClassRef m_jsClassRef; - - /** - * The callback invoked when an object is first created. - */ - static void initialize(JSContextRef context, JSObjectRef object); - - /** - * The callback invoked when an object is finalized. - */ - static void finalize(JSObjectRef object); - - static JSValueRef getName(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef getSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef getCompressedSize(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef getModified(JSContextRef context, - JSObjectRef object, - JSStringRef propertyName, - JSValueRef* exception); - - static JSValueRef extract(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); -}; - -} // Archive -} // DeviceAPI - -#endif // _TIZEN_ARCHIVE_JS_ARCHIVE_FILE_ENTRY_H_ diff --git a/src/archive/old/JSArchiveManager.cpp b/src/archive/old/JSArchiveManager.cpp deleted file mode 100755 index 7169a6d0..00000000 --- a/src/archive/old/JSArchiveManager.cpp +++ /dev/null @@ -1,295 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "JSArchiveManager.h" -#include "ArchiveManager.h" -#include "ArchiveUtils.h" -#include "plugin_config.h" - -namespace DeviceAPI { -namespace Archive { - -using namespace WrtDeviceApis::Commons; -using namespace DeviceAPI::Common; -using namespace DeviceAPI::Filesystem; - -namespace { -const char* ARCHIVE_MANAGER = "ArchiveManager"; -const char* ARCHIVE_FILE_OPTIONS_OVERWRITE = "overwrite"; -} - -JSClassDefinition JSArchiveManager::m_classInfo = { - 0, // version - kJSClassAttributeNone, // attributes - ARCHIVE_MANAGER, // class name - NULL, // parent class - NULL, // static values - m_function, // static functions - initialize, // initialize - finalize, // finalize - NULL, // hasProperty - NULL, // getProperty - NULL, // setProperty - NULL, // deleteProperty - NULL, // getPropertyNames - NULL, // callAsFunctionvalidator - NULL, // constructor - NULL, // hasInstance - NULL // convertToType -}; - -const JSClassDefinition* JSArchiveManager::getClassInfo() -{ - return &m_classInfo; -} - -JSStaticFunction JSArchiveManager::m_function[] = { - { ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_ABORT, abort, kJSPropertyAttributeNone }, - { ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN, open, kJSPropertyAttributeNone }, - { 0, 0, 0 } -}; - -JSClassRef JSArchiveManager::m_jsClassRef = JSClassCreate(JSArchiveManager::getClassInfo()); - -const JSClassRef DLL_EXPORT JSArchiveManager::getClassRef() -{ - if (!m_jsClassRef) { - m_jsClassRef = JSClassCreate(&m_classInfo); - } - return m_jsClassRef; -} - -void JSArchiveManager::initialize(JSContextRef context, JSObjectRef object) -{ - LOGD("Entered"); -} - -void JSArchiveManager::finalize(JSObjectRef object) -{ - LOGD("Entered"); -} - -JSValueRef JSArchiveManager::open(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - ACE_ACCESS_CHECK( - AceSecurityStatus status = ARCHIVE_CHECK_ACCESS(ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN); - TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); - ); - - OpenCallbackData *open_cb = NULL; - try{ - long op_id = -1; - ArgumentValidator validator(context, argumentCount, arguments); - FilePtr file_ptr; - // process file mode argument (is checked when opening archive) - std::string fm_string = validator.toString(1); - // in case of invalid file mode exception is thrown - FileMode fm = stringToFileMode(fm_string); - - auto g_ctx = GlobalContextManager::getInstance()->getGlobalContext(context); - - // set callbacks - open_cb = new (std::nothrow) OpenCallbackData(g_ctx); - if(!open_cb) { - LOGE("Couldn't allocate OpenCallbackData"); - throw UnknownException("Memory allocation error"); - } - open_cb->setSuccessCallback(validator.toFunction(2)); - open_cb->setErrorCallback(validator.toFunction(3, true)); - - bool overwrite = false; - // check and set options (if given) - if(!validator.isOmitted(4)) { - if(validator.isUndefined(4)) { - LOGE("Type mismath error"); - throw TypeMismatchException("ArchiveFileOptions is undefined"); - } - - LOGD("Processing options dictionary."); - JSObjectRef options = validator.toObject(4, true); - JSValueRef opt_overwrite = JSUtil::getProperty(context, options, - ARCHIVE_FILE_OPTIONS_OVERWRITE); - if (!JSValueIsUndefined(context, opt_overwrite)) { - overwrite = JSUtil::JSValueToBoolean(context, opt_overwrite); - LOGD("Overwrite: %d", overwrite); - - if(FileMode::ADD == fm) { - LOGW("File mode is: \"a\" -> overwrite will be ignored"); - } - } - } - - std::string location_string = validator.toString(0); - std::string location_full_path; - - LOGD("location_string: %s", location_string.c_str()); - - // process file reference - try { - file_ptr = fileReferenceToFile(context, arguments[0]); - const std::string full_path = file_ptr->getNode()->getPath()->getFullPath(); - LOGD("open: %s mode: 0x%x overwrite: %d", full_path.c_str(), fm, overwrite); - - if(FileMode::WRITE == fm || FileMode::READ_WRITE == fm) { - if(overwrite) { - try { - //Store requested full path - location_string = std::string(); // remove "[object File]" - location_full_path = full_path; - - LOGD("Deleting existing file: %s", full_path.c_str()); - file_ptr->getNode()->remove(OPT_RECURSIVE); - file_ptr.reset(); //We need to create new empty file - } catch(...) { - LOGE("Couldn't remove existing file: %s", full_path.c_str()); - throw Common::IOException("Could not remove existing file"); - } - } - else if(FileMode::WRITE == fm) { - LOGE("open: %s with mode: \"w\" file exists and overwrite is FALSE!" - " throwing InvalidModificationException", full_path.c_str()); - throw Common::InvalidModificationException("Zip archive already exists"); - } - } - } catch (const NotFoundException& nfe) { - LOGD("location_string: %s is not file reference", location_string.c_str()); - file_ptr.reset(); - } - - if (!file_ptr) { - NodePtr node_ptr; - - if(FileMode::WRITE == fm || - FileMode::READ_WRITE == fm || - FileMode::ADD == fm) { - - if(location_full_path.empty()) { - location_full_path = External::fromVirtualPath(location_string, g_ctx); - } - LOGD("Archive file not found - trying to create new one at: " - "original: %s full: %s", location_string.c_str(), - location_full_path.c_str()); - - PathPtr path = Path::create(location_full_path); - - std::string parent_path_string = path->getPath(); - PathPtr parent_path = Path::create(parent_path_string); - LOGD("Parent path: %s", parent_path_string.c_str()); - - NodePtr parent_node = Node::resolve(parent_path); - parent_node->setPermissions(PERM_READ | PERM_WRITE); - std::string filename = path->getName(); - LOGD("File name: %s", filename.c_str()); - node_ptr = parent_node->createChild(Path::create(filename), NT_FILE); - } - else { - LOGE("Archive file not found"); - throw Common::NotFoundException("Archive file not found"); - } - file_ptr = FilePtr(new File(node_ptr, File::PermissionList())); - } - - // prepare empty archive file and assign File pointer - ArchiveFilePtr afp = ArchiveFilePtr(new ArchiveFile(fm)); - afp->setFile(file_ptr); - afp->setOverwrite(overwrite); - open_cb->setArchiveFile(afp); - - op_id = ArchiveManager::getInstance().open(open_cb); - return JSUtil::toJSValueRef(context, op_id); - } - catch (const NotFoundException &nfe) { - open_cb->setError(nfe.getName(), nfe.getMessage()); - } - catch (const IOException &ioe) { - open_cb->setError(ioe.getName(), ioe.getMessage()); - } - catch (const BasePlatformException &error) { - LOGE("Open failed: %s", error.getMessage().c_str()); - delete open_cb; - open_cb = NULL; - return JSWebAPIErrorFactory::postException(context, exception, error); - } - catch (...) { - LOGE("Open failed"); - delete open_cb; - open_cb = NULL; - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); - } - - if (open_cb && open_cb->isError()) { - JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(context, - open_cb->getErrorName(), - open_cb->getErrorMessage()); - open_cb->callErrorCallback(errobj); - delete open_cb; - open_cb = NULL; - } - - return JSValueMakeUndefined(context); -} - - -JSValueRef JSArchiveManager::abort(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception) -{ - LOGD("Entered"); - - try{ - ArgumentValidator validator(context, argumentCount, arguments); - long operation_id = validator.toLong(0); - - ArchiveManager::getInstance().abort(operation_id); - } - catch (const BasePlatformException &error) { - LOGE("Abort failed: %s", error.getMessage().c_str()); - return JSWebAPIErrorFactory::postException(context, exception, error); - } - catch (...) { - LOGE("Abort failed"); - return JSWebAPIErrorFactory::postException(context, exception, - JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); - } - - return JSValueMakeUndefined(context); -} - -} // Archive -} // DeviceAPI diff --git a/src/archive/old/JSArchiveManager.h b/src/archive/old/JSArchiveManager.h deleted file mode 100644 index ce0cb70d..00000000 --- a/src/archive/old/JSArchiveManager.h +++ /dev/null @@ -1,72 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#ifndef _TIZEN_ARCHIVE_JS_ARCHIVE_MANAGER_H_ -#define _TIZEN_ARCHIVE_JS_ARCHIVE_MANAGER_H_ -#include - -namespace DeviceAPI { -namespace Archive { - -class JSArchiveManager { -public: - static const JSClassDefinition* getClassInfo(); - static const JSClassRef getClassRef(); - -private: - - /** - * This member variable contains the values which has to be passed - * when the this class is embedded into JS Engine. - */ - static JSClassDefinition m_classInfo; - - /** - * This structure describes a statically declared function property. - */ - static JSStaticFunction m_function[]; - - static JSClassRef m_jsClassRef; - - /** - * The callback invoked when an object is first created. - */ - static void initialize(JSContextRef context, JSObjectRef object); - - /** - * The callback invoked when an object is finalized. - */ - static void finalize(JSObjectRef object); - - static JSValueRef open(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); - - static JSValueRef abort(JSContextRef context, - JSObjectRef object, - JSObjectRef thisObject, - size_t argumentCount, - const JSValueRef arguments[], - JSValueRef* exception); -}; - -} // Archive -} // DeviceAPI - -#endif // _TIZEN_ARCHIVE_JS_ARCHIVE_MANAGER_H_ diff --git a/src/archive/old/UnZip.cpp b/src/archive/old/UnZip.cpp deleted file mode 100644 index 310466ba..00000000 --- a/src/archive/old/UnZip.cpp +++ /dev/null @@ -1,430 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "UnZip.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "ArchiveUtils.h" -#include "UnZipExtractRequest.h" -#include "ArchiveFile.h" - -namespace DeviceAPI { - -using namespace DeviceAPI::Common; - -namespace Archive { - -UnZip::UnZip(const std::string& filename) : - m_zipfile_name(filename), - m_unzip(NULL), - m_default_buffer_size(1024 * 1024) -{ - LOGD("Entered"); - - m_unzip = unzOpen(filename.c_str()); - if(!m_unzip) { - LOGE("unzOpen returned NULL : It means the file is invalid."); - throw InvalidValuesException("Failed to open zip file"); - } - m_is_open = true; -} - -UnZip::~UnZip() -{ - close(); -} - -void UnZip::close() -{ - LOGD("Entered"); - if(!m_is_open) { - LOGD("Unzip already closed - exiting"); - return; - } - - int errclose = unzClose(m_unzip); - m_unzip = NULL; - - if (errclose != UNZ_OK) { - LOGE("ret: %d",errclose); - throwArchiveException(errclose, "unzClose()"); - } - m_is_open = false; -} - -UnZipPtr UnZip::open(const std::string& filename) -{ - LOGD("Entered"); - return UnZipPtr(new UnZip(filename)); -} - -ArchiveFileEntryPtrMapPtr UnZip::listEntries(unsigned long *decompressedSize) -{ - if(!m_is_open) { - LOGE("Failed to get list of entries - UnZip closed"); - throw UnknownException("Failed to get list of files in zip archive"); - } - unz_global_info gi; - int err = unzGetGlobalInfo (m_unzip, &gi); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGetGlobalInfo()"); - } - - char filename_inzip[512]; - unz_file_info file_info; - - ArchiveFileEntryPtrMapPtr map = ArchiveFileEntryPtrMapPtr( - new ArchiveFileEntryPtrMap()); - - unsigned long totalDecompressed = 0; - - err = unzGoToFirstFile(m_unzip); - if (err != UNZ_OK) { - LOGW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); - } - - for (uLong i = 0; i < gi.number_entry; i++) { - - err = unzGetCurrentFileInfo(m_unzip, &file_info, - filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); - if (err != UNZ_OK) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); - } - - LOGD("file: %s | unc size: %d | comp size: %d", filename_inzip, - file_info.uncompressed_size, file_info.compressed_size); - - ArchiveFileEntryPtr entry = ArchiveFileEntryPtr(new ArchiveFileEntry()); - entry->setName(filename_inzip); - entry->setSize(file_info.uncompressed_size); - entry->setCompressedSize(file_info.compressed_size); - - totalDecompressed += file_info.uncompressed_size; - - tm date;// = file_info.tmu_date; - date.tm_sec = file_info.tmu_date.tm_sec; - date.tm_min = file_info.tmu_date.tm_min; - date.tm_hour = file_info.tmu_date.tm_hour; - date.tm_mday = file_info.tmu_date.tm_mday; - date.tm_mon = file_info.tmu_date.tm_mon; - date.tm_year = file_info.tmu_date.tm_year - 1900; - date.tm_wday = 0; - date.tm_yday = 0; - date.tm_isdst = 0; - LOGD("%d, %d, %d, %d, %d, %d", date.tm_hour, date.tm_min, date.tm_sec, date.tm_mday, date.tm_mon, date.tm_year); - entry->setModified(mktime(&date)); - - map->insert(std::make_pair(filename_inzip, entry)); - - if ( (i+1) < gi.number_entry) { - - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); - } - } - } - - (*decompressedSize) = totalDecompressed; - - return map; -} - -void UnZip::extractAllFilesTo(const std::string& extract_path, - ExtractAllProgressCallback* callback) -{ - if(!m_is_open) { - LOGE("Failed to extract files - UnZip closed"); - throw UnknownException("Failed to extract zip archive"); - } - - // - // Calculate number of entries to extract and total number of bytes - // - unz_global_info gi; - updateCallbackWithArchiveStatistics(callback, gi); - - // - // Begin extracting entries - // - int err = unzGoToFirstFile(m_unzip); - if (err != UNZ_OK) { - LOGW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); - } - - for (uLong i = 0; i < gi.number_entry; i++) { - - if (callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - extractCurrentFile(extract_path, std::string(), callback); - - if ((i + 1) < gi.number_entry) { - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); - } - } - } - - callback->callSuccessCallbackOnMainThread(); - callback = NULL; -} - -struct ExtractDataHolder -{ - UnZip* unzip; - ExtractEntryProgressCallback* callback; - std::string root_output_path; -}; - -void UnZip::extractTo(ExtractEntryProgressCallback* callback) -{ - if(!m_is_open) { - LOGE("Extract archive file entry failed - UnZip closed"); - throw UnknownException("Extract archive file entry failed"); - } - - if(!callback) { - LOGE("callback is NULL"); - throw UnknownException("Extract archive file entry failed"); - } - - if(!callback->getArchiveFileEntry()) { - LOGE("callback->getArchiveFileEntry() is NULL"); - throw UnknownException("Extract archive file entry failed"); - } - - Filesystem::FilePtr out_dir = callback->getDirectory(); - if(!out_dir) { - LOGE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); - } - - Filesystem::NodePtr out_node = out_dir->getNode(); - if(!out_node) { - LOGE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); - } - - Filesystem::PathPtr out_path = out_node->getPath(); - if(!out_path) { - LOGE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); - } - - auto entry_name_in_zip = callback->getArchiveFileEntry()->getName(); - auto root_output_path = out_path->getFullPath(); - LOGD("Extract: [%s] to root output directory: [%s] (stripBasePath: [%s])", - entry_name_in_zip.c_str(), - root_output_path.c_str(), - callback->getStripBasePath().c_str()); - - // - // Calculate number of entries to extract and total number of bytes - // - unz_global_info gi; - updateCallbackWithArchiveStatistics(callback, gi, entry_name_in_zip); - - // - // Begin extracting entries - // - - ExtractDataHolder h; - h.unzip = this; - h.callback = callback; - h.root_output_path = root_output_path; - - // this loop call internally progress callbacks - IterateFilesInZip(gi, entry_name_in_zip, callback, extractItFunction, &h); - - // after finish extracting success callback will be called - callback->callSuccessCallbackOnMainThread(); - callback = NULL; -} - -void UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, - void* user_data) -{ - ExtractDataHolder* h = static_cast(user_data); - if(!h) { - LOGE("ExtractDataHolder is NULL!"); - throw UnknownException("Could not list content of zip archive"); - } - - h->unzip->extractCurrentFile(h->root_output_path, - h->callback->getStripBasePath(), - h->callback); -} - -unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, - const std::string& entry_name_in_zip, - OperationCallbackData* callback, - UnZip::IterateFunction itfunc, - void* user_data) -{ - int err = unzGoToFirstFile(m_unzip); - if (UNZ_OK != err) { - LOGW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); - } - - unsigned int num_file_or_folder_matched = 0; - const bool is_directory = isDirectoryPath(entry_name_in_zip); - - unz_file_info cur_file_info; - char tmp_fname[512]; - - for (uLong i = 0; i < gi.number_entry; i++) { - - if (callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - err = unzGetCurrentFileInfo(m_unzip, &cur_file_info, - tmp_fname, sizeof(tmp_fname), NULL, 0, NULL, 0); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); - } - - const std::string cur_filename_in_zip(tmp_fname); - bool match = true; - - if(!entry_name_in_zip.empty()) { - if(is_directory) { - //If entry_name_in_zip is pointing at directory we need to check each entry in - //zip if its path starts with entry_name_in_zip - match = (0 == cur_filename_in_zip.find(entry_name_in_zip)); - } else { - //If entry name points to file we only extract entry with matching name - match = (cur_filename_in_zip == entry_name_in_zip); - } - } - - if(match) { - itfunc(cur_filename_in_zip, cur_file_info, user_data); - ++num_file_or_folder_matched; - } - - if ((i + 1) < gi.number_entry) { - err = unzGoToNextFile(m_unzip); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); - } - } - } - - return num_file_or_folder_matched; -} - -void UnZip::extractCurrentFile(const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) -{ - LOGD("Entered"); - - if (callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - LOGD("extract_path: [%s] base_strip_path: [%s] ", extract_path.c_str(), - base_strip_path.c_str()); - UnZipExtractRequest::execute(*this, extract_path, base_strip_path, callback); -} - -struct ArchiveStatistics -{ - ArchiveStatistics() : uncompressed_size(0), - number_of_files(0), - number_of_folders(0) {} - - unsigned long uncompressed_size; - unsigned long number_of_files; - unsigned long number_of_folders; -}; - -void generateArchiveStatistics(const std::string& file_name, unz_file_info& file_info, - void* user_data) -{ - if(user_data) { - ArchiveStatistics* astats = static_cast(user_data); - astats->uncompressed_size += file_info.uncompressed_size; - - if(isDirectoryPath(file_name)) { - astats->number_of_folders += 1; - } - else { - astats->number_of_files += 1; - } - } -} - -void UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, - unz_global_info& out_global_info, - const std::string optional_filter) -{ - int err = unzGetGlobalInfo(m_unzip, &out_global_info); - if (UNZ_OK != err) { - LOGE("ret: %d",err); - throwArchiveException(err, "unzGetGlobalInfo()"); - } - - ArchiveStatistics astats; - const auto num_matched = IterateFilesInZip(out_global_info, optional_filter, - callback, generateArchiveStatistics, &astats); - if(0 == num_matched) { - LOGE("No matching file/directory: [%s] has been found in zip archive", - optional_filter.c_str()); - LOGE("Throwing NotFoundException - Could not extract file from archive"); - throw NotFoundException("Could not extract file from archive"); - } - - callback->setExpectedDecompressedSize(astats.uncompressed_size); - LOGD("Expected uncompressed size: %s", - bytesToReadableString(astats.uncompressed_size).c_str()); - - callback->setNumberOfFilesToExtract(astats.number_of_files); - LOGD("Number entries to extract: files: %d folders: %d", astats.number_of_files, - astats.number_of_folders); -} - -} //namespace Archive -} //namespace DeviceAPI diff --git a/src/archive/old/UnZip.h b/src/archive/old/UnZip.h deleted file mode 100644 index 508eead1..00000000 --- a/src/archive/old/UnZip.h +++ /dev/null @@ -1,99 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef __TIZEN_ARCHIVE_UNZIP_H__ -#define __TIZEN_ARCHIVE_UNZIP_H__ - -#include -#include -#include - -#include - -#include "ArchiveCallbackData.h" -#include "ArchiveFileEntry.h" - -namespace DeviceAPI { -namespace Archive { - -class UnZipExtractRequest; - -typedef std::shared_ptr> CharVectorPtr; - -class UnZip; -typedef std::shared_ptr UnZipPtr; - -class UnZip -{ -public: - static UnZipPtr open(const std::string& filename); - ~UnZip(); - - ArchiveFileEntryPtrMapPtr listEntries(unsigned long *decompressedSize); - - /** - * \brief Extract all files to output directory - * \param callback which keep pointer to ArchiveFile. - */ - void extractAllFilesTo(const std::string& extract_path, - ExtractAllProgressCallback* callback); - - void extractTo(ExtractEntryProgressCallback* callback); - - void close(); - -private: - UnZip(const std::string& filename); - - /** - * \brief Extract current file (iterated with minizip library) - * \param callback which keep pointer to ArchiveFile. - */ - void extractCurrentFile(const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - - static void extractItFunction(const std::string& file_name, - unz_file_info& file_info, - void* user_data); - - typedef void (*IterateFunction) (const std::string& file_name, - unz_file_info& file_info, - void* user_data); - - unsigned int IterateFilesInZip(unz_global_info& gi, - const std::string& entry_name_in_zip, - OperationCallbackData* callback, - IterateFunction itfunc, - void* user_data); - - void updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, - unz_global_info& out_global_info, - const std::string optional_filter = std::string()); - - std::string m_zipfile_name; - unzFile m_unzip; - size_t m_default_buffer_size; - bool m_is_open; - - friend class UnZipExtractRequest; -}; - -} //namespace Archive -} //namespace DeviceAPI - -#endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/old/UnZipExtractRequest.cpp b/src/archive/old/UnZipExtractRequest.cpp deleted file mode 100644 index 18df81de..00000000 --- a/src/archive/old/UnZipExtractRequest.cpp +++ /dev/null @@ -1,508 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "UnZipExtractRequest.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "ArchiveFile.h" -#include "ArchiveUtils.h" -#include "UnZip.h" - -namespace DeviceAPI { - -using namespace DeviceAPI::Common; - -namespace Archive { - -FilePathStatus getPathStatus(const std::string& path) -{ - if(path.empty()) { - return FPS_NOT_EXIST; - } - - std::string npath = removeTrailingDirectorySlashFromPath(path); - - struct stat sb; - if (stat(npath.c_str(), &sb) == -1) { - return FPS_NOT_EXIST; - } - if(sb.st_mode & S_IFDIR) { - return FPS_DIRECTORY; - } else { - return FPS_FILE; - } -} - -void divideToPathAndName(const std::string& filepath, std::string& out_path, - std::string& out_name) -{ - - size_t pos_last_dir = filepath.find_last_of("/\\"); - if(pos_last_dir == std::string::npos) { - out_path = ""; - out_name = filepath; - } else { - out_path = filepath.substr(0, pos_last_dir+1); - out_name = filepath.substr(pos_last_dir+1); - } -} - -void createMissingDirectories(const std::string& path, bool check_first = true) -{ - if(check_first) { - const FilePathStatus path_status = getPathStatus(path); - //LOGD("[%s] status: %d", path.c_str(), path_status); - if(FPS_DIRECTORY == path_status) { - return; - } - } - - const size_t extract_path_len = path.length(); - for(size_t i = 0; i < extract_path_len; ++i) { - const char& cur = path[i]; - if( (('\\' == cur || '/' == cur) && i > 0) || //handle left side from current / - (extract_path_len-1 == i) ) { //handle last subdirectory path - - const std::string left_part = path.substr(0,i+1); - const FilePathStatus status = getPathStatus(left_part); - //LOGD("left_part: [%s] status:%d", left_part.c_str(), status); - - if(FPS_DIRECTORY != status) { - //TODO investigate 0775 (mode) - Filesystem assumed that file should have parent mode - if(mkdir(left_part.c_str(), 0775) == -1) { - LOGE("Couldn't create new directory: %s errno:%s", - left_part.c_str(), strerror(errno)); - //TODO check why mkdir return -1 but directory is successfully created - // throw UnknownException( - // "Could not create new directory"); - } - } - } - } -} - -void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) -{ - struct utimbuf ut; - struct tm newdate; - newdate.tm_sec = tmu_date.tm_sec; - newdate.tm_min = tmu_date.tm_min; - newdate.tm_hour = tmu_date.tm_hour; - newdate.tm_mday = tmu_date.tm_mday; - newdate.tm_mon = tmu_date.tm_mon; - - if (tmu_date.tm_year > 1900) { - newdate.tm_year = tmu_date.tm_year - 1900; - } else { - newdate.tm_year = tmu_date.tm_year ; - } - newdate.tm_isdst = -1; - - ut.actime = ut.modtime = mktime(&newdate); - if(utime(filepath.c_str(), &ut) == -1) { - LOGE("Couldn't set time for: [%s] errno:%s", filepath.c_str(), strerror(errno)); - } -} - -void UnZipExtractRequest::execute(UnZip& owner, const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) -{ - UnZipExtractRequest req(owner, extract_path, base_strip_path, callback); - req.run(); -} - -UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback) : - - m_owner(owner), - m_extract_path(extract_path), - m_base_strip_path(base_strip_path), - m_callback(callback), - - m_output_file(NULL), - m_buffer(NULL), - m_delete_output_file(false), - m_close_unz_current_file(false), - m_new_dir_status(FPS_NOT_EXIST), - - m_is_directory_entry(false) -{ - if(!m_callback){ - LOGE("Callback is null"); - throw UnknownException("Problem with callback functionality"); - } -} - -void UnZipExtractRequest::run() -{ - LOGD("Entered"); - - getCurrentFileInfo(); - - if(m_is_directory_entry) { - handleDirectoryEntry(); - } else { - handleFileEntry(); - } -} - -UnZipExtractRequest::~UnZipExtractRequest() -{ - if(m_output_file) { - fclose(m_output_file); - m_output_file = NULL; - } - - if(m_delete_output_file && !m_is_directory_entry) { - if(std::remove(m_output_filepath.c_str()) != 0) { - LOGE("Couldn't remove partial file! " - "std::remove(\"%s\") failed with errno:%s", - m_output_filepath.c_str(), strerror(errno)); - } - } - - delete [] m_buffer; - m_buffer = NULL; - - if(m_close_unz_current_file) { - int err = unzCloseCurrentFile (m_owner.m_unzip); - if(UNZ_OK != err) { - LOGW("%s",getArchiveLogMessage(err, "unzCloseCurrentFile()").c_str()); - } - } -} - -void UnZipExtractRequest::getCurrentFileInfo() -{ - LOGD("Entered"); - int err = unzGetCurrentFileInfo(m_owner.m_unzip, &m_file_info, - m_filename_inzip, sizeof(m_filename_inzip), NULL, 0, NULL, 0); - if (err != UNZ_OK) { - LOGE("ret: %d", err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); - } - - LOGD("Input from ZIP: m_filename_inzip: [%s]", m_filename_inzip); - LOGD("m_base_strip_path: [%s]", m_base_strip_path.c_str()); - - std::string file_path = m_filename_inzip; - if(!m_base_strip_path.empty()) { - if(file_path.find(m_base_strip_path) != 0) { - LOGW("m_base_strip_path: [%s] is not begin of m_filename_inzip: [%s]!", - m_base_strip_path.c_str(), - m_filename_inzip); - } - else { - file_path = file_path.substr(m_base_strip_path.length()); - LOGD("Stripped file name: [%s]", file_path.c_str()); - } - } - else { - LOGD("Not stripped file name: [%s]", file_path.c_str()); - } - - m_output_filepath = removeDuplicatedSlashesFromPath(m_extract_path + "/" + file_path); - - LOGD("Packed: [%s], uncompressed_size: %d, will extract to: [%s]", - m_filename_inzip, m_file_info.uncompressed_size, - m_output_filepath.c_str()); - - std::string path, name; - divideToPathAndName(file_path, path, name); - m_new_dir_path = removeDuplicatedSlashesFromPath(m_extract_path + "/" + path); - m_new_dir_status = getPathStatus(m_new_dir_path); - m_is_directory_entry = name.empty(); - - LOGD("New output dir: [%s] status: %d m_is_directory_entry: %d", - m_new_dir_path.c_str(), m_new_dir_status, m_is_directory_entry); - - if(FPS_DIRECTORY != m_new_dir_status) { - - if(m_is_directory_entry) { - - std::string base_directories; - const size_t len = m_new_dir_path.length(); - - for(int i = static_cast(len) - 2; i >= 0; i--) { //skip last \, / - const char& cur = m_new_dir_path[i]; - if('\\' == cur || '/' == cur) { - base_directories = m_new_dir_path.substr(0, static_cast(i)); - break; - } - } - - LOGD("Type: DIRECTORY checking base output directories: [%s]", - base_directories.c_str()); - createMissingDirectories(base_directories, false); - } else { - LOGD("Type: FILE checking output dir: [%s]", m_new_dir_path.c_str()); - createMissingDirectories(m_new_dir_path, false); - } - } -} - -void UnZipExtractRequest::handleDirectoryEntry() -{ - LOGD("Entered"); - if(FPS_DIRECTORY != m_new_dir_status) { - - if(FPS_FILE == m_new_dir_status) { - if(m_callback->getOverwrite()) { //Is a file & overwrite is set: - std::string fn = removeTrailingDirectorySlashFromPath(m_new_dir_path); - if(std::remove(fn.c_str()) != 0) { - LOGE("std::remove(\"%s\") failed with errno:%s", - m_new_dir_path.c_str(), strerror(errno)); - throw UnknownException( - "Could not overwrite file in output directory"); - } - } else { //Is a file & overwrite is not set: - LOGE("Failed to extract directory, " - "file with the same name exists in output directory"); - throw UnknownException("Failed to extract directory, " - "file with the same name exists in output directory"); - } - } - - //Try to create new directory in output directory - if(mkdir(m_new_dir_path.c_str(), 0775) == -1) { - LOGE("Couldn't create new directory: %s errno:%s", - m_new_dir_path.c_str(), strerror(errno)); - throw UnknownException( - "Could not create new directory in extract output directory"); - } - } - - LOGD("Set dir: [%s] access and modify to: %4d-%2d-%2d %2d:%2d:%2d", m_new_dir_path.c_str(), - m_file_info.tmu_date.tm_year, - m_file_info.tmu_date.tm_mon, - m_file_info.tmu_date.tm_mday, - m_file_info.tmu_date.tm_hour, - m_file_info.tmu_date.tm_min, - m_file_info.tmu_date.tm_sec); - - // Directory already exists we only need to update time - changeFileAccessAndModifyDate(m_new_dir_path, m_file_info.tmu_date); - - LOGD("Extracted directory entry: [%s]", m_new_dir_path.c_str()); -} - -bool UnZipExtractRequest::prepareOutputSubdirectory() -{ - LOGD("Entered"); - //This zip entry points to file - verify that parent directory in output dir exists - if(FPS_DIRECTORY != m_new_dir_status) { - if(FPS_FILE == m_new_dir_status) { - LOGE("Path: %s is pointing to file not directory!", - m_new_dir_path.c_str()); - throw UnknownException("Failed to extract file from zip archive, " - "output path is invalid"); - } - - //Try to create new directory in output directory - //TODO investigate 0775 (mode) - Filesystem assumed that file should have parent mode - if(mkdir(m_new_dir_path.c_str(), 0775) == -1) { - LOGW("couldn't create new directory: %s errno:%s", - m_new_dir_path.c_str(), strerror(errno)); - //TODO check why mkdir return -1 but directory is successfully created - // throw UnknownException( - // "Could not create new directory in extract output directory"); - } - } - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - const FilePathStatus output_fstatus = getPathStatus(m_output_filepath); - if(FPS_NOT_EXIST != output_fstatus) { - if(!m_callback->getOverwrite()) { - LOGW("%s exists at output path: [%s], overwrite is set to FALSE", - (FPS_DIRECTORY == output_fstatus ? "Directory" : "File"), - m_output_filepath.c_str()); - - //Just skip this file - TODO: this should be documented in WIDL - return false; - } else { - if(FPS_DIRECTORY == output_fstatus) { - try { - Filesystem::PathPtr path = Filesystem::Path::create(m_output_filepath); - Filesystem::NodePtr node = Filesystem::Node::resolve(path); - node->remove(Filesystem::OPT_RECURSIVE); - LOGD("Removed directory: [%s]", m_output_filepath.c_str()); - } catch(BasePlatformException& ex) { - LOGE("Remove dir: [%s] failed with exception: %s:%s", - m_output_filepath.c_str(), - ex.getName().c_str(), ex.getMessage().c_str()); - throw UnknownException("Could not overwrite existing directory"); - } catch (...) { - LOGE("Remove dir: [%s] failed", m_output_filepath.c_str()); - throw UnknownException("Could not overwrite existing directory"); - } - } //else { - //We will overwrite it with fopen - //} - } - } - - return true; -} - -void UnZipExtractRequest::handleFileEntry() -{ - LOGD("Entered"); - if(!prepareOutputSubdirectory()) { - LOGE("File exists but overwrite is false"); - throw InvalidModificationException("file already exists."); - } - - int err = unzOpenCurrentFilePassword(m_owner.m_unzip, - NULL); //password is not supported yet therefore passing NULL - if (UNZ_OK != err) { - LOGE("ret: %d", err); - throwArchiveException(err, "unzOpenCurrentFilePassword()"); - } - - //We have successfully opened curent file, therefore we should close it later - m_close_unz_current_file = true; - - const size_t buffer_size = m_owner.m_default_buffer_size; - m_buffer = new(std::nothrow) char[buffer_size]; - if(!m_buffer) { - LOGE("Couldn't allocate buffer with size: %s", - bytesToReadableString(buffer_size).c_str()); - throw UnknownException("Memory allocation failed"); - } - - m_output_file = fopen(m_output_filepath.c_str(), "wb"); - if(!m_output_file) { - LOGE("Couldn't open output file: %s", m_output_filepath.c_str()); - throw UnknownException("Could not create extracted file"); - } - m_delete_output_file = true; - - int read_size = 0; - bool marked_as_finished = false; - - LOGD("Started extracting: [%s] uncompressed size: %d - %s", m_filename_inzip, - m_file_info.uncompressed_size, - bytesToReadableString(m_file_info.uncompressed_size).c_str()); - - ExtractAllProgressCallback* extract_callback = NULL; - if(m_callback->getCallbackType() == EXTRACT_ALL_PROGRESS_CALLBACK || - m_callback->getCallbackType() == EXTRACT_ENTRY_PROGRESS_CALLBACK) { - extract_callback = static_cast(m_callback); - extract_callback->startedExtractingFile(m_file_info.uncompressed_size); - } - - ArchiveFileEntryPtrMapPtr entries = m_callback->getArchiveFile()->getEntryMap(); - auto it = entries->find(m_filename_inzip); - if (it == entries->end()) { - LOGE("Entry not found"); - throw Common::NotFoundException("Entry not found"); - } - - while(true) { - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - read_size = unzReadCurrentFile(m_owner.m_unzip, m_buffer, buffer_size); - if (read_size < 0) { - LOGE("unzReadCurrentFile failed with error code:%d for file:%s", read_size, - m_filename_inzip); - throw UnknownException("Failed to extract file from zip archive"); - } - else if(0 == read_size) { - - if(extract_callback) { - if(!marked_as_finished) { - LOGD("NOT marked_as_finished -> increment extracted files counter"); - extract_callback->finishedExtractingFile(); - - //Call progress callback only if we expected empty file - if(m_file_info.uncompressed_size == 0) { - LOGD("Calling progress callback(%f, %s)", - extract_callback->getOverallProgress(), m_filename_inzip); - extract_callback->callProgressCallbackOnMainThread( - extract_callback->getOverallProgress(), it->second); - } - } - } - //Finished writing file, we should not delete extracted file - m_delete_output_file = false; - break; - } - - if (fwrite(m_buffer, read_size, 1, m_output_file) != 1) { - LOGE("Couldn't write extracted data to output file:%s", - m_output_filepath.c_str()); - throw UnknownException("Could not write extract file into output file"); - } - - if(extract_callback) { - extract_callback->extractedPartOfFile(read_size); - LOGD("File: [%s] extracted: %s - %f%%; total progress %f%%", m_filename_inzip, - bytesToReadableString(read_size).c_str(), - 100.0f * extract_callback->getCurrentFileProgress(), - 100.0f * extract_callback->getOverallProgress()); - - // It is better to update number of extracted entries so we will have - // overal progres: 1.0 if all files are extracted - // - if(extract_callback->getCurrentFileProgress() >= 1.0) { - LOGD("Current file: [%s] progress: %f >= 1.0 -> " - "marked_as_finished = true and increment extracted files counter", - m_filename_inzip, extract_callback->getCurrentFileProgress()); - marked_as_finished = true; - extract_callback->finishedExtractingFile(); - } - - LOGD("Calling progress callback(%f, %s)", - extract_callback->getOverallProgress(), m_filename_inzip); - extract_callback->callProgressCallbackOnMainThread( - extract_callback->getOverallProgress(), it->second); - } - } - - if(m_output_file) { - fclose(m_output_file); - m_output_file = NULL; - } - - changeFileAccessAndModifyDate(m_output_filepath, m_file_info.tmu_date); -} - -} //namespace Archive -} //namespace DeviceAPI diff --git a/src/archive/old/UnZipExtractRequest.h b/src/archive/old/UnZipExtractRequest.h deleted file mode 100644 index 49d65618..00000000 --- a/src/archive/old/UnZipExtractRequest.h +++ /dev/null @@ -1,85 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ -#define __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ - -#include -#include -#include "UnZip.h" - -namespace DeviceAPI { -namespace Archive { - -enum FilePathStatus { - FPS_NOT_EXIST = 0, - FPS_FILE = 1, - FPS_DIRECTORY = 2 -}; - -class UnZipExtractRequest -{ -public: - static void execute(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - - ~UnZipExtractRequest(); - -private: - UnZipExtractRequest(UnZip& owner, - const std::string& extract_path, - const std::string& base_strip_path, - BaseProgressCallback* callback); - void run(); - - void getCurrentFileInfo(); - - void handleDirectoryEntry(); - - void handleFileEntry(); - bool prepareOutputSubdirectory(); - - //----------------------------------------------------------------------------- - //Input request variables - UnZip& m_owner; - const std::string m_extract_path; - const std::string m_base_strip_path; - BaseProgressCallback* m_callback; - - //----------------------------------------------------------------------------- - //Working variables - FILE* m_output_file; //Used to write extracted file into output directory - char* m_buffer; //Memory buffer passed between Minizip lib and fwrite function - - bool m_delete_output_file; - bool m_close_unz_current_file; - - unz_file_info m_file_info; //Informations about current archive entry (from minizip) - char m_filename_inzip[512]; //Name of archive file entry (from minizip) - std::string m_output_filepath; //Extracted output file name with full path - - FilePathStatus m_new_dir_status; - bool m_is_directory_entry; //Is this request for directory - std::string m_new_dir_path; -}; - -} //namespace Archive -} //namespace DeviceAPI - -#endif // __TIZEN_ARCHIVE_UNZIP_EXTRACT_REQUEST_H__ diff --git a/src/archive/old/Zip.cpp b/src/archive/old/Zip.cpp deleted file mode 100644 index fd9a6839..00000000 --- a/src/archive/old/Zip.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include "Zip.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "ArchiveFile.h" -#include "ArchiveUtils.h" -#include "crypt.h" - -#include "ZipAddRequest.h" - -namespace DeviceAPI { - -using namespace DeviceAPI::Common; - -namespace Archive { - -void Zip::generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi) -{ - memset(&out_zi, 0, sizeof(zip_fileinfo)); - - time_t tm_t = 0; - if (filename != "-") { - std::string name = filename; - if (name[name.length() - 1] == '/') { - name[name.length() - 1] = '\0'; - } - - struct stat s; - // not all systems allow stat'ing a file with / appended - if (stat(name.c_str(), &s) == 0) { - tm_t = s.st_mtime; - } - } - - struct tm* filedate = localtime(&tm_t); - if(filedate) { - out_zi.tmz_date.tm_sec = filedate->tm_sec; - out_zi.tmz_date.tm_min = filedate->tm_min; - out_zi.tmz_date.tm_hour = filedate->tm_hour; - out_zi.tmz_date.tm_mday = filedate->tm_mday; - out_zi.tmz_date.tm_mon = filedate->tm_mon ; - out_zi.tmz_date.tm_year = filedate->tm_year; - } -} - -Zip::Zip(const std::string& filename, ZipOpenMode open_mode) : - m_zipfile_name(filename), - m_zip(NULL), - m_default_buffer_size(1024 * 1024) -{ - LOGD("Entered"); - - int append_mode = APPEND_STATUS_CREATE; - if(ZOM_CREATEAFTER == open_mode) { - append_mode = APPEND_STATUS_CREATEAFTER; - } else if(ZOM_ADDINZIP == open_mode) { - append_mode = APPEND_STATUS_ADDINZIP; - } - LOGD("append_mode: %d", append_mode); - - m_zip = zipOpen(filename.c_str(), append_mode); - if(!m_zip) { - LOGE("zipOpen returned NULL!"); - throw UnknownException("Opening/creating zip file failed"); - } - m_is_open = true; -} - -Zip::~Zip() -{ - close(); -} - -void Zip::close() -{ - LOGD("Entered"); - if(!m_is_open) { - LOGD("Already closed - exiting."); - return; - } - - int errclose = zipClose(m_zip, NULL); - m_zip = NULL; - - if (errclose != ZIP_OK) { - LOGE("ret: %d", errclose); - throwArchiveException(errclose, "zipClose()"); - } - m_is_open = false; -} - -ZipPtr Zip::createNew(const std::string& filename) -{ - LOGD("Entered"); - return ZipPtr(new Zip(filename, ZOM_CREATE)); -} - -ZipPtr Zip::open(const std::string& filename) -{ - LOGD("Entered"); - return ZipPtr(new Zip(filename, ZOM_ADDINZIP)); -} - -void Zip::addFile(AddProgressCallback*& callback) -{ - LOGD("Entered"); - if(!callback) { - LOGE("callback is NULL!"); - throw UnknownException("Could not add file(-s) to archive"); - } - if(!m_is_open) { - LOGE("Zip file not opened - exiting"); - throw UnknownException("Could not add file(-s) to archive - zip file closed"); - } - - ZipAddRequest::execute(*this, callback); -} - -} //namespace Archive -} //namespace DeviceAPI diff --git a/src/archive/old/Zip.h b/src/archive/old/Zip.h deleted file mode 100644 index 657a9893..00000000 --- a/src/archive/old/Zip.h +++ /dev/null @@ -1,76 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef __TIZEN_ARCHIVE_ZIP_H__ -#define __TIZEN_ARCHIVE_ZIP_H__ - -#include -#include - -#include - -#include "ArchiveCallbackData.h" - -namespace DeviceAPI { -namespace Archive { - - -class ZipAddRequest; - -class Zip; -typedef std::shared_ptr ZipPtr; - -class Zip -{ -public: - static ZipPtr createNew(const std::string& filename); - static ZipPtr open(const std::string& filename); - ~Zip(); - - /** - * When request has finished callback is set to NULL and is - * deleted on main thread after calling all progress callbacks. - * If exception is thrown please delete callback. - */ - void addFile(AddProgressCallback*& callback); - - void close(); - -private: - enum ZipOpenMode { - ZOM_CREATE, - ZOM_CREATEAFTER, - ZOM_ADDINZIP - }; - - Zip(const std::string& filename, ZipOpenMode open_mode); - - static void generateZipFileInfo(const std::string& filename, zip_fileinfo& out_zi); - - std::string m_zipfile_name; - zipFile m_zip; - size_t m_default_buffer_size; - bool m_is_open; - - - friend class ZipAddRequest; -}; - -} //namespace Archive -} //namespace DeviceAPI - -#endif // __TIZEN_ARCHIVE_ZIP_H__ diff --git a/src/archive/old/ZipAddRequest.cpp b/src/archive/old/ZipAddRequest.cpp deleted file mode 100644 index a43352c2..00000000 --- a/src/archive/old/ZipAddRequest.cpp +++ /dev/null @@ -1,529 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#include - -#include "ZipAddRequest.h" - -#include - -#include "ArchiveFile.h" -#include "ArchiveFileEntry.h" -#include "ArchiveUtils.h" - -namespace DeviceAPI { - -using namespace DeviceAPI::Common; - -namespace Archive { - -ZipAddRequest::ZipAddRequest(Zip& owner, AddProgressCallback*& callback) : - m_owner(owner), - m_callback(callback), - m_input_file(NULL), - m_buffer(NULL), - m_buffer_size(m_owner.m_default_buffer_size), - m_files_to_compress(0), - m_bytes_to_compress(0), - m_files_compressed(0), - m_bytes_compressed(0), - m_compression_level(0), - m_new_file_in_zip_opened(false) -{ -} - -ZipAddRequest::~ZipAddRequest() -{ - if(m_input_file) { - fclose(m_input_file); - m_input_file = NULL; - } - - delete [] m_buffer; - m_buffer = NULL; - - - if(m_new_file_in_zip_opened) { - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - } -} - -void ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) -{ - ZipAddRequest req(owner, callback); - req.run(); -} - -void ZipAddRequest::run() -{ - if(!m_callback) { - LOGE("m_callback is NULL"); - throw UnknownException("Could not add file(-s) to archive"); - } - - if(!m_callback->getFileEntry()) { - LOGE("m_callback->getFileEntry() is NULL"); - throw InvalidValuesException("Provided ArchiveFileEntry is not correct"); - } - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - m_compression_level = m_callback->getFileEntry()->getCompressionLevel(); - m_root_src_file = m_callback->getFileEntry()->getFile(); - m_root_src_file_node = m_root_src_file->getNode(); - - //We just need read permission to list files in subdirectories - m_root_src_file_node->setPermissions(Filesystem::PERM_READ); - - std::string src_basepath, src_name; - getBasePathAndName(m_root_src_file_node->getPath()->getFullPath(), src_basepath, - src_name); - - m_absoulte_path_to_extract = src_basepath; - LOGD("m_absoulte_path_to_extract: [%s]", m_absoulte_path_to_extract.c_str()); - - m_destination_path_in_zip = removeDuplicatedSlashesFromPath( - m_callback->getFileEntry()->getDestination()); - - // If we have destination set then we need to create all folders and sub folders - // inside this zip archive. - // - if(m_destination_path_in_zip.length() > 0) { - LOGD("destination is: [%s]", m_destination_path_in_zip.c_str()); - - for(size_t i = 0; i < m_destination_path_in_zip.length(); ++i) { - const char cur_char = m_destination_path_in_zip[i]; - - if( ((cur_char == '/' || cur_char == '\\') && i > 0 ) || - (i == m_destination_path_in_zip.length() - 1)) { - - //Extract left side with '/': - const std::string new_dir = m_destination_path_in_zip.substr(0, i + 1); - - LOGD("Adding empty directory: [%s] to archive", new_dir.c_str()); - addEmptyDirectoryToZipArchive(new_dir); - } - } - } - - // Generate list of files and all subdirectories - // - Filesystem::NodeList all_sub_nodes; - addNodeAndSubdirsToList(m_root_src_file_node, all_sub_nodes); - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - // Calculate total size to be compressed - // - m_bytes_to_compress = 0; - m_files_to_compress = 0; - - int i = 0; - for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { - - unsigned long long size = 0; - if((*it)->getType() == Filesystem::NT_FILE) { - size = (*it)->getSize(); - m_bytes_to_compress += size; - ++m_files_to_compress; - } - - LOGD("[%d] : [%s] --zip--> [%s] | size: %s", i, (*it)->getPath()->getFullPath().c_str(), - getNameInZipArchiveFor(*it, m_callback->getFileEntry()->getStriped()).c_str(), - bytesToReadableString(size).c_str()); - } - - LOGD("m_files_to_compress: %d", m_files_to_compress); - LOGD("m_bytes_to_compress: %llu (%s)", m_bytes_to_compress, - bytesToReadableString(m_bytes_to_compress).c_str()); - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - // Begin files compression - // - for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { - addToZipArchive(*it); - } - - m_callback->callSuccessCallbackOnMainThread(); - m_callback = NULL; -} - -void ZipAddRequest::addNodeAndSubdirsToList(Filesystem::NodePtr src_node, - Filesystem::NodeList& out_list_of_child_nodes) -{ - out_list_of_child_nodes.push_back(src_node); - - if(Filesystem::NT_DIRECTORY == src_node->getType()) { - auto child_nodes = src_node->getChildNodes(); - for(auto it = child_nodes.begin(); it != child_nodes.end(); ++it) { - addNodeAndSubdirsToList(*it, out_list_of_child_nodes); - } - } -} - -void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) -{ - LOGD("Entered name_in_zip:%s", name_in_zip.c_str()); - - if(name_in_zip.length() == 0) { - LOGW("Trying to create directory with empty name - \"\""); - return; - } - - const char last_char = name_in_zip[name_in_zip.length()-1]; - if(last_char != '/' && last_char != '\\') { - name_in_zip += "/"; - LOGD("Corrected name_in_zip: [%s]", name_in_zip.c_str()); - } - - if(m_new_file_in_zip_opened) { - LOGE("WARNING: Previous new file in zip archive is opened!"); - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - } - - bool is_directory = false; - std::string conflicting_name; - - if(m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, - &is_directory, &conflicting_name)) { - - if(!is_directory) { - LOGE("Entry: [%s] exists and is NOT directory!", conflicting_name.c_str()); - - LOGE("Throwing InvalidValuesException - File with the same name exists"); - throw InvalidValuesException("File with the same name exists"); - } - - LOGD("Directory: [%s] already exists -> nothing to do", name_in_zip.c_str()); - return; - } - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - zip_fileinfo new_dir_info; - memset(&new_dir_info, 0, sizeof(zip_fileinfo)); - - // - // Since this directory does not exist we will set current time - // - time_t current_time = time(NULL); - struct tm* current_time_tm = localtime(¤t_time); - if(current_time_tm) { - new_dir_info.tmz_date.tm_sec = current_time_tm->tm_sec; - new_dir_info.tmz_date.tm_min = current_time_tm->tm_min; - new_dir_info.tmz_date.tm_hour = current_time_tm->tm_hour; - new_dir_info.tmz_date.tm_mday = current_time_tm->tm_mday; - new_dir_info.tmz_date.tm_mon = current_time_tm->tm_mon ; - new_dir_info.tmz_date.tm_year = current_time_tm->tm_year; - } - - int err = zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_dir_info, - NULL, 0, NULL, 0, NULL, - (m_compression_level != 0) ? Z_DEFLATED : 0, - m_compression_level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0); - - if (err != ZIP_OK) { - LOGE("ret: %d", err); - throwArchiveException(err, "zipOpenNewFileInZip3()"); - } - - m_new_file_in_zip_opened = true; - - err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - - LOGD("Added new empty directory to archive: [%s]", name_in_zip.c_str()); - m_new_file_in_zip_opened = false; -} - -void ZipAddRequest::addToZipArchive(Filesystem::NodePtr src_file_node) -{ - const std::string name_in_zip = getNameInZipArchiveFor(src_file_node, - m_callback->getFileEntry()->getStriped()); - const std::string src_file_path = src_file_node->getPath()->getFullPath(); - - LOGD("Compress: [%s] to zip archive as: [%s]", src_file_path.c_str(), - name_in_zip.c_str()); - - zip_fileinfo new_file_info; - Zip::generateZipFileInfo(src_file_path, new_file_info); - - if(m_new_file_in_zip_opened) { - LOGE("WARNING: Previous new file in zip archive is opened!"); - int err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - } - - if(m_callback->isCanceled()) { - LOGD("Operation cancelled"); - throw OperationCanceledException(); - } - - std::string conflicting_name; - if(m_callback->getArchiveFile()->isEntryWithNameInArchive(name_in_zip, - NULL, &conflicting_name)) { - - LOGE("Cannot add new entry with name name: [%s] " - "it would conflict with existing entry: [%s]", - name_in_zip.c_str(), conflicting_name.c_str()); - - LOGE("Throwing InvalidModificationException - Archive entry name conflicts"); - throw InvalidModificationException("Archive entry name conflicts"); - } - - int err = zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_file_info, - NULL, 0, NULL, 0, NULL, - (m_compression_level != 0) ? Z_DEFLATED : 0, - m_compression_level, 0, - -MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, - NULL, 0); - - if (err != ZIP_OK) { - LOGE("ret: %d", err); - throwArchiveException(err, "zipOpenNewFileInZip3()"); - } - - m_new_file_in_zip_opened = true; - - if(m_input_file) { - LOGW("WARNING: Previous m_input_file has not been closed"); - fclose(m_input_file); - m_input_file = NULL; - } - - Filesystem::File::PermissionList perm_list; - Filesystem::FilePtr cur_file(new Filesystem::File(src_file_node, perm_list)); - ArchiveFileEntryPtr cur_afentry(new ArchiveFileEntry(cur_file)); - cur_afentry->setCompressionLevel(m_compression_level); - cur_afentry->setName(name_in_zip); - cur_afentry->setModified(src_file_node->getModified()); - - auto entry = m_callback->getFileEntry(); - cur_afentry->setDestination(entry->getDestination()); - cur_afentry->setStriped(entry->getStriped()); - cur_afentry->setSize(0); - - LOGD("m_bytes_compressed:%llu / m_bytes_to_compress: %llu", - m_bytes_compressed, m_bytes_to_compress); - - LOGD("m_files_compressed:%d / m_files_to_compress: %d", - m_files_compressed, m_files_to_compress); - - if(src_file_node->getType() == Filesystem::NT_FILE) { - m_input_file = fopen(src_file_path.c_str(), "rb"); - if (!m_input_file) { - LOGE("Error opening source file:%s", src_file_path.c_str()); - throw UnknownException("Could not open file to be added"); - } - - //Get file length - fseek(m_input_file, 0, SEEK_END); - const size_t in_file_size = ftell(m_input_file); - fseek(m_input_file, 0, SEEK_SET); - LOGD("Source file: [%s] size: %d - %s", src_file_path.c_str(), - in_file_size, - bytesToReadableString(in_file_size).c_str()); - - cur_afentry->setSize(in_file_size); - - if(!m_buffer) { - m_buffer = new(std::nothrow) char[m_buffer_size]; - if(!m_buffer) { - LOGE("Couldn't allocate m_buffer"); - throw UnknownException("Memory allocation error"); - } - } - - size_t total_bytes_read = 0; - size_t size_read = 0; - - do { - size_read = fread(m_buffer, 1, m_buffer_size, m_input_file); - if (size_read < m_buffer_size && - feof(m_input_file) == 0) { - LOGE("Error reading source file: %s\n", src_file_path.c_str()); - throw UnknownException("New file addition failed"); - } - - LOGD("Read: %d bytes from input file:[%s]", size_read, - src_file_path.c_str()); - total_bytes_read += size_read; - m_bytes_compressed += size_read; - - if (size_read > 0) { - err = zipWriteInFileInZip (m_owner.m_zip, m_buffer, size_read); - if (err < 0) { - LOGE("Error during adding file: %s into zip archive", - src_file_path.c_str()); - throw UnknownException("New file addition failed"); - } - } - - if(total_bytes_read == in_file_size) { - LOGD("Finished reading and compressing source file: [%s]", - src_file_path.c_str()); - ++m_files_compressed; - } - - LOGD("Callculatting overall progress: %llu/%llu bytes; " - "%d/%d files; current file: [%s] progress: %d/%d bytes; ", - m_bytes_compressed, m_bytes_to_compress, - m_files_compressed, m_files_to_compress, - src_file_path.c_str(), - total_bytes_read, in_file_size); - - double progress = 1.0; - if(m_bytes_to_compress > 0 || m_files_to_compress > 0) { - progress = static_cast(m_bytes_compressed + m_files_compressed) / - static_cast(m_bytes_to_compress + m_files_to_compress); - } - - LOGD("Wrote: %s total progress: %.2f%% %d/%d files", - bytesToReadableString(size_read).c_str(), progress * 100.0, - m_files_compressed, m_files_to_compress); - - LOGD("Calling add onprogress callback(%f, %s)", progress, - name_in_zip.c_str()); - m_callback->callProgressCallbackOnMainThread(progress, cur_afentry); - - } while (size_read > 0 && total_bytes_read < in_file_size); - - if(in_file_size != total_bytes_read) { - LOGE("in_file_size(%d) != total_bytes_read(%d)", in_file_size, - total_bytes_read); - throw UnknownException("Could not add file to archive"); - } - - fclose(m_input_file); - m_input_file = NULL; - } - - err = zipCloseFileInZip(m_owner.m_zip); - if (ZIP_OK != err) { - LOGE("%s",getArchiveLogMessage(err, "zipCloseFileInZip()").c_str()); - } - - m_new_file_in_zip_opened = false; -} - -std::string removeDirCharsFromFront(const std::string& path) -{ - for(size_t i = 0; i < path.length(); ++i) { - const char& cur = path[i]; - if(cur != '/' && cur != '\\') { - return path.substr(i); - } - } - - return std::string(); //in case path contained only slashes -} - -std::string generateFullPathForZip(const std::string& path) -{ - //Step 1: Remove / from begining - const size_t path_len = path.length(); - - size_t start_i = 0; - for(size_t i = 0; i < path_len; ++i) { - const char& cur = path[i]; - if(cur != '/' && cur != '\\') { - start_i = i; - break; - } - } - - std::string out; - out.reserve(path_len); - - //Step 1: Remove duplicated / characters - bool prev_is_dir = false; - for(size_t i = start_i; i < path_len; ++i) { - const char& cur = path[i]; - if(cur == '/' || cur == '\\') { - if(!prev_is_dir) { - out += cur; - } - prev_is_dir = true; - } else { - prev_is_dir = false; - out += cur; - } - } - - return out; -} - -std::string ZipAddRequest::getNameInZipArchiveFor(Filesystem::NodePtr node, bool strip) -{ - const std::string node_full_path = node->getPath()->getFullPath(); - std::string cut_path; - - const size_t pos = node_full_path.find(m_absoulte_path_to_extract); - if(std::string::npos == pos) { - LOGW("node: [%s] is not containing m_absoulte_path_to_extract: [%s]!", - node_full_path.c_str(), - m_absoulte_path_to_extract.c_str()); - } - - cut_path = node_full_path.substr(pos+m_absoulte_path_to_extract.length()); - LOGD("node_full_path:%s cut_path: %s", node_full_path.c_str(), cut_path.c_str()); - - if(!strip) { - cut_path = m_callback->getBaseVirtualPath() + "/" + cut_path; - LOGD("nonstripped cut_path: %s", cut_path.c_str()); - } - - std::string name = generateFullPathForZip(m_destination_path_in_zip + "/" + cut_path); - if(node->getType() == Filesystem::NT_DIRECTORY) { - if(name.length() > 0 - && name[name.length()-1] != '/' - && name[name.length()-1] != '\\') { - name += "/"; - LOGD("Directory: [%s] added \\", name.c_str()); - } - } - - return name; -} - -} //namespace Archive -} //namespace DeviceAPI diff --git a/src/archive/old/ZipAddRequest.h b/src/archive/old/ZipAddRequest.h deleted file mode 100644 index a40db2d9..00000000 --- a/src/archive/old/ZipAddRequest.h +++ /dev/null @@ -1,88 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__ -#define __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__ - -#include -#include - -#include -#include -#include - -#include "ArchiveCallbackData.h" -#include "Zip.h" - -namespace DeviceAPI { -namespace Archive { - -class ZipAddRequest -{ -public: - - /** - * When request has finished callback is set to NULL and is - * deleted on main thread after calling all progress callbacks. - * If exception is thrown please delete callback. - */ - static void execute(Zip& owner, AddProgressCallback*& callback); - ~ZipAddRequest(); - -private: - ZipAddRequest(Zip& owner, AddProgressCallback*& callback); - void run(); - - void addNodeAndSubdirsToList(Filesystem::NodePtr src_node, - Filesystem::NodeList& out_list_of_child_nodes); - - void addEmptyDirectoryToZipArchive(std::string name_in_zip); - void addToZipArchive(Filesystem::NodePtr src_file_node); - - std::string getNameInZipArchiveFor(Filesystem::NodePtr node, bool strip); - - //----------------------------------------------------------------------------- - //Input request variables - Zip& m_owner; - AddProgressCallback* m_callback; - - - FILE* m_input_file; - char* m_buffer; - size_t m_buffer_size; - - - unsigned long m_files_to_compress; - unsigned long long m_bytes_to_compress; - - unsigned long m_files_compressed; - unsigned long long m_bytes_compressed; - - Filesystem::FilePtr m_root_src_file; - Filesystem::NodePtr m_root_src_file_node; - std::string m_absoulte_path_to_extract; - std::string m_destination_path_in_zip; - - unsigned int m_compression_level; - - bool m_new_file_in_zip_opened; -}; - -} //namespace Archive -} //namespace DeviceAPI - -#endif // __TIZEN_ARCHIVE_ZIP_ADD_REQUEST_H__ diff --git a/src/archive/old/plugin_config.cpp b/src/archive/old/plugin_config.cpp deleted file mode 100755 index 18647b08..00000000 --- a/src/archive/old/plugin_config.cpp +++ /dev/null @@ -1,144 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include -#include - -#include "plugin_config.h" - -using namespace WrtDeviceApis::Commons; - -namespace DeviceAPI { -namespace Archive { - -namespace{ -const char* ARCHIVE_FEATURE_API_WRITE = "http://tizen.org/privilege/filesystem.write"; -const char* ARCHIVE_FEATURE_API_READ = "http://tizen.org/privilege/filesystem.read"; - -const char* ARCHIVE_DEVICE_CAP_WRITE = "filesystem.write"; -const char* ARCHIVE_DEVICE_CAP_READ = "filesystem.read"; -} - -static FunctionMapping createArchiveFunctions(); - -static FunctionMapping ArchiveFunctions = createArchiveFunctions(); - -#pragma GCC visibility push(default) -DEFINE_FUNCTION_GETTER(Archive, ArchiveFunctions); -#pragma GCC visibility pop - -static FunctionMapping createArchiveFunctions() -{ - /** - * Device capabilities - */ - ACE_CREATE_DEVICE_CAP(DEVICE_CAP_ARCHIVE_WRITE, ARCHIVE_DEVICE_CAP_WRITE); - ACE_CREATE_DEVICE_CAP(DEVICE_CAP_ARCHIVE_READ, ARCHIVE_DEVICE_CAP_READ); - - ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_ARCHIVE_WRITE); - ACE_ADD_DEVICE_CAP(DEVICE_LIST_ARCHIVE_WRITE, DEVICE_CAP_ARCHIVE_WRITE); - - ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_ARCHIVE_READ); - ACE_ADD_DEVICE_CAP(DEVICE_LIST_ARCHIVE_READ, DEVICE_CAP_ARCHIVE_READ); - - /** - * Api Features - */ - ACE_CREATE_FEATURE(FEATURE_ARCHIVE_READ, ARCHIVE_FEATURE_API_READ); - ACE_CREATE_FEATURE(FEATURE_ARCHIVE_WRITE, ARCHIVE_FEATURE_API_WRITE); - - ACE_CREATE_FEATURE_LIST(ARCHIVE_FEATURES_READ); - ACE_ADD_API_FEATURE(ARCHIVE_FEATURES_READ, FEATURE_ARCHIVE_READ); - - ACE_CREATE_FEATURE_LIST(ARCHIVE_FEATURES_WRITE); - ACE_ADD_API_FEATURE(ARCHIVE_FEATURES_WRITE, FEATURE_ARCHIVE_WRITE); - - /** - * Functions - */ - FunctionMapping archiveMapping; - - // open - AceFunction archiveFileOpenFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_OPEN, - ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN, - ARCHIVE_FEATURES_WRITE, - DEVICE_LIST_ARCHIVE_WRITE); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN, - archiveFileOpenFunc)); - - // add - AceFunction archiveFileAddFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_ADD, - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, - ARCHIVE_FEATURES_WRITE, - DEVICE_LIST_ARCHIVE_WRITE); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD, - archiveFileAddFunc)); - - // extractAll - AceFunction archiveFileExtractAllFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_EXTRACT_ALL, - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, - ARCHIVE_FEATURES_WRITE, - DEVICE_LIST_ARCHIVE_WRITE); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL, - archiveFileExtractAllFunc)); - - // getEntries - AceFunction archiveFileGetEntriesFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_GET_ENTRIES, - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, - ARCHIVE_FEATURES_READ, - DEVICE_LIST_ARCHIVE_READ); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES, - archiveFileGetEntriesFunc)); - - // getEntryByName - AceFunction archiveFileGetEntryByNameFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_GET_ENTRY_BY_NAME, - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, - ARCHIVE_FEATURES_READ, - DEVICE_LIST_ARCHIVE_READ); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME, - archiveFileGetEntryByNameFunc)); - - // extract - AceFunction archiveFileEntryExtractFunc = ACE_CREATE_FUNCTION( - FUNCTION_ARCHIVE_FILE_ENTRY_EXTRACT, - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT, - ARCHIVE_FEATURES_WRITE, - DEVICE_LIST_ARCHIVE_WRITE); - - archiveMapping.insert(std::make_pair( - ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT, - archiveFileEntryExtractFunc)); - - return archiveMapping; -} - -} -} diff --git a/src/archive/old/plugin_config.h b/src/archive/old/plugin_config.h deleted file mode 100755 index b1dc7d8f..00000000 --- a/src/archive/old/plugin_config.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - - -#ifndef _ARCHIVE_PLUGIN_CONFIG_H_ -#define _ARCHIVE_PLUGIN_CONFIG_H_ - -#include -#include - -#include "plugin_config_impl.h" - -namespace DeviceAPI { -namespace Archive { - -DECLARE_FUNCTION_GETTER(Archive); - -#define ARCHIVE_CHECK_ACCESS(functionName) \ - aceCheckAccess >( \ - getArchiveFunctionData, \ - functionName) - -} // Archive -} // DeviceAPI - -#endif // _ARCHIVE_PLUGIN_CONFIG_H_ diff --git a/src/archive/old/plugin_config_impl.h b/src/archive/old/plugin_config_impl.h deleted file mode 100755 index 8ac0abeb..00000000 --- a/src/archive/old/plugin_config_impl.h +++ /dev/null @@ -1,36 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -#ifndef _ARCHIVE_PLUGIN_CONFIG_IMPL_H_ -#define _ARCHIVE_PLUGIN_CONFIG_IMPL_H_ - -#define TIZEN_ARCHIVE_ARCHIVE_CLASS "archive" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_ABORT "abort" -#define ARCHIVE_FUNCTION_API_ARCHIVE_MANAGER_OPEN "open" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ADD "add" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_EXTRACT_ALL "extractAll" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRIES "getEntries" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_GET_ENTRY_BY_NAME "getEntryByName" -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_CLOSE "close" - -#define ARCHIVE_FUNCTION_API_ARCHIVE_FILE_ENTRY_EXTRACT "extract" - - - -#endif // _ARCHIVE_PLUGIN_CONFIG_IMPL_H_ diff --git a/src/archive/old/plugin_initializer.cpp b/src/archive/old/plugin_initializer.cpp deleted file mode 100644 index c289411e..00000000 --- a/src/archive/old/plugin_initializer.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// -// Tizen Web Device API -// Copyright (c) 2014 Samsung Electronics Co., Ltd. -// -// Licensed under the Apache License, Version 2.0 (the License); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -#include -#include -#include -#include - -#include "JSArchiveManager.h" -#include "JSArchiveFile.h" -#include "JSArchiveFileEntry.h" -#include "plugin_config.h" - -namespace DeviceAPI { -namespace Archive { - -using namespace DeviceAPI::Common; -using namespace WrtDeviceApis::Commons; - -namespace Options{ -class_definition_options_t ArchiveOptions = { - JS_CLASS, - CREATE_INSTANCE, - NONE_NOTICE, - USE_OVERLAYED, - NULL, - NULL, - NULL -}; -} - -void on_widget_start_callback(int widget_id) -{ - LOGD("[TIZEN\\Archive] on_widget_start_callback (%d)", widget_id); - try { - WrtAccessSingleton::Instance().initialize(widget_id); - } - catch (...) { - LOGE("WrtAccess initialization failed"); - } -} - -void on_widget_stop_callback(int widget_id) -{ - LOGD("[TIZEN\\Archive ] on_widget_stop_callback (%d)", widget_id); - try { - WrtAccessSingleton::Instance().deinitialize(widget_id); - } - catch (...) { - LOGE("WrtAccess deinitialization failed"); - } -} - -void on_frame_load_callback(const void* context) -{ - LOGD("[Tizen\\Archive] on_frame_unload_callback ( %p )", context); - GlobalContextManager::getInstance()->addGlobalContext(static_cast(context)); -} - -void on_frame_unload_callback(const void* context) -{ - LOGD("[Tizen\\Archive] on_frame_unload_callback ( %p )", context); - GlobalContextManager::getInstance()->removeGlobalContext(static_cast(context)); -} - -PLUGIN_ON_WIDGET_START(on_widget_start_callback) -PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) - -PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) -PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) - -PLUGIN_CLASS_MAP_BEGIN -PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, - TIZEN_ARCHIVE_ARCHIVE_CLASS, - (js_class_template_getter)JSArchiveManager::getClassRef, - &Options::ArchiveOptions) -PLUGIN_CLASS_MAP_END - -} -} - diff --git a/src/archive/un_zip.cc b/src/archive/un_zip.cc index ec74c484..49404848 100644 --- a/src/archive/un_zip.cc +++ b/src/archive/un_zip.cc @@ -46,11 +46,6 @@ UnZip::UnZip(const std::string& filename) : LoggerD("Entered"); m_unzip = unzOpen(filename.c_str()); - if(!m_unzip) { - LoggerE("unzOpen returned NULL : It means the file is invalid."); - throw InvalidValuesException("Failed to open zip file"); - } - m_is_open = true; } UnZip::~UnZip() @@ -58,12 +53,12 @@ UnZip::~UnZip() close(); } -void UnZip::close() +PlatformResult UnZip::close() { LoggerD("Entered"); if(!m_is_open) { LoggerD("Unzip already closed - exiting"); - return; + return PlatformResult(ErrorCode::NO_ERROR); } int errclose = unzClose(m_unzip); @@ -71,35 +66,43 @@ void UnZip::close() if (errclose != UNZ_OK) { LoggerE("ret: %d",errclose); - throwArchiveException(errclose, "unzClose()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "unzClose()")); } m_is_open = false; + return PlatformResult(ErrorCode::NO_ERROR); } -UnZipPtr UnZip::open(const std::string& filename) +PlatformResult UnZip::open(const std::string& filename, UnZipPtr* out_unzip) { LoggerD("Entered"); - return UnZipPtr(new UnZip(filename)); + UnZipPtr unzip = UnZipPtr(new UnZip(filename)); + + if(!unzip->m_unzip) { + LoggerE("unzOpen returned NULL : It means the file is invalid."); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Failed to open zip file"); + } + unzip->m_is_open = true; + *out_unzip = unzip; + return PlatformResult(ErrorCode::NO_ERROR); } -ArchiveFileEntryPtrMapPtr UnZip::listEntries(unsigned long *decompressedSize) +PlatformResult UnZip::listEntries(unsigned long *decompressedSize, ArchiveFileEntryPtrMapPtr* out_map) { if(!m_is_open) { LoggerE("Failed to get list of entries - UnZip closed"); - throw UnknownException("Failed to get list of files in zip archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to get list of files in zip archive"); } unz_global_info gi; int err = unzGetGlobalInfo (m_unzip, &gi); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGetGlobalInfo()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetGlobalInfo()")); } char filename_inzip[512]; unz_file_info file_info; - ArchiveFileEntryPtrMapPtr map = ArchiveFileEntryPtrMapPtr( - new ArchiveFileEntryPtrMap()); + ArchiveFileEntryPtrMapPtr map = ArchiveFileEntryPtrMapPtr(new ArchiveFileEntryPtrMap()); unsigned long totalDecompressed = 0; @@ -114,7 +117,7 @@ ArchiveFileEntryPtrMapPtr UnZip::listEntries(unsigned long *decompressedSize) filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()")); } LoggerD("file: %s | unc size: %d | comp size: %d", filename_inzip, @@ -147,29 +150,34 @@ ArchiveFileEntryPtrMapPtr UnZip::listEntries(unsigned long *decompressedSize) err = unzGoToNextFile(m_unzip); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()")); } } } (*decompressedSize) = totalDecompressed; - return map; + *out_map = map; + + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZip::extractAllFilesTo(const std::string& extract_path, - ExtractAllProgressCallback* callback) +PlatformResult UnZip::extractAllFilesTo(const std::string& extract_path, + ExtractAllProgressCallback* callback) { if(!m_is_open) { LoggerE("Failed to extract files - UnZip closed"); - throw UnknownException("Failed to extract zip archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to extract zip archive"); } // // Calculate number of entries to extract and total number of bytes // unz_global_info gi; - updateCallbackWithArchiveStatistics(callback, gi); + PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } // // Begin extracting entries @@ -183,22 +191,27 @@ void UnZip::extractAllFilesTo(const std::string& extract_path, if (callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } - extractCurrentFile(extract_path, std::string(), callback); + result = extractCurrentFile(extract_path, std::string(), callback); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } if ((i + 1) < gi.number_entry) { err = unzGoToNextFile(m_unzip); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()")); } } } callback->callSuccessCallbackOnMainThread(); callback = NULL; + + return PlatformResult(ErrorCode::NO_ERROR); } struct ExtractDataHolder @@ -208,39 +221,39 @@ struct ExtractDataHolder std::string root_output_path; }; -void UnZip::extractTo(ExtractEntryProgressCallback* callback) +PlatformResult UnZip::extractTo(ExtractEntryProgressCallback* callback) { if(!m_is_open) { LoggerE("Extract archive file entry failed - UnZip closed"); - throw UnknownException("Extract archive file entry failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); } if(!callback) { LoggerE("callback is NULL"); - throw UnknownException("Extract archive file entry failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); } if(!callback->getArchiveFileEntry()) { LoggerE("callback->getArchiveFileEntry() is NULL"); - throw UnknownException("Extract archive file entry failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Extract archive file entry failed"); } filesystem::FilePtr out_dir = callback->getDirectory(); if(!out_dir) { LoggerE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); } NodePtr out_node = out_dir->getNode(); if(!out_node) { LoggerE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); } PathPtr out_path = out_node->getPath(); if(!out_path) { LoggerE("Output directory is not valid"); - throw InvalidValuesException("Output directory is not correct"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Output directory is not correct"); } auto entry_name_in_zip = callback->getArchiveFileEntry()->getName(); @@ -255,7 +268,10 @@ void UnZip::extractTo(ExtractEntryProgressCallback* callback) // Calculate number of entries to extract and total number of bytes // unz_global_info gi; - updateCallbackWithArchiveStatistics(callback, gi, entry_name_in_zip); + PlatformResult result = updateCallbackWithArchiveStatistics(callback, gi, entry_name_in_zip); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } // // Begin extracting entries @@ -267,31 +283,43 @@ void UnZip::extractTo(ExtractEntryProgressCallback* callback) h.root_output_path = root_output_path; // this loop call internally progress callbacks - IterateFilesInZip(gi, entry_name_in_zip, callback, extractItFunction, &h); + unsigned int matched; + result = IterateFilesInZip(gi, entry_name_in_zip, callback, extractItFunction, matched, &h); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } // after finish extracting success callback will be called callback->callSuccessCallbackOnMainThread(); callback = NULL; + + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, - void* user_data) +PlatformResult UnZip::extractItFunction(const std::string& file_name, unz_file_info& file_info, + void* user_data) { ExtractDataHolder* h = static_cast(user_data); if(!h) { LoggerE("ExtractDataHolder is NULL!"); - throw UnknownException("Could not list content of zip archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not list content of zip archive"); + } + + PlatformResult result = h->unzip->extractCurrentFile(h->root_output_path, + h->callback->getStripBasePath(), + h->callback); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; } - h->unzip->extractCurrentFile(h->root_output_path, - h->callback->getStripBasePath(), - h->callback); + return PlatformResult(ErrorCode::NO_ERROR); } -unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, +PlatformResult UnZip::IterateFilesInZip(unz_global_info& gi, const std::string& entry_name_in_zip, OperationCallbackData* callback, UnZip::IterateFunction itfunc, + unsigned int& num_file_or_folder_matched, void* user_data) { int err = unzGoToFirstFile(m_unzip); @@ -299,7 +327,7 @@ unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, LoggerW("%s",getArchiveLogMessage(err, "unzGoToFirstFile()").c_str()); } - unsigned int num_file_or_folder_matched = 0; + num_file_or_folder_matched = 0; const bool is_directory = isDirectoryPath(entry_name_in_zip); unz_file_info cur_file_info; @@ -309,14 +337,14 @@ unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, if (callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } err = unzGetCurrentFileInfo(m_unzip, &cur_file_info, tmp_fname, sizeof(tmp_fname), NULL, 0, NULL, 0); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()")); } const std::string cur_filename_in_zip(tmp_fname); @@ -334,7 +362,10 @@ unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, } if(match) { - itfunc(cur_filename_in_zip, cur_file_info, user_data); + PlatformResult result = itfunc(cur_filename_in_zip, cur_file_info, user_data); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } ++num_file_or_folder_matched; } @@ -342,15 +373,15 @@ unsigned int UnZip::IterateFilesInZip(unz_global_info& gi, err = unzGoToNextFile(m_unzip); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGoToNextFile()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGoToNextFile()")); } } } - return num_file_or_folder_matched; + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZip::extractCurrentFile(const std::string& extract_path, +PlatformResult UnZip::extractCurrentFile(const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback) { @@ -358,12 +389,12 @@ void UnZip::extractCurrentFile(const std::string& extract_path, if (callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } LoggerD("extract_path: [%s] base_strip_path: [%s] ", extract_path.c_str(), base_strip_path.c_str()); - UnZipExtractRequest::execute(*this, extract_path, base_strip_path, callback); + return UnZipExtractRequest::execute(*this, extract_path, base_strip_path, callback); } struct ArchiveStatistics @@ -377,7 +408,7 @@ struct ArchiveStatistics unsigned long number_of_folders; }; -void generateArchiveStatistics(const std::string& file_name, unz_file_info& file_info, +PlatformResult generateArchiveStatistics(const std::string& file_name, unz_file_info& file_info, void* user_data) { if(user_data) { @@ -391,26 +422,32 @@ void generateArchiveStatistics(const std::string& file_name, unz_file_info& file astats->number_of_files += 1; } } + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, +PlatformResult UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, unz_global_info& out_global_info, const std::string optional_filter) { int err = unzGetGlobalInfo(m_unzip, &out_global_info); if (UNZ_OK != err) { LoggerE("ret: %d",err); - throwArchiveException(err, "unzGetGlobalInfo()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetGlobalInfo()")); } ArchiveStatistics astats; - const auto num_matched = IterateFilesInZip(out_global_info, optional_filter, - callback, generateArchiveStatistics, &astats); + unsigned int num_matched; + + PlatformResult result = IterateFilesInZip(out_global_info, optional_filter, + callback, generateArchiveStatistics, num_matched, &astats); + if ( result.error_code() != ErrorCode::NO_ERROR) { + return result; + } if(0 == num_matched) { LoggerE("No matching file/directory: [%s] has been found in zip archive", optional_filter.c_str()); LoggerE("Throwing NotFoundException - Could not extract file from archive"); - throw NotFoundException("Could not extract file from archive"); + return PlatformResult(ErrorCode::NOT_FOUND_ERR, "Could not extract file from archive"); } callback->setExpectedDecompressedSize(astats.uncompressed_size); @@ -420,6 +457,8 @@ void UnZip::updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* call callback->setNumberOfFilesToExtract(astats.number_of_files); LoggerD("Number entries to extract: files: %d folders: %d", astats.number_of_files, astats.number_of_folders); + + return PlatformResult(ErrorCode::NO_ERROR); } } //namespace archive diff --git a/src/archive/un_zip.h b/src/archive/un_zip.h index eac7deff..430abd1f 100644 --- a/src/archive/un_zip.h +++ b/src/archive/un_zip.h @@ -21,9 +21,9 @@ #include #include #include - #include +#include "common/platform_result.h" #include "archive_callback_data.h" #include "archive_file_entry.h" @@ -40,21 +40,21 @@ typedef std::shared_ptr UnZipPtr; class UnZip { public: - static UnZipPtr open(const std::string& filename); + static PlatformResult open(const std::string& filename, UnZipPtr* out_unzip); ~UnZip(); - ArchiveFileEntryPtrMapPtr listEntries(unsigned long *decompressedSize); + PlatformResult listEntries(unsigned long *decompressedSize, ArchiveFileEntryPtrMapPtr* out_map); /** * \brief Extract all files to output directory * \param callback which keep pointer to ArchiveFile. */ - void extractAllFilesTo(const std::string& extract_path, + PlatformResult extractAllFilesTo(const std::string& extract_path, ExtractAllProgressCallback* callback); - void extractTo(ExtractEntryProgressCallback* callback); + PlatformResult extractTo(ExtractEntryProgressCallback* callback); - void close(); + PlatformResult close(); private: UnZip(const std::string& filename); @@ -63,25 +63,26 @@ private: * \brief Extract current file (iterated with minizip library) * \param callback which keep pointer to ArchiveFile. */ - void extractCurrentFile(const std::string& extract_path, + PlatformResult extractCurrentFile(const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback); - static void extractItFunction(const std::string& file_name, + static PlatformResult extractItFunction(const std::string& file_name, unz_file_info& file_info, void* user_data); - typedef void (*IterateFunction) (const std::string& file_name, + typedef PlatformResult (*IterateFunction) (const std::string& file_name, unz_file_info& file_info, void* user_data); - unsigned int IterateFilesInZip(unz_global_info& gi, + PlatformResult IterateFilesInZip(unz_global_info& gi, const std::string& entry_name_in_zip, OperationCallbackData* callback, IterateFunction itfunc, + unsigned int& num_file_or_folder_matched, void* user_data); - void updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, + PlatformResult updateCallbackWithArchiveStatistics(ExtractAllProgressCallback* callback, unz_global_info& out_global_info, const std::string optional_filter = std::string()); diff --git a/src/archive/un_zip_extract_request.cc b/src/archive/un_zip_extract_request.cc index 1ac27496..8ed2c15d 100644 --- a/src/archive/un_zip_extract_request.cc +++ b/src/archive/un_zip_extract_request.cc @@ -27,9 +27,7 @@ #include #include "common/logger.h" -#include "common/platform_exception.h" #include "filesystem_file.h" - #include "archive_file.h" #include "archive_utils.h" #include "un_zip.h" @@ -84,7 +82,7 @@ void createMissingDirectories(const std::string& path, bool check_first = true) const size_t extract_path_len = path.length(); for(size_t i = 0; i < extract_path_len; ++i) { const char& cur = path[i]; - if( (('\\' == cur || '/' == cur) && i > 0) || //handle left side from current / + if((('\\' == cur || '/' == cur) && i > 0) || //handle left side from current / (extract_path_len-1 == i) ) { //handle last subdirectory path const std::string left_part = path.substr(0,i+1); @@ -128,12 +126,16 @@ void changeFileAccessAndModifyDate(const std::string& filepath, tm_unz tmu_date) } } -void UnZipExtractRequest::execute(UnZip& owner, const std::string& extract_path, +PlatformResult UnZipExtractRequest::execute(UnZip& owner, const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback) { UnZipExtractRequest req(owner, extract_path, base_strip_path, callback); - req.run(); + if(!req.m_callback){ + LoggerE("Callback is null"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Problem with callback functionality"); + } + return req.run(); } UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, @@ -154,23 +156,24 @@ UnZipExtractRequest::UnZipExtractRequest(UnZip& owner, m_is_directory_entry(false) { - if(!m_callback){ - LoggerE("Callback is null"); - throw UnknownException("Problem with callback functionality"); - } } -void UnZipExtractRequest::run() +PlatformResult UnZipExtractRequest::run() { LoggerD("Entered"); - getCurrentFileInfo(); + PlatformResult result = getCurrentFileInfo(); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } if(m_is_directory_entry) { - handleDirectoryEntry(); + result = handleDirectoryEntry(); } else { - handleFileEntry(); + result = handleFileEntry(); } + + return result; } UnZipExtractRequest::~UnZipExtractRequest() @@ -199,14 +202,14 @@ UnZipExtractRequest::~UnZipExtractRequest() } } -void UnZipExtractRequest::getCurrentFileInfo() +PlatformResult UnZipExtractRequest::getCurrentFileInfo() { LoggerD("Entered"); int err = unzGetCurrentFileInfo(m_owner.m_unzip, &m_file_info, m_filename_inzip, sizeof(m_filename_inzip), NULL, 0, NULL, 0); if (err != UNZ_OK) { LoggerE("ret: %d", err); - throwArchiveException(err, "unzGetCurrentFileInfo()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzGetCurrentFileInfo()")); } LoggerD("Input from ZIP: m_filename_inzip: [%s]", m_filename_inzip); @@ -266,9 +269,10 @@ void UnZipExtractRequest::getCurrentFileInfo() createMissingDirectories(m_new_dir_path, false); } } + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZipExtractRequest::handleDirectoryEntry() +PlatformResult UnZipExtractRequest::handleDirectoryEntry() { LoggerD("Entered"); if(FPS_DIRECTORY != m_new_dir_status) { @@ -279,14 +283,13 @@ void UnZipExtractRequest::handleDirectoryEntry() if(std::remove(fn.c_str()) != 0) { LoggerE("std::remove(\"%s\") failed with errno:%s", m_new_dir_path.c_str(), strerror(errno)); - throw UnknownException( - "Could not overwrite file in output directory"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not overwrite file in output directory"); } } else { //Is a file & overwrite is not set: LoggerE("Failed to extract directory, " "file with the same name exists in output directory"); - throw UnknownException("Failed to extract directory, " - "file with the same name exists in output directory"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to extract directory, " + "file with the same name exists in output directory"); } } @@ -294,8 +297,7 @@ void UnZipExtractRequest::handleDirectoryEntry() if(mkdir(m_new_dir_path.c_str(), 0775) == -1) { LoggerE("Couldn't create new directory: %s errno:%s", m_new_dir_path.c_str(), strerror(errno)); - throw UnknownException( - "Could not create new directory in extract output directory"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not create new directory in extract output directory"); } } @@ -311,9 +313,11 @@ void UnZipExtractRequest::handleDirectoryEntry() changeFileAccessAndModifyDate(m_new_dir_path, m_file_info.tmu_date); LoggerD("Extracted directory entry: [%s]", m_new_dir_path.c_str()); + + return PlatformResult(ErrorCode::NO_ERROR); } -bool UnZipExtractRequest::prepareOutputSubdirectory() +PlatformResult UnZipExtractRequest::prepareOutputSubdirectory() { LoggerD("Entered"); //This zip entry points to file - verify that parent directory in output dir exists @@ -321,8 +325,8 @@ bool UnZipExtractRequest::prepareOutputSubdirectory() if(FPS_FILE == m_new_dir_status) { LoggerE("Path: %s is pointing to file not directory!", m_new_dir_path.c_str()); - throw UnknownException("Failed to extract file from zip archive, " - "output path is invalid"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to extract file from zip archive, " + "output path is invalid"); } //Try to create new directory in output directory @@ -338,7 +342,7 @@ bool UnZipExtractRequest::prepareOutputSubdirectory() if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } const FilePathStatus output_fstatus = getPathStatus(m_output_filepath); @@ -349,45 +353,41 @@ bool UnZipExtractRequest::prepareOutputSubdirectory() m_output_filepath.c_str()); //Just skip this file - TODO: this should be documented in WIDL - return false; + return PlatformResult(ErrorCode::INVALID_MODIFICATION_ERR, "file already exists."); } else { if(FPS_DIRECTORY == output_fstatus) { - try { - filesystem::PathPtr path = filesystem::Path::create(m_output_filepath); - filesystem::NodePtr node = filesystem::Node::resolve(path); - node->remove(filesystem::OPT_RECURSIVE); - LoggerD("Removed directory: [%s]", m_output_filepath.c_str()); - } catch(PlatformException& ex) { - LoggerE("Remove dir: [%s] failed with exception: %s:%s", - m_output_filepath.c_str(), - ex.name().c_str(), ex.message().c_str()); - throw UnknownException("Could not overwrite existing directory"); - } catch (...) { - LoggerE("Remove dir: [%s] failed", m_output_filepath.c_str()); - throw UnknownException("Could not overwrite existing directory"); + filesystem::PathPtr path = filesystem::Path::create(m_output_filepath); + filesystem::NodePtr node; + PlatformResult result = filesystem::Node::resolve(path, &node); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + result = node->remove(filesystem::OPT_RECURSIVE); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; } - } //else { - //We will overwrite it with fopen - //} + } } } - return true; + return PlatformResult(ErrorCode::NO_ERROR); } -void UnZipExtractRequest::handleFileEntry() +PlatformResult UnZipExtractRequest::handleFileEntry() { LoggerD("Entered"); - if(!prepareOutputSubdirectory()) { + + PlatformResult result = prepareOutputSubdirectory(); + if (result.error_code() != ErrorCode::NO_ERROR) { LoggerE("File exists but overwrite is false"); - throw InvalidModificationException("file already exists."); + return result; } int err = unzOpenCurrentFilePassword(m_owner.m_unzip, NULL); //password is not supported yet therefore passing NULL if (UNZ_OK != err) { LoggerE("ret: %d", err); - throwArchiveException(err, "unzOpenCurrentFilePassword()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "unzOpenCurrentFilePassword()")); } //We have successfully opened curent file, therefore we should close it later @@ -398,13 +398,13 @@ void UnZipExtractRequest::handleFileEntry() if(!m_buffer) { LoggerE("Couldn't allocate buffer with size: %s", bytesToReadableString(buffer_size).c_str()); - throw UnknownException("Memory allocation failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Memory allocation failed"); } m_output_file = fopen(m_output_filepath.c_str(), "wb"); if(!m_output_file) { LoggerE("Couldn't open output file: %s", m_output_filepath.c_str()); - throw UnknownException("Could not create extracted file"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not create extracted file"); } m_delete_output_file = true; @@ -426,20 +426,20 @@ void UnZipExtractRequest::handleFileEntry() auto it = entries->find(m_filename_inzip); if (it == entries->end()) { LoggerE("Entry not found"); - throw NotFoundException("Entry not found"); + return PlatformResult(ErrorCode::NOT_FOUND_ERR, "Entry not found"); } while(true) { if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } read_size = unzReadCurrentFile(m_owner.m_unzip, m_buffer, buffer_size); if (read_size < 0) { LoggerE("unzReadCurrentFile failed with error code:%d for file:%s", read_size, m_filename_inzip); - throw UnknownException("Failed to extract file from zip archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Failed to extract file from zip archive"); } else if(0 == read_size) { @@ -465,7 +465,7 @@ void UnZipExtractRequest::handleFileEntry() if (fwrite(m_buffer, read_size, 1, m_output_file) != 1) { LoggerE("Couldn't write extracted data to output file:%s", m_output_filepath.c_str()); - throw UnknownException("Could not write extract file into output file"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not write extract file into output file"); } if(extract_callback) { @@ -499,6 +499,8 @@ void UnZipExtractRequest::handleFileEntry() } changeFileAccessAndModifyDate(m_output_filepath, m_file_info.tmu_date); + + return PlatformResult(ErrorCode::NO_ERROR); } } //namespace archive diff --git a/src/archive/un_zip_extract_request.h b/src/archive/un_zip_extract_request.h index c78789a6..d8b97539 100644 --- a/src/archive/un_zip_extract_request.h +++ b/src/archive/un_zip_extract_request.h @@ -34,7 +34,7 @@ enum FilePathStatus { class UnZipExtractRequest { public: - static void execute(UnZip& owner, + static PlatformResult execute(UnZip& owner, const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback); @@ -46,14 +46,11 @@ private: const std::string& extract_path, const std::string& base_strip_path, BaseProgressCallback* callback); - void run(); - - void getCurrentFileInfo(); - - void handleDirectoryEntry(); - - void handleFileEntry(); - bool prepareOutputSubdirectory(); + PlatformResult run(); + PlatformResult getCurrentFileInfo(); + PlatformResult handleDirectoryEntry(); + PlatformResult handleFileEntry(); + PlatformResult prepareOutputSubdirectory(); //----------------------------------------------------------------------------- //Input request variables diff --git a/src/archive/zip.cc b/src/archive/zip.cc index 1de915d6..354ade9e 100644 --- a/src/archive/zip.cc +++ b/src/archive/zip.cc @@ -24,9 +24,8 @@ #include #include "common/logger.h" -#include "common/platform_exception.h" +#include "common/platform_result.h" #include "filesystem_file.h" - #include "archive_file.h" #include "archive_utils.h" #include "crypt.h" @@ -82,11 +81,6 @@ Zip::Zip(const std::string& filename, ZipOpenMode open_mode) : LoggerD("append_mode: %d", append_mode); m_zip = zipOpen(filename.c_str(), append_mode); - if(!m_zip) { - LoggerE("zipOpen returned NULL!"); - throw UnknownException("Opening/creating zip file failed"); - } - m_is_open = true; } Zip::~Zip() @@ -94,12 +88,12 @@ Zip::~Zip() close(); } -void Zip::close() +PlatformResult Zip::close() { LoggerD("Entered"); if(!m_is_open) { LoggerD("Already closed - exiting."); - return; + return PlatformResult(ErrorCode::NO_ERROR); } int errclose = zipClose(m_zip, NULL); @@ -107,36 +101,51 @@ void Zip::close() if (errclose != ZIP_OK) { LoggerE("ret: %d", errclose); - throwArchiveException(errclose, "zipClose()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(errclose, "zipClose()")); } m_is_open = false; + return PlatformResult(ErrorCode::NO_ERROR); } -ZipPtr Zip::createNew(const std::string& filename) +PlatformResult Zip::createNew(const std::string& filename, ZipPtr* out_zip) { LoggerD("Entered"); - return ZipPtr(new Zip(filename, ZOM_CREATE)); + ZipPtr zip = ZipPtr(new Zip(filename, ZOM_CREATE)); + if(!zip->m_zip) { + LoggerE("zipOpen returned NULL!"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed"); + } + zip->m_is_open = true; + *out_zip = zip; + return PlatformResult(ErrorCode::NO_ERROR); } -ZipPtr Zip::open(const std::string& filename) +PlatformResult Zip::open(const std::string& filename, ZipPtr* out_zip) { LoggerD("Entered"); - return ZipPtr(new Zip(filename, ZOM_ADDINZIP)); + ZipPtr zip = ZipPtr(new Zip(filename, ZOM_ADDINZIP)); + if(!zip->m_zip) { + LoggerE("zipOpen returned NULL!"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Opening/creating zip file failed"); + } + zip->m_is_open = true; + *out_zip = zip; + return PlatformResult(ErrorCode::NO_ERROR); } -void Zip::addFile(AddProgressCallback*& callback) +PlatformResult Zip::addFile(AddProgressCallback*& callback) { LoggerD("Entered"); if(!callback) { LoggerE("callback is NULL!"); - throw UnknownException("Could not add file(-s) to archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive"); } if(!m_is_open) { LoggerE("Zip file not opened - exiting"); - throw UnknownException("Could not add file(-s) to archive - zip file closed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive - zip file closed"); } - ZipAddRequest::execute(*this, callback); + return ZipAddRequest::execute(*this, callback); } } //namespace archive diff --git a/src/archive/zip.h b/src/archive/zip.h index 3fb0807b..7fb3cbb3 100644 --- a/src/archive/zip.h +++ b/src/archive/zip.h @@ -37,8 +37,8 @@ typedef std::shared_ptr ZipPtr; class Zip { public: - static ZipPtr createNew(const std::string& filename); - static ZipPtr open(const std::string& filename); + static PlatformResult createNew(const std::string& filename, ZipPtr* out_zip); + static PlatformResult open(const std::string& filename, ZipPtr* out_zip); ~Zip(); /** @@ -46,9 +46,9 @@ public: * deleted on main thread after calling all progress callbacks. * If exception is thrown please delete callback. */ - void addFile(AddProgressCallback*& callback); + PlatformResult addFile(AddProgressCallback*& callback); - void close(); + PlatformResult close(); private: enum ZipOpenMode { diff --git a/src/archive/zip_add_request.cc b/src/archive/zip_add_request.cc index 7665cdf6..bbda2ffd 100644 --- a/src/archive/zip_add_request.cc +++ b/src/archive/zip_add_request.cc @@ -16,10 +16,7 @@ // #include "zip_add_request.h" - #include "common/logger.h" -#include "common/platform_exception.h" - #include "archive_file.h" #include "archive_file_entry.h" #include "archive_utils.h" @@ -63,27 +60,27 @@ ZipAddRequest::~ZipAddRequest() } } -void ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) +PlatformResult ZipAddRequest::execute(Zip& owner, AddProgressCallback*& callback) { ZipAddRequest req(owner, callback); - req.run(); + return req.run(); } -void ZipAddRequest::run() +PlatformResult ZipAddRequest::run() { if(!m_callback) { LoggerE("m_callback is NULL"); - throw UnknownException("Could not add file(-s) to archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file(-s) to archive"); } if(!m_callback->getFileEntry()) { LoggerE("m_callback->getFileEntry() is NULL"); - throw InvalidValuesException("Provided ArchiveFileEntry is not correct"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "Provided ArchiveFileEntry is not correct"); } if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } m_compression_level = m_callback->getFileEntry()->getCompressionLevel(); @@ -107,20 +104,24 @@ void ZipAddRequest::run() // If we have destination set then we need to create all folders and sub folders // inside this zip archive. // + PlatformResult result(ErrorCode::NO_ERROR); if(m_destination_path_in_zip.length() > 0) { LoggerD("destination is: [%s]", m_destination_path_in_zip.c_str()); for(size_t i = 0; i < m_destination_path_in_zip.length(); ++i) { const char cur_char = m_destination_path_in_zip[i]; - if( ((cur_char == '/' || cur_char == '\\') && i > 0 ) || + if(((cur_char == '/' || cur_char == '\\') && i > 0 ) || (i == m_destination_path_in_zip.length() - 1)) { //Extract left side with '/': const std::string new_dir = m_destination_path_in_zip.substr(0, i + 1); LoggerD("Adding empty directory: [%s] to archive", new_dir.c_str()); - addEmptyDirectoryToZipArchive(new_dir); + result = addEmptyDirectoryToZipArchive(new_dir); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } } } } @@ -132,7 +133,7 @@ void ZipAddRequest::run() if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } // Calculate total size to be compressed @@ -145,7 +146,10 @@ void ZipAddRequest::run() unsigned long long size = 0; if((*it)->getType() == filesystem::NT_FILE) { - size = (*it)->getSize(); + result = (*it)->getSize(&size); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } m_bytes_to_compress += size; ++m_files_to_compress; } @@ -161,17 +165,22 @@ void ZipAddRequest::run() if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } // Begin files compression // for(auto it = all_sub_nodes.begin(); it != all_sub_nodes.end(); ++it, ++i) { - addToZipArchive(*it); + result = addToZipArchive(*it); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } } m_callback->callSuccessCallbackOnMainThread(); m_callback = NULL; + + return PlatformResult(ErrorCode::NO_ERROR); } void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, @@ -188,19 +197,19 @@ void ZipAddRequest::addNodeAndSubdirsToList(filesystem::NodePtr src_node, } } -void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) +PlatformResult ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) { LoggerD("Entered name_in_zip:%s", name_in_zip.c_str()); if(name_in_zip.length() == 0) { LoggerW("Trying to create directory with empty name - \"\""); - return; + return PlatformResult(ErrorCode::NO_ERROR); } const char last_char = name_in_zip[name_in_zip.length()-1]; if(last_char != '/' && last_char != '\\') { - name_in_zip += "/"; - LoggerD("Corrected name_in_zip: [%s]", name_in_zip.c_str()); + name_in_zip += "/"; + LoggerD("Corrected name_in_zip: [%s]", name_in_zip.c_str()); } if(m_new_file_in_zip_opened) { @@ -221,16 +230,16 @@ void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) LoggerE("Entry: [%s] exists and is NOT directory!", conflicting_name.c_str()); LoggerE("Throwing InvalidValuesException - File with the same name exists"); - throw InvalidValuesException("File with the same name exists"); + return PlatformResult(ErrorCode::INVALID_VALUES_ERR, "File with the same name exists"); } LoggerD("Directory: [%s] already exists -> nothing to do", name_in_zip.c_str()); - return; + return PlatformResult(ErrorCode::NO_ERROR); } if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } zip_fileinfo new_dir_info; @@ -259,7 +268,7 @@ void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) if (err != ZIP_OK) { LoggerE("ret: %d", err); - throwArchiveException(err, "zipOpenNewFileInZip3()"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, getArchiveLogMessage(err, "zipOpenNewFileInZip3()")); } m_new_file_in_zip_opened = true; @@ -271,9 +280,11 @@ void ZipAddRequest::addEmptyDirectoryToZipArchive(std::string name_in_zip) LoggerD("Added new empty directory to archive: [%s]", name_in_zip.c_str()); m_new_file_in_zip_opened = false; + + return PlatformResult(ErrorCode::NO_ERROR); } -void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) +PlatformResult ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) { const std::string name_in_zip = getNameInZipArchiveFor(src_file_node, m_callback->getFileEntry()->getStriped()); @@ -295,7 +306,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) if(m_callback->isCanceled()) { LoggerD("Operation cancelled"); - throw OperationCanceledException(); + return PlatformResult(ErrorCode::OPERATION_CANCELED_ERR); } std::string conflicting_name; @@ -307,7 +318,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) name_in_zip.c_str(), conflicting_name.c_str()); LoggerE("Throwing InvalidModificationException - Archive entry name conflicts"); - throw InvalidModificationException("Archive entry name conflicts"); + return PlatformResult(ErrorCode::INVALID_MODIFICATION_ERR, "Archive entry name conflicts"); } int err = zipOpenNewFileInZip3(m_owner.m_zip, name_in_zip.c_str(), &new_file_info, @@ -319,7 +330,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) if (err != ZIP_OK) { LoggerE("Error opening new file: [%s] in zipfile", name_in_zip.c_str()); - throw UnknownException("Could not add new file to zip archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add new file to zip archive"); } m_new_file_in_zip_opened = true; @@ -335,7 +346,13 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) ArchiveFileEntryPtr cur_afentry(new ArchiveFileEntry(cur_file)); cur_afentry->setCompressionLevel(m_compression_level); cur_afentry->setName(name_in_zip); - cur_afentry->setModified(src_file_node->getModified()); + + std::time_t time; + PlatformResult result = src_file_node->getModified(&time); + if (result.error_code() != ErrorCode::NO_ERROR) { + return result; + } + cur_afentry->setModified(time); auto entry = m_callback->getFileEntry(); cur_afentry->setDestination(entry->getDestination()); @@ -352,7 +369,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) m_input_file = fopen(src_file_path.c_str(), "rb"); if (!m_input_file) { LoggerE("Error opening source file:%s", src_file_path.c_str()); - throw UnknownException("Could not open file to be added"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not open file to be added"); } //Get file length @@ -369,7 +386,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) m_buffer = new(std::nothrow) char[m_buffer_size]; if(!m_buffer) { LoggerE("Couldn't allocate m_buffer"); - throw UnknownException("Memory allocation error"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Memory allocation error"); } } @@ -381,7 +398,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) if (size_read < m_buffer_size && feof(m_input_file) == 0) { LoggerE("Error reading source file: %s\n", src_file_path.c_str()); - throw UnknownException("New file addition failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); } LoggerD("Read: %d bytes from input file:[%s]", size_read, @@ -394,7 +411,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) if (err < 0) { LoggerE("Error during adding file: %s into zip archive", src_file_path.c_str()); - throw UnknownException("New file addition failed"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "New file addition failed"); } } @@ -430,7 +447,7 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) if(in_file_size != total_bytes_read) { LoggerE("in_file_size(%d) != total_bytes_read(%d)", in_file_size, total_bytes_read); - throw UnknownException("Could not add file to archive"); + return PlatformResult(ErrorCode::UNKNOWN_ERR, "Could not add file to archive"); } fclose(m_input_file); @@ -443,6 +460,8 @@ void ZipAddRequest::addToZipArchive(filesystem::NodePtr src_file_node) } m_new_file_in_zip_opened = false; + + return PlatformResult(ErrorCode::NO_ERROR); } std::string removeDirCharsFromFront(const std::string& path) diff --git a/src/archive/zip_add_request.h b/src/archive/zip_add_request.h index 0bfd4e58..5c97c374 100644 --- a/src/archive/zip_add_request.h +++ b/src/archive/zip_add_request.h @@ -21,8 +21,8 @@ #include #include +#include "common/platform_result.h" #include "filesystem_file.h" - #include "archive_callback_data.h" #include "zip.h" @@ -38,18 +38,18 @@ public: * deleted on main thread after calling all progress callbacks. * If exception is thrown please delete callback. */ - static void execute(Zip& owner, AddProgressCallback*& callback); + static PlatformResult execute(Zip& owner, AddProgressCallback*& callback); ~ZipAddRequest(); private: ZipAddRequest(Zip& owner, AddProgressCallback*& callback); - void run(); + PlatformResult run(); void addNodeAndSubdirsToList(filesystem::NodePtr src_node, filesystem::NodeList& out_list_of_child_nodes); - void addEmptyDirectoryToZipArchive(std::string name_in_zip); - void addToZipArchive(filesystem::NodePtr src_file_node); + PlatformResult addEmptyDirectoryToZipArchive(std::string name_in_zip); + PlatformResult addToZipArchive(filesystem::NodePtr src_file_node); std::string getNameInZipArchiveFor(filesystem::NodePtr node, bool strip);