diff --git a/Modules/CppRestSdk/CMakeLists.txt b/Modules/CppRestSdk/CMakeLists.txt index 2bf7de274c..ba20ff7a7e 100644 --- a/Modules/CppRestSdk/CMakeLists.txt +++ b/Modules/CppRestSdk/CMakeLists.txt @@ -1,16 +1,15 @@ if(MITK_USE_CppRestSdk) MITK_CREATE_MODULE( - DEPENDS MitkCore MitkQtWidgetsExt CppMicroServices - PACKAGE_DEPENDS Qt5|Core + DEPENDS MitkCore CppMicroServices WARNINGS_NO_ERRORS AUTOLOAD_WITH MitkCore ) find_package(OpenSSL REQUIRED) target_link_libraries(${MODULE_TARGET} PRIVATE cpprestsdk::cpprest) target_link_libraries(${MODULE_TARGET} PUBLIC OpenSSL::SSL) add_subdirectory(test) endif(MITK_USE_CppRestSdk) diff --git a/Modules/CppRestSdk/files.cmake b/Modules/CppRestSdk/files.cmake index 705ca888fc..77a843d01a 100644 --- a/Modules/CppRestSdk/files.cmake +++ b/Modules/CppRestSdk/files.cmake @@ -1,14 +1,12 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES mitkRESTClientMicroService.cpp mitkRESTServerMicroService.cpp mitkCppRestSdkActivator.cpp mitkIRESTManager.cpp mitkRESTManager.cpp mitkIRESTObserver.cpp mitkCppRestSdk.cpp -) -set(MOC_H_FILES -include/mitkRESTServerMicroService.h -include/mitkRESTManager.h) \ No newline at end of file + mitkIRESTServerMicroService.cpp +) \ No newline at end of file diff --git a/Modules/CppRestSdk/include/mitkIRESTManager.h b/Modules/CppRestSdk/include/mitkIRESTManager.h index 5c7f5eb332..ab2171b378 100644 --- a/Modules/CppRestSdk/include/mitkIRESTManager.h +++ b/Modules/CppRestSdk/include/mitkIRESTManager.h @@ -1,93 +1,95 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkIRESTManager_h #define mitkIRESTManager_h #include "cpprest/json.h" #include "cpprest/uri.h" #include #include +#include +#include #include namespace mitk { - class RESTServerMicroService; - class IRESTManager + class IRESTServerMicroService; + class MITKCPPRESTSDK_EXPORT IRESTManager { public: virtual ~IRESTManager(); /** * @brief request type for client requests by calling SendRequest */ enum RequestType { get, post, put }; /** * @brief Executes a HTTP request in the mitkRESTClientMicroService class * * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param body the body for the request (optional) * @return task to wait for */ virtual pplx::task SendRequest(const web::uri &uri, - const RequestType &type = get, - const web::json::value &body = NULL, - const utility::string_t &filePath = L"") = 0; + const RequestType &type = get, + const web::json::value &body = NULL, + const utility::string_t &filePath = L"") = 0; /** * @brief starts listening for requests if there isn't another observer listening and the port is free * * @param uri defines the URI for which incoming requests should be send to the observer * @param observer the observer which handles the incoming requests */ virtual void ReceiveRequest(const web::uri &uri, IRESTObserver *observer) = 0; /** * @brief Handles incoming requests by notifying the observer which should receive it * * @param uri defines the URI of the request * @param body the body of the request * @return the data which is modified by the notified observer */ virtual web::json::value Handle(const web::uri &uri, web::json::value &body) = 0; /** * @brief Handles the deletion of an observer for all or a specific uri * * @param observer the observer which shouldn't receive requests anymore * @param uri the uri for which the observer doesn't handle requests anymore (optional) */ virtual void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri = L"") = 0; - virtual std::map GetM_ServerMap() = 0; + virtual std::map GetM_ServerMap() = 0; virtual std::map, IRESTObserver *> GetM_Observers() = 0; - + }; } // namespace mitk MITK_DECLARE_SERVICE_INTERFACE(mitk::IRESTManager, "org.mitk.IRESTManager") #endif diff --git a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h b/Modules/CppRestSdk/include/mitkIRESTServerMicroService.h similarity index 69% copy from Modules/CppRestSdk/include/mitkRESTServerMicroService.h copy to Modules/CppRestSdk/include/mitkIRESTServerMicroService.h index 26ad46b9f0..037def9ce2 100644 --- a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h +++ b/Modules/CppRestSdk/include/mitkIRESTServerMicroService.h @@ -1,77 +1,76 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#ifndef mitkRESTServerMicroService_h -#define mitkRESTServerMicroService_h +#ifndef mitkIRESTServerMicroService_h +#define mitkIRESTServerMicroService_h -#include #include "cpprest/http_listener.h" -#include "MitkCppRestSdkExports.h" + +#include #include #include #include #include typedef web::http::experimental::listener::http_listener MitkListener; typedef web::http::http_request MitkRequest; typedef web::http::http_response MitkResponse; typedef web::http::methods MitkRESTMethods; typedef web::http::status_codes MitkRestStatusCodes; typedef web::json::json_exception MitkJsonException; namespace mitk { - class RESTServerMicroService : public QObject + class MITKCPPRESTSDK_EXPORT IRESTServerMicroService { - Q_OBJECT - public: + //** + // * @brief Creates an server listening to the given URI + // * + // * @param uri the URI at which the server is listening for requests + // */ + IRESTServerMicroService(); + ~IRESTServerMicroService(); + + virtual web::uri GetUri() = 0; + /** - * @brief Creates an server listening to the given URI - * - * @param uri the URI at which the server is listening for requests + * @brief Opens the listener and starts the listening process */ - RESTServerMicroService(web::uri uri); - ~RESTServerMicroService(); + virtual void OpenListener() = 0; - web::uri GetUri(); + /** + * @brief Closes the listener and stops the listening process + */ + virtual void CloseListener() = 0; - private: + protected: /** * @brief Handle for incoming GET requests * * @param MitkRequest incoming request object */ - void HandleGet(MitkRequest request); + virtual void HandleGet(MitkRequest request) = 0; MitkListener m_Listener; web::uri m_Uri; - public slots: - /** - * @brief Opens the listener and starts the listening process - */ - void OpenListener(); - - /** - * @brief Closes the listener and stops the listening process - */ - void CloseListener(); + // public slots: }; } // namespace mitk #endif \ No newline at end of file diff --git a/Modules/CppRestSdk/include/mitkRESTClientMicroService.h b/Modules/CppRestSdk/include/mitkRESTClientMicroService.h index 8c343ed697..8a6e9c8e12 100644 --- a/Modules/CppRestSdk/include/mitkRESTClientMicroService.h +++ b/Modules/CppRestSdk/include/mitkRESTClientMicroService.h @@ -1,85 +1,86 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkRESTClientMicroService_h #define mitkRESTClientMicroService_h #include "cpprest/asyncrt_utils.h" #include "cpprest/containerstream.h" #include "cpprest/filestream.h" #include "cpprest/http_client.h" #include "cpprest/producerconsumerstream.h" #include "MitkCppRestSdkExports.h" #include #include #include #include +#include typedef web::http::client::http_client MitkClient; typedef web::http::http_request MitkRequest; typedef web::http::http_response MitkResponse; typedef web::http::methods MitkRESTMethods; typedef web::http::uri_builder MitkUriBuilder; typedef web::http::status_codes MitkRestStatusCodes; typedef web::json::json_exception MitkJsonException; namespace mitk { - class RESTClientMicroService + class MITKCPPRESTSDK_EXPORT RESTClientMicroService { public: RESTClientMicroService(); ~RESTClientMicroService(); /** *@brief Executes a HTTP GET request with the given uri and returns a task waiting for a json object * * @param uri the URI resulting the target of the HTTP request * @return task to wait for with resulting json object */ pplx::task Get(const web::uri &uri); /** *@brief Executes a HTTP GET request with the given uri and and stores the byte stream in a file given by the filePath * * @param uri the URI resulting the target of the HTTP request * @return task to wait for returning an empty json object */ pplx::task Get(const web::uri &uri, const utility::string_t &filePath); /** * @brief Executes a HTTP PUT request with given uri and the content given as json * * @param uri defines the URI resulting the target of the HTTP request * @param content the content as json value which should be the body of the request and thus the content of the * created resources * @return task to wait for with resulting json object */ pplx::task PUT(const web::uri &uri, const web::json::value &content); /** * @brief Executes a HTTP POST request with given uri and the content given as json * * @param uri defines the URI resulting the target of the HTTP request * @param content the content as json value which should be the body of the request and thus the content of the created resource * @return task to wait for with resulting json object */ pplx::task POST(const web::uri &uri, const web::json::value &content); }; } // namespace mitk #endif // !mitkRESTClientMicroService_h diff --git a/Modules/CppRestSdk/include/mitkRESTManager.h b/Modules/CppRestSdk/include/mitkRESTManager.h index cdbcd0514d..975bf74ae2 100644 --- a/Modules/CppRestSdk/include/mitkRESTManager.h +++ b/Modules/CppRestSdk/include/mitkRESTManager.h @@ -1,87 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkRESTManager_h #define mitkRESTManager_h -#include -#include - #include #include #include #include namespace mitk { - class MITKCPPRESTSDK_EXPORT RESTManager : public QObject, public IRESTManager + class MITKCPPRESTSDK_EXPORT RESTManager : public IRESTManager { - Q_OBJECT public: RESTManager(); ~RESTManager() override; /** * @brief Executes a HTTP request in the mitkRESTClientMicroService class * * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param body the body for the request (optional) * @param filePath the file path to store the request to * @return task to wait for */ pplx::task SendRequest(const web::uri &uri, const RequestType &type = get, const web::json::value &body= NULL, const utility::string_t &filePath = L"") override; /** * @brief starts listening for requests if there isn't another observer listening and the port is free * * @param uri defines the URI for which incoming requests should be send to the observer * @param observer the observer which handles the incoming requests */ void ReceiveRequest(const web::uri &uri, IRESTObserver *observer) override; /** * @brief Handles incoming requests by notifying the observer which should receive it * * @param uri defines the URI of the request * @param body the body of the request * @return the data which is modified by the notified observer */ web::json::value Handle(const web::uri &uri, web::json::value &body) override; /** * @brief Handles the deletion of an observer for all or a specific uri * * @param observer the observer which shouldn't receive requests anymore * @param uri the uri for which the observer doesn't handle requests anymore (optional) */ virtual void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri) override; - virtual std::map GetM_ServerMap() override; + virtual std::map GetM_ServerMap() override; virtual std::map, IRESTObserver *> GetM_Observers() override; private: - std::map m_ServerMap; // Map with port server pairs - std::map m_ServerThreadMap; // Map with threads for servers + std::map m_ServerMap; // Map with port server pairs std::map, IRESTObserver *> m_Observers; // Map with all observers }; } // namespace mitk #endif // !mitkRESTManager_h diff --git a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h b/Modules/CppRestSdk/include/mitkRESTServerMicroService.h index 26ad46b9f0..3e9581ac90 100644 --- a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h +++ b/Modules/CppRestSdk/include/mitkRESTServerMicroService.h @@ -1,77 +1,71 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkRESTServerMicroService_h #define mitkRESTServerMicroService_h -#include #include "cpprest/http_listener.h" #include "MitkCppRestSdkExports.h" #include #include #include #include +#include +#include typedef web::http::experimental::listener::http_listener MitkListener; typedef web::http::http_request MitkRequest; typedef web::http::http_response MitkResponse; typedef web::http::methods MitkRESTMethods; typedef web::http::status_codes MitkRestStatusCodes; typedef web::json::json_exception MitkJsonException; namespace mitk { - class RESTServerMicroService : public QObject + class MITKCPPRESTSDK_EXPORT RESTServerMicroService : public IRESTServerMicroService { - Q_OBJECT - public: /** * @brief Creates an server listening to the given URI * * @param uri the URI at which the server is listening for requests */ RESTServerMicroService(web::uri uri); ~RESTServerMicroService(); - web::uri GetUri(); - - private: - /** - * @brief Handle for incoming GET requests - * - * @param MitkRequest incoming request object - */ - void HandleGet(MitkRequest request); - - MitkListener m_Listener; - web::uri m_Uri; + web::uri GetUri() override; - public slots: - /** + /** * @brief Opens the listener and starts the listening process */ - void OpenListener(); + void OpenListener() override; /** * @brief Closes the listener and stops the listening process */ - void CloseListener(); + void CloseListener() override; + private: + /** + * @brief Handle for incoming GET requests + * + * @param MitkRequest incoming request object + */ + void HandleGet(MitkRequest request) override; }; } // namespace mitk #endif \ No newline at end of file diff --git a/Modules/CppRestSdk/src/mitkCppRestSdkActivator.cpp b/Modules/CppRestSdk/src/mitkCppRestSdkActivator.cpp index 0f7af349eb..8cfb1d2e51 100644 --- a/Modules/CppRestSdk/src/mitkCppRestSdkActivator.cpp +++ b/Modules/CppRestSdk/src/mitkCppRestSdkActivator.cpp @@ -1,26 +1,28 @@ #include "mitkCppRestSdkActivator.h" #include #include #include #include #include #include #include #include #include #include #include void MitkCppRestSdkActivator::Load(us::ModuleContext *context) { //Registration of the RESTManagerMicroservice m_RESTManager.reset(new mitk::RESTManager); - context->RegisterService(m_RESTManager.get()); + us::ServiceProperties props; + props[us::ServiceConstants::SERVICE_RANKING()] = 5; + context->RegisterService(m_RESTManager.get(),props); } void MitkCppRestSdkActivator::Unload(us::ModuleContext *) { } US_EXPORT_MODULE_ACTIVATOR(MitkCppRestSdkActivator) diff --git a/Modules/CppRestSdk/src/mitkIRESTManager.cpp b/Modules/CppRestSdk/src/mitkIRESTManager.cpp index 65788c646f..b54c19f6d9 100644 --- a/Modules/CppRestSdk/src/mitkIRESTManager.cpp +++ b/Modules/CppRestSdk/src/mitkIRESTManager.cpp @@ -1,3 +1,3 @@ #include "mitkIRESTManager.h" -mitk::IRESTManager::~IRESTManager() {} \ No newline at end of file +mitk::IRESTManager::~IRESTManager() {} diff --git a/Modules/CppRestSdk/src/mitkIRESTServerMicroService.cpp b/Modules/CppRestSdk/src/mitkIRESTServerMicroService.cpp new file mode 100644 index 0000000000..3f478adc55 --- /dev/null +++ b/Modules/CppRestSdk/src/mitkIRESTServerMicroService.cpp @@ -0,0 +1,5 @@ +#include "mitkIRESTServerMicroService.h" + +mitk::IRESTServerMicroService::IRESTServerMicroService() {} + +mitk::IRESTServerMicroService::~IRESTServerMicroService() {} diff --git a/Modules/CppRestSdk/src/mitkRESTManager.cpp b/Modules/CppRestSdk/src/mitkRESTManager.cpp index 9fee438abf..303a6d9f50 100644 --- a/Modules/CppRestSdk/src/mitkRESTManager.cpp +++ b/Modules/CppRestSdk/src/mitkRESTManager.cpp @@ -1,228 +1,203 @@ #include "mitkRESTManager.h" #include -#include + mitk::RESTManager::RESTManager() {} mitk::RESTManager::~RESTManager() {} pplx::task mitk::RESTManager::SendRequest(const web::uri &uri, const RequestType &type, const web::json::value &content, const utility::string_t &filePath) { pplx::task answer; auto client = new RESTClientMicroService(); //according to the RequestType, different HTTP requests are made switch (type) { case get: { if (filePath == L"") { //no file path specified, starts a normal get request returning the normal json result answer = client->Get(uri); } else { //file path ist specified, the result of the get request ist stored in this file //and an empty json object is returned answer = client->Get(uri, filePath); } break; } case post: { if (content == NULL) { //warning because normally you won't create an empty ressource MITK_WARN << "Content for put is empty, this will create an empty ressource"; } answer = client->POST(uri, content); break; } break; case put: { if (content == NULL) { //warning because normally you won't empty a ressource MITK_WARN << "Content for put is empty, this will empty the ressource"; } answer = client->PUT(uri,content); break; } } return answer; } void mitk::RESTManager::ReceiveRequest(const web::uri &uri, mitk::IRESTObserver *observer) { // New instance of RESTServerMicroservice in m_ServerMap, key is port of the request int port = uri.port(); // Checking if port is free to add a new Server if (m_ServerMap.count(port) == 0) { // new observer has to be added std::pair key(uri.port(), uri.path()); m_Observers[key] = observer; // testing if entry has been added to observer map utility::string_t uristringt = uri.path(); std::string uristring(uristringt.begin(), uristringt.end()); MITK_INFO <<"[" <OpenListener(); - if (QCoreApplication::instance() != NULL) - { - // Move server to seperate Thread and create connections between threads - m_ServerThreadMap[port] = new QThread(); - server->moveToThread(m_ServerThreadMap[port]); - - connect(m_ServerThreadMap[port], &QThread::finished, server, &QObject::deleteLater); - - // starting Server - m_ServerThreadMap[port]->start(); - QMetaObject::invokeMethod(server, "OpenListener"); - } - else - { - server->OpenListener(); - } - utility::string_t host = uri.authority().to_string(); std::string hoststring(host.begin(), host.end()); MITK_INFO << "new server" << hoststring << " at port" << port; } // If there is already a server under this port else { // Same host, means new observer but not a new server instance if (m_ServerMap[port]->GetUri() == uri.authority()) { // new observer has to be added std::pair key(uri.port(), uri.path()); //only add a new observer if there isn't already an observer for this uri if (m_Observers.count(key) == 0) { m_Observers[key] = observer; // testing if entry has been added to map utility::string_t uristringt = uri.path(); std::string uristring(uristringt.begin(), uristringt.end()); MITK_INFO << "[" << uri.port() << ", " << uristring<< "] : Number of elements in map: " << m_Observers.count(key); // info output MITK_INFO << "started listening, no new server instance has been created"; } else { MITK_ERROR << "Threre is already a observer handeling this data"; } } // Error, since another server can't be added under this port else { MITK_ERROR << "There is already another server listening under this port"; } } } web::json::value mitk::RESTManager::Handle(const web::uri &uri, web::json::value &body) { // Checking if there is an observer for the port and path std::pair key(uri.port(), uri.path()); if (m_Observers.count(key) != 0) { MITK_INFO << "Manager: Data send to observer"; return m_Observers[key]->Notify(body,uri); } //No observer under this port, return null which results in status code 404 (s. RESTServerMicroService) else { MITK_WARN << "No Observer can handle the data"; return NULL; } } void mitk::RESTManager::HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri= L"") { for (auto it = m_Observers.begin(); it != m_Observers.end();) { mitk::IRESTObserver *obsMap = it->second; // Check wether observer is at this place in map if (obsMap == observer) { //Check wether it is the right uri to be deleted if (uri==L""||it->first.second == uri.path()) { // if yes // 1. store port and path in a temporary variable // (path is only needed to create a key for info output) int port = it->first.first; utility::string_t path = it->first.second; std::pair key(port, path); MITK_INFO << "Number of elements at key [ " << port << ", " << std::string(key.second.begin(), key.second.end()) << "]: " << m_Observers.count(key); // 2. delete map entry it = m_Observers.erase(it); MITK_INFO << "Number of elements at key [ " << port << ", " << std::string(key.second.begin(), key.second.end()) << "]: " << m_Observers.count(key); // 3. check, if there is another observer under this port in observer map (with bool flag) bool noObserverForPort = true; for (auto o : m_Observers) { if (o.first.first == port) { // there still exists an observer for this port noObserverForPort = false; } } if (noObserverForPort) { // there isn't an observer at this port, delete m_ServerMap entry for this port // close listener - if (QCoreApplication::instance() != NULL) - { - QMetaObject::invokeMethod(m_ServerMap[port], "CloseListener"); - // end thread - m_ServerThreadMap[port]->quit(); - m_ServerThreadMap[port]->wait(); - } - else - { - m_ServerMap[port]->CloseListener(); - m_ServerMap[port]->~RESTServerMicroService(); - } + m_ServerMap[port]->CloseListener(); + dynamic_cast(m_ServerMap[port])->~RESTServerMicroService(); // delete server from map m_ServerMap.erase(port); } } else { ++it; } } else { ++it; } } } -std::map mitk::RESTManager::GetM_ServerMap() +std::map mitk::RESTManager::GetM_ServerMap() { return m_ServerMap; } std::map, mitk::IRESTObserver *> mitk::RESTManager::GetM_Observers() { return m_Observers; } diff --git a/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp b/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp index 1332e2d3c7..37da54f090 100644 --- a/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp +++ b/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp @@ -1,73 +1,73 @@ #include "mitkRESTServerMicroService.h" #include -mitk::RESTServerMicroService::RESTServerMicroService(web::uri uri) : m_Listener(uri) +mitk::RESTServerMicroService::RESTServerMicroService(web::uri uri) { m_Uri = uri; } mitk::RESTServerMicroService::~RESTServerMicroService() { } void mitk::RESTServerMicroService::OpenListener() { //create listener m_Listener = MitkListener(m_Uri); //Connect incoming get requests with HandleGet method m_Listener.support(web::http::methods::GET, std::bind(&mitk::RESTServerMicroService::HandleGet, this, std::placeholders::_1)); //open listener m_Listener.open().wait(); } void mitk::RESTServerMicroService::CloseListener() { //close listener m_Listener.close().wait(); } web::uri mitk::RESTServerMicroService::GetUri() { return m_Uri; } void mitk::RESTServerMicroService::HandleGet(MitkRequest request) { int port = m_Listener.uri().port(); //getting exact request uri has to be a parameter in handle function web::uri_builder build(m_Listener.uri()); build.append(request.absolute_uri()); utility::string_t uriStringT = build.to_uri().to_string(); std::string uriString(uriStringT.begin(), uriStringT.end()); MITK_INFO << "Get Request fot server at port " << port << " Exact request uri: " << uriString; web::json::value content; //get RESTManager as microservice to call th Handle method of the manager us::ModuleContext *context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { web::json::value data = request.extract_json().get(); MITK_INFO << "Server: Data send to manager"; //call the handle method content = managerService->Handle(build.to_uri(), data); MITK_INFO << "server: Data received from manager"; } } if (content!=NULL) { //content handled by observer request.reply(MitkRestStatusCodes::OK, content); } else { //no observer to handle data request.reply(MitkRestStatusCodes::NotFound); } } \ No newline at end of file diff --git a/Modules/CppRestSdk/test/mitkRESTClientTest.cpp b/Modules/CppRestSdk/test/mitkRESTClientTest.cpp index 9554a63880..6596eea8b9 100644 --- a/Modules/CppRestSdk/test/mitkRESTClientTest.cpp +++ b/Modules/CppRestSdk/test/mitkRESTClientTest.cpp @@ -1,281 +1,279 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // Testing #include "mitkTestFixture.h" #include "mitkTestingMacros.h" // MITK includes #include "mitkRESTClientMicroService.h" // VTK includes #include #include "mitkIRESTManager.h" #include #include #include #include #include #include -#include -#include class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver { CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite); MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish); MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON); MITK_TEST(GetRequestInvalidURI_ThrowsException); MITK_TEST(PutRequestInvalidURI_ThrowsException); MITK_TEST(PostRequestInvalidURI_ThrowsException); CPPUNIT_TEST_SUITE_END(); public: mitk::IRESTManager *m_Service; web::json::value Notify(web::json::value &data, const web::uri &uri) override { MITK_INFO << "Observer: Data in observer"; data[L"userId"] = web::json::value(1); data[L"id"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a title")); data[L"body"] = web::json::value(U("this is a body")); return data; } /** * @brief Setup Always call this method before each Test-case to ensure correct and new intialization of the used * members for a new test case. (If the members are not used in a test, the method does not need to be called). */ void setUp() override { us::ServiceReference serviceRef = us::GetModuleContext()->GetServiceReference(); if (serviceRef) { m_Service = us::GetModuleContext()->GetService(serviceRef); } if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } } void tearDown() override { if (m_Service) { m_Service->HandleDeleteObserver(this); } } void GetRequestValidURI_ReturnsExpectedJSON() { web::json::value *result = new web::json::value(); web::json::value data; data[L"userId"] = web::json::value(1); data[L"id"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a title")); data[L"body"] = web::json::value(U("this is a body")); if (m_Service) { m_Service->SendRequest(L"http://localhost:8080/test") .then([=](pplx::task resultTask) { try { *result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); } CPPUNIT_ASSERT_MESSAGE("Result is the expected JSON value", *result == data); } void MultipleGetRequestValidURI_AllTasksFinish() { int *count = new int(0); if (m_Service) { // Create multiple tasks e.g. as shown below std::vector> tasks; for (int i = 0; i < 20; i++) { pplx::task singleTask = m_Service->SendRequest(L"http://localhost:8080/test") .then([=](pplx::task resultTask) { // Do something when a single task is done try { resultTask.get(); *count +=1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); tasks.push_back(singleTask); } // Create a joinTask which includes all tasks you've created auto joinTask = pplx::when_all(begin(tasks), end(tasks)); // Run asynchonously joinTask.then([=](pplx::task resultTask) { // Do something when all tasks are finished try { resultTask.get(); *count += 1; } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }).wait(); } CPPUNIT_ASSERT_MESSAGE("Multiple Requests", *count ==21); } void PutRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value *result = new web::json::value(); web::json::value data; if (m_Service) { data[L"userId"] = web::json::value(1); data[L"id"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a changed title")); data[L"body"] = web::json::value(U("and the body is changed as well")); m_Service ->SendRequest(L"https://jsonplaceholder.typicode.com/posts/1", mitk::IRESTManager::RequestType::put, data) .then([=](pplx::task resultTask) { try { *result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); } CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", *result == data); } void PostRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value *result = new web::json::value(); web::json::value data; if (m_Service) { data[L"userId"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a new title")); data[L"body"] = web::json::value(U("this is a new body")); m_Service->SendRequest(L"https://jsonplaceholder.typicode.com/posts", mitk::IRESTManager::RequestType::post, data) .then([=](pplx::task resultTask) { try { *result = resultTask.get(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }) .wait(); } data[L"id"] = web::json::value(101); CPPUNIT_ASSERT_MESSAGE( "Result is the expected JSON value, check if the link is still valid since this is an optional test", *result == data); } void GetException() { //Method which makes a get request to an invalid uri web::json::value *result = new web::json::value(); if (m_Service) { m_Service->SendRequest(L"http://localhost:1234/invalid") .then([=](pplx::task resultTask) { *result = resultTask.get(); }) .wait(); } } void GetRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(GetException(), mitk::Exception); } void PutException() { //Method which makes a put request to an invalid uri web::json::value *result = new web::json::value(); web::json::value data; if (m_Service) { data[L"userId"] = web::json::value(1); data[L"id"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a changed title")); data[L"body"] = web::json::value(U("and the body is changed as well")); m_Service->SendRequest(L"http://localhost:1234/invalid", mitk::IRESTManager::RequestType::put, data) .then([=](pplx::task resultTask) { *result = resultTask.get();}) .wait(); } } void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); } void PostException() { //Method which makes a post request to an invalid uri web::json::value *result = new web::json::value(); web::json::value data; if (m_Service) { data[L"userId"] = web::json::value(1); data[L"title"] = web::json::value(U("this is a new title")); data[L"body"] = web::json::value(U("this is a new body")); m_Service->SendRequest(L"http://localhost:1234/invalid", mitk::IRESTManager::RequestType::post, data) .then([=](pplx::task resultTask) { *result = resultTask.get(); }) .wait(); } } void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTClient) \ No newline at end of file diff --git a/Modules/CppRestSdk/CMakeLists.txt b/Modules/CppRestSdkQt/CMakeLists.txt similarity index 67% copy from Modules/CppRestSdk/CMakeLists.txt copy to Modules/CppRestSdkQt/CMakeLists.txt index 2bf7de274c..457076c61f 100644 --- a/Modules/CppRestSdk/CMakeLists.txt +++ b/Modules/CppRestSdkQt/CMakeLists.txt @@ -1,16 +1,15 @@ if(MITK_USE_CppRestSdk) MITK_CREATE_MODULE( - DEPENDS MitkCore MitkQtWidgetsExt CppMicroServices + DEPENDS MitkCore MitkQtWidgetsExt CppMicroServices MitkCppRestSdk PACKAGE_DEPENDS Qt5|Core WARNINGS_NO_ERRORS - AUTOLOAD_WITH MitkCore + AUTOLOAD_WITH MitkQtWidgets ) find_package(OpenSSL REQUIRED) target_link_libraries(${MODULE_TARGET} PRIVATE cpprestsdk::cpprest) target_link_libraries(${MODULE_TARGET} PUBLIC OpenSSL::SSL) -add_subdirectory(test) -endif(MITK_USE_CppRestSdk) +endif() diff --git a/Modules/CppRestSdkQt/files.cmake b/Modules/CppRestSdkQt/files.cmake new file mode 100644 index 0000000000..2b0784db4b --- /dev/null +++ b/Modules/CppRestSdkQt/files.cmake @@ -0,0 +1,11 @@ +file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") + +set(CPP_FILES +mitkRESTManagerQt.cpp +mitkCppRestSdkQtActivator.cpp +mitkRESTServerMicroServiceQt.cpp +) + +set(MOC_H_FILES +include/mitkRESTManagerQt.h +include/mitkRESTServerMicroServiceQt.h) \ No newline at end of file diff --git a/Modules/CppRestSdk/include/mitkRESTManager.h b/Modules/CppRestSdkQt/include/mitkRESTManagerQt.h similarity index 80% copy from Modules/CppRestSdk/include/mitkRESTManager.h copy to Modules/CppRestSdkQt/include/mitkRESTManagerQt.h index cdbcd0514d..82bf56e28b 100644 --- a/Modules/CppRestSdk/include/mitkRESTManager.h +++ b/Modules/CppRestSdkQt/include/mitkRESTManagerQt.h @@ -1,87 +1,87 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#ifndef mitkRESTManager_h -#define mitkRESTManager_h +#ifndef mitkRESTManagerQt_h +#define mitkRESTManagerQt_h #include #include #include #include -#include +#include -#include +#include namespace mitk { - class MITKCPPRESTSDK_EXPORT RESTManager : public QObject, public IRESTManager + class MITKCPPRESTSDKQT_EXPORT RESTManagerQt : public QObject, public IRESTManager { - Q_OBJECT + Q_OBJECT public: - RESTManager(); - ~RESTManager() override; + RESTManagerQt(); + ~RESTManagerQt() override; /** * @brief Executes a HTTP request in the mitkRESTClientMicroService class * * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param body the body for the request (optional) * @param filePath the file path to store the request to * @return task to wait for */ pplx::task SendRequest(const web::uri &uri, const RequestType &type = get, - const web::json::value &body= NULL, + const web::json::value &body = NULL, const utility::string_t &filePath = L"") override; - + /** * @brief starts listening for requests if there isn't another observer listening and the port is free * * @param uri defines the URI for which incoming requests should be send to the observer * @param observer the observer which handles the incoming requests */ void ReceiveRequest(const web::uri &uri, IRESTObserver *observer) override; /** * @brief Handles incoming requests by notifying the observer which should receive it * * @param uri defines the URI of the request * @param body the body of the request * @return the data which is modified by the notified observer */ web::json::value Handle(const web::uri &uri, web::json::value &body) override; /** * @brief Handles the deletion of an observer for all or a specific uri * * @param observer the observer which shouldn't receive requests anymore * @param uri the uri for which the observer doesn't handle requests anymore (optional) */ virtual void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri) override; - virtual std::map GetM_ServerMap() override; + virtual std::map GetM_ServerMap() override; virtual std::map, IRESTObserver *> GetM_Observers() override; private: - std::map m_ServerMap; // Map with port server pairs - std::map m_ServerThreadMap; // Map with threads for servers + std::map m_ServerMap; // Map with port server pairs + std::map m_ServerThreadMap; // Map with threads for servers std::map, IRESTObserver *> m_Observers; // Map with all observers }; } // namespace mitk -#endif // !mitkRESTManager_h +#endif // !mitkRESTManager_h \ No newline at end of file diff --git a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h b/Modules/CppRestSdkQt/include/mitkRESTServerMicroServiceQt.h similarity index 71% copy from Modules/CppRestSdk/include/mitkRESTServerMicroService.h copy to Modules/CppRestSdkQt/include/mitkRESTServerMicroServiceQt.h index 26ad46b9f0..2600391f0f 100644 --- a/Modules/CppRestSdk/include/mitkRESTServerMicroService.h +++ b/Modules/CppRestSdkQt/include/mitkRESTServerMicroServiceQt.h @@ -1,77 +1,68 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -#ifndef mitkRESTServerMicroService_h -#define mitkRESTServerMicroService_h +#ifndef mitkRESTServerMicroServiceQt_h +#define mitkRESTServerMicroServiceQt_h #include -#include "cpprest/http_listener.h" - -#include "MitkCppRestSdkExports.h" -#include -#include -#include -#include +#include typedef web::http::experimental::listener::http_listener MitkListener; typedef web::http::http_request MitkRequest; typedef web::http::http_response MitkResponse; typedef web::http::methods MitkRESTMethods; typedef web::http::status_codes MitkRestStatusCodes; typedef web::json::json_exception MitkJsonException; namespace mitk { - class RESTServerMicroService : public QObject + class RESTServerMicroServiceQt : public QObject, public IRESTServerMicroService { Q_OBJECT public: /** * @brief Creates an server listening to the given URI * * @param uri the URI at which the server is listening for requests */ - RESTServerMicroService(web::uri uri); - ~RESTServerMicroService(); + RESTServerMicroServiceQt(web::uri uri); + ~RESTServerMicroServiceQt(); - web::uri GetUri(); + web::uri GetUri() override; private: /** * @brief Handle for incoming GET requests * * @param MitkRequest incoming request object */ - void HandleGet(MitkRequest request); - - MitkListener m_Listener; - web::uri m_Uri; + void HandleGet(MitkRequest request) override; public slots: /** * @brief Opens the listener and starts the listening process */ - void OpenListener(); + void OpenListener() override; /** * @brief Closes the listener and stops the listening process */ - void CloseListener(); + void CloseListener() override; }; } // namespace mitk #endif \ No newline at end of file diff --git a/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp new file mode 100644 index 0000000000..a492835561 --- /dev/null +++ b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp @@ -0,0 +1,34 @@ +#include "mitkCppRestSdkQtActivator.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void MitkCppRestSdkQtActivator::Load(us::ModuleContext *context) +{ + // Registration of the RESTManagerMicroservice + m_RESTManagerQt.reset(new mitk::RESTManagerQt); + + us::ServiceProperties props; + if (QCoreApplication::instance()!=NULL) + { + props[us::ServiceConstants::SERVICE_RANKING()] = 10; + } + else + { + props[us::ServiceConstants::SERVICE_RANKING()] = 0; + } + context->RegisterService(m_RESTManagerQt.get(),props); +} + +void MitkCppRestSdkQtActivator::Unload(us::ModuleContext *) {} + +US_EXPORT_MODULE_ACTIVATOR(MitkCppRestSdkQtActivator) diff --git a/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.h b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.h new file mode 100644 index 0000000000..7fcdd9e51e --- /dev/null +++ b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.h @@ -0,0 +1,37 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef MITKCPPRESTSDKQTACTIVATOR_H_ +#define MITKCPPRESTSDKQTACTIVATOR_H_ + +#include + +#include +#include +#include +#include + +class MitkCppRestSdkQtActivator : public us::ModuleActivator +{ + +public: + void Load(us::ModuleContext *context) override; + void Unload(us::ModuleContext *) override; + +private: + std::unique_ptr m_RESTManagerQt; +}; +#endif diff --git a/Modules/CppRestSdk/src/mitkRESTManager.cpp b/Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp similarity index 64% copy from Modules/CppRestSdk/src/mitkRESTManager.cpp copy to Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp index 9fee438abf..144d520137 100644 --- a/Modules/CppRestSdk/src/mitkRESTManager.cpp +++ b/Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp @@ -1,228 +1,213 @@ -#include "mitkRESTManager.h" -#include +#include "mitkRESTManagerQt.h" #include -mitk::RESTManager::RESTManager() {} +#include +mitk::RESTManagerQt::RESTManagerQt() {} -mitk::RESTManager::~RESTManager() {} +mitk::RESTManagerQt::~RESTManagerQt() {} -pplx::task mitk::RESTManager::SendRequest(const web::uri &uri, +pplx::task mitk::RESTManagerQt::SendRequest(const web::uri &uri, const RequestType &type, const web::json::value &content, const utility::string_t &filePath) { pplx::task answer; auto client = new RESTClientMicroService(); - //according to the RequestType, different HTTP requests are made + // according to the RequestType, different HTTP requests are made switch (type) { case get: { if (filePath == L"") { - //no file path specified, starts a normal get request returning the normal json result + // no file path specified, starts a normal get request returning the normal json result answer = client->Get(uri); } else { - //file path ist specified, the result of the get request ist stored in this file - //and an empty json object is returned + // file path ist specified, the result of the get request ist stored in this file + // and an empty json object is returned answer = client->Get(uri, filePath); } break; } case post: { if (content == NULL) { - //warning because normally you won't create an empty ressource + // warning because normally you won't create an empty ressource MITK_WARN << "Content for put is empty, this will create an empty ressource"; } answer = client->POST(uri, content); break; } - break; + break; case put: { if (content == NULL) { - //warning because normally you won't empty a ressource + // warning because normally you won't empty a ressource MITK_WARN << "Content for put is empty, this will empty the ressource"; } - answer = client->PUT(uri,content); + answer = client->PUT(uri, content); break; } } return answer; } -void mitk::RESTManager::ReceiveRequest(const web::uri &uri, mitk::IRESTObserver *observer) +void mitk::RESTManagerQt::ReceiveRequest(const web::uri &uri, mitk::IRESTObserver *observer) { // New instance of RESTServerMicroservice in m_ServerMap, key is port of the request int port = uri.port(); // Checking if port is free to add a new Server if (m_ServerMap.count(port) == 0) { // new observer has to be added std::pair key(uri.port(), uri.path()); m_Observers[key] = observer; // testing if entry has been added to observer map utility::string_t uristringt = uri.path(); std::string uristring(uristringt.begin(), uristringt.end()); - MITK_INFO <<"[" <moveToThread(m_ServerThreadMap[port]); + // Move server to seperate Thread and create connections between threads + m_ServerThreadMap[port] = new QThread; + server->moveToThread(m_ServerThreadMap[port]); - connect(m_ServerThreadMap[port], &QThread::finished, server, &QObject::deleteLater); + connect(m_ServerThreadMap[port], &QThread::finished, server, &QObject::deleteLater); + + // starting Server + m_ServerThreadMap[port]->start(); + QMetaObject::invokeMethod(server, "OpenListener"); - // starting Server - m_ServerThreadMap[port]->start(); - QMetaObject::invokeMethod(server, "OpenListener"); - } - else - { - server->OpenListener(); - } - utility::string_t host = uri.authority().to_string(); std::string hoststring(host.begin(), host.end()); MITK_INFO << "new server" << hoststring << " at port" << port; } // If there is already a server under this port else { // Same host, means new observer but not a new server instance if (m_ServerMap[port]->GetUri() == uri.authority()) { // new observer has to be added std::pair key(uri.port(), uri.path()); - //only add a new observer if there isn't already an observer for this uri + // only add a new observer if there isn't already an observer for this uri if (m_Observers.count(key) == 0) { m_Observers[key] = observer; // testing if entry has been added to map utility::string_t uristringt = uri.path(); std::string uristring(uristringt.begin(), uristringt.end()); - MITK_INFO << "[" << uri.port() << ", " << uristring<< "] : Number of elements in map: " << m_Observers.count(key); + MITK_INFO << "[" << uri.port() << ", " << uristring + << "] : Number of elements in map: " << m_Observers.count(key); // info output MITK_INFO << "started listening, no new server instance has been created"; } else { MITK_ERROR << "Threre is already a observer handeling this data"; } } // Error, since another server can't be added under this port else { MITK_ERROR << "There is already another server listening under this port"; } } } - -web::json::value mitk::RESTManager::Handle(const web::uri &uri, web::json::value &body) +web::json::value mitk::RESTManagerQt::Handle(const web::uri &uri, web::json::value &body) { // Checking if there is an observer for the port and path std::pair key(uri.port(), uri.path()); if (m_Observers.count(key) != 0) { MITK_INFO << "Manager: Data send to observer"; - return m_Observers[key]->Notify(body,uri); + return m_Observers[key]->Notify(body, uri); } - //No observer under this port, return null which results in status code 404 (s. RESTServerMicroService) + // No observer under this port, return null which results in status code 404 (s. RESTServerMicroService) else { MITK_WARN << "No Observer can handle the data"; return NULL; } } -void mitk::RESTManager::HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri= L"") +void mitk::RESTManagerQt::HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri = L"") { for (auto it = m_Observers.begin(); it != m_Observers.end();) { mitk::IRESTObserver *obsMap = it->second; // Check wether observer is at this place in map if (obsMap == observer) { - //Check wether it is the right uri to be deleted - if (uri==L""||it->first.second == uri.path()) + // Check wether it is the right uri to be deleted + if (uri == L"" || it->first.second == uri.path()) { // if yes // 1. store port and path in a temporary variable // (path is only needed to create a key for info output) int port = it->first.first; utility::string_t path = it->first.second; std::pair key(port, path); MITK_INFO << "Number of elements at key [ " << port << ", " << std::string(key.second.begin(), key.second.end()) << "]: " << m_Observers.count(key); // 2. delete map entry it = m_Observers.erase(it); MITK_INFO << "Number of elements at key [ " << port << ", " << std::string(key.second.begin(), key.second.end()) << "]: " << m_Observers.count(key); // 3. check, if there is another observer under this port in observer map (with bool flag) bool noObserverForPort = true; for (auto o : m_Observers) { if (o.first.first == port) { // there still exists an observer for this port noObserverForPort = false; } } if (noObserverForPort) { // there isn't an observer at this port, delete m_ServerMap entry for this port // close listener - if (QCoreApplication::instance() != NULL) - { - QMetaObject::invokeMethod(m_ServerMap[port], "CloseListener"); - // end thread - m_ServerThreadMap[port]->quit(); - m_ServerThreadMap[port]->wait(); - } - else - { - m_ServerMap[port]->CloseListener(); - m_ServerMap[port]->~RESTServerMicroService(); - } + QMetaObject::invokeMethod(dynamic_cast(m_ServerMap[port]), "CloseListener"); + // end thread + m_ServerThreadMap[port]->quit(); + m_ServerThreadMap[port]->wait(); + // delete server from map m_ServerMap.erase(port); } - } + } else { ++it; } } else { ++it; } } } -std::map mitk::RESTManager::GetM_ServerMap() +std::map mitk::RESTManagerQt::GetM_ServerMap() { return m_ServerMap; } -std::map, mitk::IRESTObserver *> mitk::RESTManager::GetM_Observers() +std::map, mitk::IRESTObserver *> mitk::RESTManagerQt::GetM_Observers() { return m_Observers; -} - +} \ No newline at end of file diff --git a/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp b/Modules/CppRestSdkQt/src/mitkRESTServerMicroServiceQt.cpp similarity index 53% copy from Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp copy to Modules/CppRestSdkQt/src/mitkRESTServerMicroServiceQt.cpp index 1332e2d3c7..5e7fe5e64b 100644 --- a/Modules/CppRestSdk/src/mitkRESTServerMicroService.cpp +++ b/Modules/CppRestSdkQt/src/mitkRESTServerMicroServiceQt.cpp @@ -1,73 +1,71 @@ -#include "mitkRESTServerMicroService.h" +#include "mitkRESTServerMicroServiceQt.h" #include -mitk::RESTServerMicroService::RESTServerMicroService(web::uri uri) : m_Listener(uri) +mitk::RESTServerMicroServiceQt::RESTServerMicroServiceQt(web::uri uri) { m_Uri = uri; } -mitk::RESTServerMicroService::~RESTServerMicroService() -{ -} +mitk::RESTServerMicroServiceQt::~RESTServerMicroServiceQt() {} -void mitk::RESTServerMicroService::OpenListener() +void mitk::RESTServerMicroServiceQt::OpenListener() { - //create listener - m_Listener = MitkListener(m_Uri); - //Connect incoming get requests with HandleGet method - m_Listener.support(web::http::methods::GET, - std::bind(&mitk::RESTServerMicroService::HandleGet, this, std::placeholders::_1)); - //open listener - m_Listener.open().wait(); + // create listener + m_Listener = MitkListener(m_Uri); + // Connect incoming get requests with HandleGet method + m_Listener.support(web::http::methods::GET, + std::bind(&mitk::RESTServerMicroServiceQt::HandleGet, this, std::placeholders::_1)); + // open listener + m_Listener.open().wait(); } -void mitk::RESTServerMicroService::CloseListener() +void mitk::RESTServerMicroServiceQt::CloseListener() { - //close listener + // close listener m_Listener.close().wait(); } -web::uri mitk::RESTServerMicroService::GetUri() +web::uri mitk::RESTServerMicroServiceQt::GetUri() { return m_Uri; } -void mitk::RESTServerMicroService::HandleGet(MitkRequest request) +void mitk::RESTServerMicroServiceQt::HandleGet(MitkRequest request) { int port = m_Listener.uri().port(); - //getting exact request uri has to be a parameter in handle function + // getting exact request uri has to be a parameter in handle function web::uri_builder build(m_Listener.uri()); build.append(request.absolute_uri()); utility::string_t uriStringT = build.to_uri().to_string(); std::string uriString(uriStringT.begin(), uriStringT.end()); MITK_INFO << "Get Request fot server at port " << port << " Exact request uri: " << uriString; - + web::json::value content; - //get RESTManager as microservice to call th Handle method of the manager + // get RESTManager as microservice to call th Handle method of the manager us::ModuleContext *context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { web::json::value data = request.extract_json().get(); MITK_INFO << "Server: Data send to manager"; - //call the handle method + // call the handle method content = managerService->Handle(build.to_uri(), data); MITK_INFO << "server: Data received from manager"; } } - if (content!=NULL) + if (content != NULL) { - //content handled by observer + // content handled by observer request.reply(MitkRestStatusCodes::OK, content); } else { - //no observer to handle data + // no observer to handle data request.reply(MitkRestStatusCodes::NotFound); } } \ No newline at end of file diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake index 544e5909ec..c807a7fca4 100644 --- a/Modules/ModuleList.cmake +++ b/Modules/ModuleList.cmake @@ -1,84 +1,85 @@ # The entries in the mitk_modules list must be # ordered according to their dependencies. set(MITK_MODULES Core CommandLine AppUtil RDF LegacyIO DataTypesExt Annotation LegacyGL AlgorithmsExt MapperExt DICOMReader DICOMReaderServices DICOMQI DICOMTesting SceneSerializationBase PlanarFigure ImageDenoising ImageExtraction SceneSerialization Gizmo GraphAlgorithms Multilabel ImageStatistics ContourModel SurfaceInterpolation Segmentation PlanarFigureSegmentation QtWidgets QtWidgetsExt Chart SegmentationUI MatchPointRegistration MatchPointRegistrationUI Classification GPGPU OpenIGTLink IGTBase IGT CameraCalibration OpenCL OpenCVVideoSupport QtOverlays ToFHardware ToFProcessing ToFUI PhotoacousticsHardware PhotoacousticsAlgorithms PhotoacousticsLib US USUI DicomUI Remeshing Python QtPython Persistence OpenIGTLinkUI IGTUI DicomRT RTUI IOExt XNAT TubeGraph BiophotonicsHardware DiffusionImaging TumorInvasionAnalysis BoundingShape RenderWindowManager RenderWindowManagerUI CEST BasicImageProcessing ModelFit ModelFitUI Pharmacokinetics PharmacokineticsUI CppRestSdk + CppRestSdkQt ) if(MITK_ENABLE_PIC_READER) list(APPEND MITK_MODULES IpPicSupportIO) endif() diff --git a/Plugins/org.mitk.gui.qt.client/CMakeLists.txt b/Plugins/org.mitk.gui.qt.client/CMakeLists.txt index f5afc5a21e..1a0d308e85 100644 --- a/Plugins/org.mitk.gui.qt.client/CMakeLists.txt +++ b/Plugins/org.mitk.gui.qt.client/CMakeLists.txt @@ -1,7 +1,7 @@ project(org_mitk_gui_qt_client) mitk_create_plugin( EXPORT_DIRECTIVE THREAD_EXPORT EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS PRIVATE MitkQtWidgets MitkCppRestSdk + MODULE_DEPENDS PRIVATE MitkQtWidgets MitkCppRestSdkQt ) diff --git a/Plugins/org.mitk.gui.qt.thread/CMakeLists.txt b/Plugins/org.mitk.gui.qt.thread/CMakeLists.txt index 85d40e1438..e954205762 100644 --- a/Plugins/org.mitk.gui.qt.thread/CMakeLists.txt +++ b/Plugins/org.mitk.gui.qt.thread/CMakeLists.txt @@ -1,7 +1,7 @@ project(org_mitk_gui_qt_thread) mitk_create_plugin( EXPORT_DIRECTIVE THREAD_EXPORT EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS PRIVATE MitkQtWidgets MitkCppRestSdk + MODULE_DEPENDS PRIVATE MitkQtWidgets MitkCppRestSdkQt )