diff --git a/Modules/CppRestSdk/src/mitkRESTClient.cpp b/Modules/CppRestSdk/src/mitkRESTClient.cpp index 3d649db4ea..0841f41933 100644 --- a/Modules/CppRestSdk/src/mitkRESTClient.cpp +++ b/Modules/CppRestSdk/src/mitkRESTClient.cpp @@ -1,210 +1,210 @@ #include "mitkRESTClient.h" #include "mitkRESTUtil.h" #include mitk::RESTClient::RESTClient() {} mitk::RESTClient::~RESTClient() {} pplx::task mitk::RESTClient::Get(const web::uri &uri) { //Create new HTTP client MitkClient *client = new MitkClient(uri); MITK_INFO << "Calling GET with " << mitk::RESTUtil::convertToUtf8(uri.path()) << " on client " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()); //create get request MitkRequest getRequest(MitkRESTMethods::GET); //make request return client->request(getRequest).then([=](pplx::task responseTask) { try { //get response of the request MitkResponse response = responseTask.get(); auto status = response.status_code(); MITK_INFO << " status: " << status; - if (status != MitkRestStatusCodes::OK) + if (MitkRestStatusCodes::OK != status) { //throw if something went wrong (e.g. invalid uri) //this exception can be handled by client mitkThrow() << "response was not OK"; } try { //parse content type to application/json if it isn't already //this is important if the content type is e.g. application/dicom+json utility::string_t requestContentType = response.headers().content_type(); - if (requestContentType != L"application/json") + if (L"application/json" != requestContentType) { response.headers().set_content_type(L"application/json"); } //return json answer return response.extract_json().get(); } catch (...) { mitkThrow() << "extracting json went wrong"; } } catch (...) { mitkThrow() << "getting response went wrong"; } }); } pplx::task mitk::RESTClient::Get(const web::uri &uri, const utility::string_t &filePath) { // Create new HTTP client MitkClient *client = new MitkClient(uri); MITK_INFO << "Calling GET with " << mitk::RESTUtil::convertToUtf8(uri.path()) << " on client " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()) << " save into " << mitk::RESTUtil::convertToUtf8(filePath); //create new file buffer auto fileBuffer = std::make_shared>(); // create get request MitkRequest getRequest(MitkRESTMethods::GET); //open file stream for the specified file path return concurrency::streams::file_buffer::open(filePath, std::ios::out) .then([=](concurrency::streams::streambuf outFile) -> pplx::task { *fileBuffer = outFile; //make the get request return client->request(MitkRESTMethods::GET); }) // Write the response body into the file buffer. .then([=](MitkResponse response) -> pplx::task { auto status = response.status_code(); MITK_DEBUG << "Status code: " << status; - if (status != web::http::status_codes::OK) + if (web::http::status_codes::OK != status) { // throw if something went wrong (e.g. invalid uri) // this exception can be handled by client mitkThrow() << "GET ended up with response " << mitk::RESTUtil::convertToUtf8(response.to_string()); } return response.body().read_to_end(*fileBuffer); }) // Close the file buffer. .then([=](size_t) { return fileBuffer->close(); }) .then([=]() { //return empty json object web::json::value data; return data; }); } pplx::task mitk::RESTClient::Put(const web::uri &uri, const web::json::value *content) { // Create new HTTP client MitkClient *client = new MitkClient(uri); MITK_INFO << "Calling PUT with " << mitk::RESTUtil::convertToUtf8(uri.path()) << " on client " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()); // create put request MitkRequest putRequest(MitkRESTMethods::PUT); //set body of the put request with data given by client - if (content != nullptr) + if (nullptr != content) { putRequest.set_body(*content); } //make put request return client->request(putRequest).then([=](pplx::task responseTask) { try { // get response of the request MitkResponse response = responseTask.get(); auto status = response.status_code(); MITK_INFO << " status: " << status; - if (status != MitkRestStatusCodes::OK) + if (MitkRestStatusCodes::OK != status) { // throw if something went wrong (e.g. invalid uri) // this exception can be handled by client mitkThrow() << "response was not OK"; } try { // parse content type to application/json if it isn't already // this is important if the content type is e.g. application/dicom+json utility::string_t requestContentType = response.headers().content_type(); - if (requestContentType != L"application/json") + if (L"application/json" != requestContentType) { response.headers().set_content_type(L"application/json"); } // return json answer return response.extract_json().get(); } catch (...) { mitkThrow() << "extracting json went wrong"; } } catch (...) { mitkThrow() << "getting response went wrong"; } }); } pplx::task mitk::RESTClient::Post(const web::uri &uri, const web::json::value *content) { // Create new HTTP client MitkClient *client = new MitkClient(uri); MITK_INFO << "Calling POST with " << mitk::RESTUtil::convertToUtf8(uri.path()) << " on client " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()); // Create post request MitkRequest postRequest(MitkRESTMethods::POST); // set body of the put request with data given by client - if (content != nullptr) + if (nullptr != content) { postRequest.set_body(*content); } //make post request return client->request(postRequest).then([=](pplx::task responseTask) { try { // get response of the request MitkResponse response = responseTask.get(); auto status = response.status_code(); MITK_INFO << " status: " << status; - if (status != MitkRestStatusCodes::Created) + if (MitkRestStatusCodes::Created != status) { // throw if something went wrong (e.g. invalid uri) // this exception can be handled by client mitkThrow() << "response was not Created"; } try { // parse content type to application/json if it isn't already // this is important if the content type is e.g. application/dicom+json utility::string_t requestContentType = response.headers().content_type(); - if (requestContentType != L"application/json") + if (L"application/json" != requestContentType) { response.headers().set_content_type(L"application/json"); } // return json answer return response.extract_json().get(); } catch (...) { mitkThrow() << "extracting json went wrong"; } } catch(...) { mitkThrow() << "getting response went wrong"; } }); } diff --git a/Modules/CppRestSdk/src/mitkRESTManager.cpp b/Modules/CppRestSdk/src/mitkRESTManager.cpp index 34683eafa3..3c9694edc2 100644 --- a/Modules/CppRestSdk/src/mitkRESTManager.cpp +++ b/Modules/CppRestSdk/src/mitkRESTManager.cpp @@ -1,212 +1,212 @@ #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 RESTClient(); // according to the RequestType, different HTTP requests are made switch (type) { case RequestType::Get: if (filePath.empty()) { // 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 RequestType::Post: //TODO fixen wert vorne bei vergleich - if (content == nullptr) + if (nullptr == content) { // 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; case RequestType::Put: - if (content == nullptr) + if (nullptr == content) { // 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; //TODO: default hinzufügen } return answer; } void mitk::RESTManager::ReceiveRequest(const web::uri &uri, mitk::IRESTObserver *observer) { // New instance of RESTServer 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) + if (0 == m_ServerMap.count(port)) { this->AddObserver(uri, observer); // creating server instance auto server = new RESTServer(uri.authority()); // add reference to server instance to map m_ServerMap[port] = server; // start Server server->OpenListener(); MITK_INFO << "new server " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()) << " at port " << port; } // If there is already a server under this port else { //TODO umbenennen this->ServerUnderPort(uri, observer); } } web::json::value mitk::RESTManager::Handle(const web::uri &uri, const 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) + if (0 != m_Observers.count(key)) { //TODO Ausgaben minimieren 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. RESTServer) 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) + if (observer == obsMap) { // Check wether it is the right uri to be deleted - if (uri.is_empty() || it->first.second == uri.path()) + if (uri.is_empty() || uri.path() == it->first.second) { int port = it->first.first; bool noObserverForPort = this->DeleteObserver(it, uri); if (noObserverForPort) { // there isn't an observer at this port, delete m_ServerMap entry for this port // close listener m_ServerMap[port]->CloseListener(); delete m_ServerMap[port]; // delete server from map m_ServerMap.erase(port); } } else { ++it; } } else { ++it; } } } const std::map &mitk::RESTManager::GetServerMap() { return m_ServerMap; } const std::map, mitk::IRESTObserver *> &mitk::RESTManager::GetObservers() { return m_Observers; } void mitk::RESTManager::AddObserver(const web::uri &uri, IRESTObserver *observer) { // 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 MITK_INFO << "[" << uri.port() << ", " << mitk::RESTUtil::convertToUtf8(uri.path()) << "] : Number of elements in map: " << m_Observers.count(key); } void mitk::RESTManager::ServerUnderPort(const web::uri &uri, IRESTObserver *observer) { // Same host, means new observer but not a new server instance - if (m_ServerMap[uri.port()]->GetUri() == uri.authority()) + if (uri.authority() == m_ServerMap[uri.port()]->GetUri()) { // 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) + if (0 == m_Observers.count(key)) { this->AddObserver(uri, observer); // 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"; } } bool mitk::RESTManager::DeleteObserver(std::map, IRESTObserver *>::iterator &it, const web::uri &uri) { // 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 << ", " << mitk::RESTUtil::convertToUtf8(key.second) << "]: " << m_Observers.count(key); // 2. delete map entry it = m_Observers.erase(it); MITK_INFO << "Number of elements at key [ " << port << ", " << mitk::RESTUtil::convertToUtf8(key.second) << "]: " << m_Observers.count(key); // 3. check, if there is another observer under this port in observer map (with bool flag) for (auto o : m_Observers) { - if (o.first.first == port) + if (port == o.first.first) { // there still exists an observer for this port return false; } } return true; } diff --git a/Modules/CppRestSdk/test/mitkRESTClientTest.cpp b/Modules/CppRestSdk/test/mitkRESTClientTest.cpp index a6d689f70f..b4681fda9e 100644 --- a/Modules/CppRestSdk/test/mitkRESTClientTest.cpp +++ b/Modules/CppRestSdk/test/mitkRESTClientTest.cpp @@ -1,282 +1,282 @@ /*=================================================================== 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 "mitkRESTClient.h" // VTK includes #include #include "mitkIRESTManager.h" #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(const web::json::value &data, const web::uri &uri) override { MITK_INFO << "Observer: Data in observer"; web::json::value returnData = data; returnData[L"userId"] = web::json::value(1); returnData[L"id"] = web::json::value(1); returnData[L"title"] = web::json::value(U("this is a title")); returnData[L"body"] = web::json::value(U("this is a body")); return returnData; } /** * @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; //TODO: data als memebrvariable/ in setup/ in methode 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 //TODO: vector konstruktoren anschauen / emplace_back 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); + CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == *count); } 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/test/mitkRESTServerTest.cpp b/Modules/CppRestSdk/test/mitkRESTServerTest.cpp index bb3507f131..f4b72c9126 100644 --- a/Modules/CppRestSdk/test/mitkRESTServerTest.cpp +++ b/Modules/CppRestSdk/test/mitkRESTServerTest.cpp @@ -1,263 +1,263 @@ /*=================================================================== 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 "mitkRESTServer.h" // VTK includes #include class mitkRESTServerTestSuite : public mitk::TestFixture, mitk::IRESTObserver { CPPUNIT_TEST_SUITE(mitkRESTServerTestSuite); MITK_TEST(OpenListener_Succeed); MITK_TEST(TwoListenerSameHostSamePort_OnlyOneOpened); MITK_TEST(CloseListener_Succeed); MITK_TEST(OpenMultipleListenerCloseOne_Succeed); MITK_TEST(OpenMultipleListenerCloseAll_Succeed); MITK_TEST(OpenListenerGetRequestSamePath_ReturnExpectedJSON); MITK_TEST(CloseListener_NoRequestPossible); MITK_TEST(OpenListenerGetRequestDifferentPath_ReturnNotFound); MITK_TEST(OpenListenerCloseAndReopen_Succeed); CPPUNIT_TEST_SUITE_END(); public: mitk::IRESTManager *m_Service; web::json::value m_Data; //TODO: bei Notify uri parameter zuerst //TODO: data als const ref web::json::value Notify(const web::json::value &data, const web::uri &uri) override { MITK_INFO << "Observer: Data in observer"; web::json::value returnData = data; returnData[L"userId"] = web::json::value(1); returnData[L"id"] = web::json::value(1); returnData[L"title"] = web::json::value(U("this is a title")); returnData[L"body"] = web::json::value(U("this is a body")); return returnData; } /** * @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 { m_Data[L"userId"] = web::json::value(1); m_Data[L"id"] = web::json::value(1); m_Data[L"title"] = web::json::value(U("this is a title")); m_Data[L"body"] = web::json::value(U("this is a body")); us::ServiceReference serviceRef = us::GetModuleContext()->GetServiceReference(); if (serviceRef) { m_Service = us::GetModuleContext()->GetService(serviceRef); } //TODO: if(m_Service) überprüfen, exception wenn nicht } void tearDown() override { m_Service->HandleDeleteObserver(this); } void OpenListener_Succeed() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } - CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", m_Service->GetObservers().size() == 1); - CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", m_Service->GetServerMap().size() == 1); + CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", 1 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", 1 == m_Service->GetServerMap().size()); } void TwoListenerSameHostSamePort_OnlyOneOpened() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); m_Service->ReceiveRequest(L"http://localhost:8080/example", this); } CPPUNIT_ASSERT_MESSAGE("Open two listener with a different path,same host, same port, observer map size is two", - m_Service->GetObservers().size() == 2); + 2 == m_Service->GetObservers().size()); CPPUNIT_ASSERT_MESSAGE("Open two listener with a different path,same host, same port, server map size is one", - m_Service->GetServerMap().size() == 1); + 1 == m_Service->GetServerMap().size()); } void CloseListener_Succeed() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } - CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", m_Service->GetObservers().size() == 1); - CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", m_Service->GetServerMap().size() == 1); + CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", 1 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", 1 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->HandleDeleteObserver(this); } - CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", m_Service->GetObservers().size() == 0); - CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", m_Service->GetServerMap().size() == 0); + CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", 0 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", 0 == m_Service->GetServerMap().size()); } void OpenMultipleListenerCloseOne_Succeed() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); m_Service->ReceiveRequest(L"http://localhost:8090/example", this); } - CPPUNIT_ASSERT_MESSAGE("Open two listener, observer map size is two", m_Service->GetObservers().size() == 2); - CPPUNIT_ASSERT_MESSAGE("Open two listener, server map size is two", m_Service->GetServerMap().size() == 2); + CPPUNIT_ASSERT_MESSAGE("Open two listener, observer map size is two", 2 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open two listener, server map size is two", 2 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->HandleDeleteObserver(this, L"http://localhost:8080/test"); } CPPUNIT_ASSERT_MESSAGE("Closed one of two listeners, observer map is size is one", - m_Service->GetObservers().size() == 1); + 1 == m_Service->GetObservers().size()); CPPUNIT_ASSERT_MESSAGE("Closed one of two listener, server map size is one", - m_Service->GetServerMap().size() == 1); + 1 == m_Service->GetServerMap().size()); } void OpenMultipleListenerCloseAll_Succeed() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); m_Service->ReceiveRequest(L"http://localhost:8090/example", this); } - CPPUNIT_ASSERT_MESSAGE("Open two listener, observer map size is two", m_Service->GetObservers().size() == 2); - CPPUNIT_ASSERT_MESSAGE("Open two listener, server map size is two", m_Service->GetServerMap().size() == 2); + CPPUNIT_ASSERT_MESSAGE("Open two listener, observer map size is two", 2 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open two listener, server map size is two", 2 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->HandleDeleteObserver(this); } - CPPUNIT_ASSERT_MESSAGE("Closed all listeners, observer map is empty", m_Service->GetObservers().size() == 0); - CPPUNIT_ASSERT_MESSAGE("Closed all listeners, server map is empty", m_Service->GetServerMap().size() == 0); + CPPUNIT_ASSERT_MESSAGE("Closed all listeners, observer map is empty", 0 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Closed all listeners, server map is empty", 0 == m_Service->GetServerMap().size()); } void OpenListenerGetRequestSamePath_ReturnExpectedJSON() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } 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("Opened listener and send request to same uri, returned expected JSON", *result == data); } void RequestToClosedListener() { web::json::value *result = new web::json::value(); if (m_Service) { m_Service->SendRequest(L"http://localhost:8080/test") .then([=](pplx::task resultTask) { *result = resultTask.get(); }) .wait(); } } void CloseListener_NoRequestPossible() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } - CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", m_Service->GetObservers().size() == 1); - CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", m_Service->GetServerMap().size() == 1); + CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", 1 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", 1 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->HandleDeleteObserver(this); } - CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", m_Service->GetObservers().size() == 0); - CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", m_Service->GetServerMap().size() == 0); + CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", 0 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", 0 == m_Service->GetServerMap().size()); CPPUNIT_ASSERT_THROW(RequestToClosedListener(), mitk::Exception); } void RequestToDifferentPathNotFound() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } 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/example") .then([=](pplx::task resultTask) { *result = resultTask.get(); }) .wait(); } } void OpenListenerGetRequestDifferentPath_ReturnNotFound() { CPPUNIT_ASSERT_THROW(RequestToDifferentPathNotFound(), mitk::Exception); } void OpenListenerCloseAndReopen_Succeed() { if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } - CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", m_Service->GetObservers().size() == 1); - CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", m_Service->GetServerMap().size() == 1); + CPPUNIT_ASSERT_MESSAGE("Open one listener, observer map size is one", 1 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Open one listener, server map size is one", 1 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->HandleDeleteObserver(this); } - CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", m_Service->GetObservers().size() == 0); - CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", m_Service->GetServerMap().size() == 0); + CPPUNIT_ASSERT_MESSAGE("Closed listener, observer map is empty", 0 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Closed listener, server map is empty", 0 == m_Service->GetServerMap().size()); if (m_Service) { m_Service->ReceiveRequest(L"http://localhost:8080/test", this); } - CPPUNIT_ASSERT_MESSAGE("Reopened listener, observer map size is one", m_Service->GetObservers().size() == 1); - CPPUNIT_ASSERT_MESSAGE("Reopened listener, server map size is one", m_Service->GetServerMap().size() == 1); + CPPUNIT_ASSERT_MESSAGE("Reopened listener, observer map size is one", 1 == m_Service->GetObservers().size()); + CPPUNIT_ASSERT_MESSAGE("Reopened listener, server map size is one", 1 == m_Service->GetServerMap().size()); } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTServer) \ No newline at end of file diff --git a/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp index f7ebbcdf7f..8e09a26401 100644 --- a/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp +++ b/Modules/CppRestSdkQt/src/mitkCppRestSdkQtActivator.cpp @@ -1,31 +1,31 @@ #include "mitkCppRestSdkQtActivator.h" #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!=nullptr) + if (nullptr != QCoreApplication::instance) { 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/mitkRESTManagerQt.cpp b/Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp index 25ae777faa..3505dd7057 100644 --- a/Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp +++ b/Modules/CppRestSdkQt/src/mitkRESTManagerQt.cpp @@ -1,80 +1,80 @@ #include "mitkRESTManagerQt.h" #include #include mitk::RESTManagerQt::RESTManagerQt() {} mitk::RESTManagerQt::~RESTManagerQt() {} void mitk::RESTManagerQt::ReceiveRequest(const web::uri &uri, mitk::IRESTObserver *observer) { // New instance of RESTServer 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) + if (0 == m_ServerMap.count(port)) { mitk::RESTManager::AddObserver(uri, observer); // creating server instance auto server = new RESTServerQt(uri.authority()); // add reference to server instance to map m_ServerMap[port] = server; // 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"); MITK_INFO << "new server " << mitk::RESTUtil::convertToUtf8(uri.authority().to_string()) << " at port " << port; } // If there is already a server under this port else { mitk::RESTManager::ServerUnderPort(uri, observer); } } 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) + if (observer == obsMap) { // Check wether it is the right uri to be deleted - if (uri.is_empty() || it->first.second == uri.path()) + if (uri.is_empty() || uri.path() == it->first.second) { int port = it->first.first; bool noObserverForPort = mitk::RESTManager::DeleteObserver(it, uri); if (noObserverForPort) { // there isn't an observer at this port, delete m_ServerMap entry for this port // close listener QMetaObject::invokeMethod(static_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; } } }