diff --git a/Modules/REST/documentation/REST.dox b/Modules/REST/documentation/REST.dox index 34eab399f7..1d467e93c6 100644 --- a/Modules/REST/documentation/REST.dox +++ b/Modules/REST/documentation/REST.dox @@ -1,194 +1,194 @@ /** \page RESTModule The MITK REST Module \tableofcontents \section REST_brief Description The MITK REST Module is able to manage REST requests. The main class is the RESTManager. It is a MicroServices which can be accessed via \code{.cpp} auto *context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { //call the function you need from the service } } \endcode \subsection REST_Technical Technical background The module uses the Microsoft C++ REST SDK for REST mechanisms as well as JSON convertion and asynchronic programming. \section Use_REST How to use the REST Module You can use the REST module from two different perspectives in MITK:
  1. The Server view (receive requests from clients)
  2. The Client view (send requests to servers)
The following sections will give you an introduction on how to use which of those roles: \subsection Server_Use Use from a Server perspective To act as a server, you need to implement the IRESTObserver, which has a Notify() method that has to be implemented. In this Notify() method you specify how you want to react to incoming requests and with which data you want to respond to the requests. You can then start listening for requests from clients as shown below: \code{.cpp} auto *context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { managerService->ReceiveRequests(uri /*specify your uri which you want to receive requests for*/, this); } } \endcode If a client sends a request, the Notify method is called and a response is sent. By now, only GET-requests from clients are supported. If you want to stop listening for requests you can do this by calling \code{.cpp} auto *context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { managerService->HandleDeleteObserver(this, uri); } } \endcode You don't have to specify a uri in the HandleDeleteObserver method, if you only call managerService->HandleDeleteObserver(this);, all uris you receive requests for are deleted and you aren't listening to any requests anymore. \subsection Client_Use Use from a Client perspective The following example shows how to send requests from a client perspective: \code{.cpp} //Get the microservice auto *context = us::ModuleRegistry::GetModule(1)->GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { //Call the send request method which starts the actual request managerService - ->SendRequest(_XPLATSTR("https://jsonplaceholder.typicode.com/posts/1")) + ->SendRequest(U("https://jsonplaceholder.typicode.com/posts/1")) .then([=](pplx::task resultTask)/*It is important to use task-based continuation*/ { try { //Get the result of the request //This will throw an exception if the ascendent task threw an exception (e.g. invalid URI) web::json::value result = resultTask.get(); //Do something with the result (e.g. convert it to a QString to update an UI element) utility::string_t stringT = result.to_string(); std::string stringStd(stringT.begin(), stringT.end()); QString stringQ = QString::fromStdString(stringStd); //Note: if you want to update your UI, do this by using signals and slots. //The UI can't be updated from a Thread different to the Qt main thread emit UpdateLabel(stringQ); } catch (const mitk::Exception &exception) { //Exceptions from ascendent tasks are catched here MITK_ERROR << exception.what(); return; } }); } } \endcode The steps you need to make are the following:
  1. Get the microservice. You can get the microservice via the module context. If you want to use the microservice within a plug-in, you need to get the module context from the us::ModuleRegistry.
  2. Call the SendRequest method. This will start the request itself and is performed asynchronously. As soon as the response is sent by the server, the .then(...) block is executed.
  3. Choose parameters for .then(...) block. For exception handling, it is important to choose pplx::task . This is a task-based continuation. For more information, visit https://docs.microsoft.com/en-us/cpp/parallel/concrt/exception-handling-in-the-concurrency-runtime?view=vs-2017.
  4. Get the result of the request. You can get the JSON-value of the result by callint .get(). At this point, an exception is thrown if something in the previous tasks threw an exception.
  5. Do something with the result. \note If you want to modify GUI elements within the .then(...) block, you need to do this by using signals and slots because GUI elements can only be modified by th Qt Main Thread. For more information, visit https://doc.qt.io/Qt-5/thread-basics.html#gui-thread-and-worker-thread
  6. Exception handling. Here you can define the behaviour if an exception is thrown, exceptions from ascendent tasks are also catched here.
Code, which is followed by this codeblock shown above will be performed asynchronously while waiting for the result. Besides Get-Requests, you can also perform Put or Post requests by specifying a RequestType in the SendRequest method. The following example shows, how you can perform multiple tasks, encapsulated to one joined task. The steps are based on the example for one request and only the specific steps for encapsulation are described. \code{.cpp} //Get the microservice //Get microservice auto *context = us::ModuleRegistry::GetModule(1)->GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto managerService = context->GetService(managerRef); if (managerService) { //Create multiple tasks e.g. as shown below std::vector> tasks; for (int i = 0; i < 20; i++) { pplx::task singleTask = managerService->SendRequest(L"https://jsonplaceholder.typicode.com/posts/1") .then([=](pplx::task resultTask) { //Do something when a single task is done try { resultTask.get(); emit UpdateProgressBar(); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); tasks.emplace_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(); emit UpdateLabel("All tasks finished"); } catch (const mitk::Exception &exception) { MITK_ERROR << exception.what(); return; } }); } \endcode The steps you need to make are the following:
  1. Get the microservice. See example above.
  2. Create multiple tasks. In this example, 20 identical tasks are created and are saved into a vector. In general, it is possible to place any tasks in that vector.
  3. Do something when a single task is done. Here, an action is performed if a single tasks is finished. In this example, a progress bar is loaded by a specific number of percent.
  4. Create a joinTask. Here, all small tasks are encapsulated in one big task.
  5. Run joinTask asynchonously. The then(...) of the joinTask is performed when all single tasks are finished.
  6. Do something when all tasks are finished. The handling of the end of a joinTask is equivalent to the end of a single tasks.
*/ diff --git a/Modules/REST/include/mitkIRESTManager.h b/Modules/REST/include/mitkIRESTManager.h index c2f71d4ef3..3da1876ec2 100644 --- a/Modules/REST/include/mitkIRESTManager.h +++ b/Modules/REST/include/mitkIRESTManager.h @@ -1,99 +1,137 @@ /*=================================================================== 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 #include +#include #include #include +#include namespace mitk { class IRESTObserver; class RESTServer; /** * @class IRESTManager * @brief This is a microservice interface for managing REST requests. */ class MITKREST_EXPORT IRESTManager { public: virtual ~IRESTManager(); /** * @brief request type for client requests by calling SendRequest */ enum class RequestType { Get, Post, Put }; /** * @brief Executes a HTTP request in the mitkRESTClient class * + * @throw mitk::Exception if RequestType is not suported * @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 headers the headers for the request (optional) * @return task to wait for */ virtual pplx::task SendRequest( + const web::uri &uri, + const RequestType &type = RequestType::Get, + const std::map headers = {}) = 0; + + /** + * @brief Executes a HTTP request in the mitkRESTClient 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 headers the headers for the request (optional) + * @param filePath the file path to store the request to (optional) + * @return task to wait for + */ + virtual pplx::task SendJSONRequest( const web::uri &uri, const RequestType &type = RequestType::Get, const web::json::value *body = nullptr, + const std::map headers = {}, const utility::string_t &filePath = {} ) = 0; + /** + * @brief Executes a HTTP request in the mitkRESTClient 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 headers the headers for the request (optional) + * @return task to wait for + */ + virtual pplx::task SendBinaryRequest(const web::uri &uri, + const RequestType &type = RequestType::Get, + const std::vector *body = {}, + const std::map headers = {}) = 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 + * @param method the http method of the request + * @param headers the http headers of the request + * @return the response */ - virtual web::json::value Handle(const web::uri &uri, const web::json::value &body) = 0; + virtual web::http::http_response Handle(const web::uri &uri, + const web::json::value &body, + const web::http::method &method, + const mitk::RESTUtil::ParamMap &headers) = 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 = {}) = 0; virtual const std::map& GetServerMap() = 0; virtual const std::map, IRESTObserver *>& GetObservers() = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IRESTManager, "org.mitk.IRESTManager") #endif diff --git a/Modules/REST/include/mitkIRESTObserver.h b/Modules/REST/include/mitkIRESTObserver.h index 9f78bbdf2b..a90e246bda 100644 --- a/Modules/REST/include/mitkIRESTObserver.h +++ b/Modules/REST/include/mitkIRESTObserver.h @@ -1,50 +1,55 @@ /*=================================================================== 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 mitkIRESTObserver_h #define mitkIRESTObserver_h #include - +#include #include #include +#include namespace mitk { class MITKREST_EXPORT IRESTObserver { public: /** * @brief Deletes an observer and calls HandleDeleteObserver() in RESTManager class * * @see HandleDeleteObserver() */ virtual ~IRESTObserver(); /** * @brief Called if there's an incoming request for the observer, observer implements how to handle request * * @param data the data of the incoming request + * @param method the http method of the incoming request * @return the modified data */ - virtual web::json::value Notify(const web::uri &uri, const web::json::value &data) = 0; + virtual web::http::http_response Notify(const web::uri &uri, + const web::json::value &data, + const web::http::method &method, + const mitk::RESTUtil::ParamMap &headers) = 0; private: }; } #endif diff --git a/Modules/REST/include/mitkRESTClient.h b/Modules/REST/include/mitkRESTClient.h index 0f52864d49..fc3c2dac42 100644 --- a/Modules/REST/include/mitkRESTClient.h +++ b/Modules/REST/include/mitkRESTClient.h @@ -1,74 +1,106 @@ /*=================================================================== 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 mitkRESTClient_h #define mitkRESTClient_h #include #include namespace mitk { class MITKREST_EXPORT RESTClient { public: + using http_request = web::http::http_request; RESTClient(); ~RESTClient(); /** * @brief Executes a HTTP GET request with the given uri and returns a task waiting for a json object * * @throw mitk::Exception if request went wrong * @param uri the URI resulting the target of the HTTP request + * @param the additional headers to be set to the HTTP request * @return task to wait for with resulting json object */ - pplx::task Get(const web::uri &uri); + pplx::task Get(const web::uri &uri, const std::map headers); /** * @brief Executes a HTTP GET request with the given uri and and stores the byte stream in a file given by the * filePath * * @throw mitk::Exception if request went wrong * @param uri the URI resulting the target of the HTTP request + * @param the additional headers to be set to 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); + pplx::task Get(const web::uri &uri, + const utility::string_t &filePath, + const std::map headers); /** * @brief Executes a HTTP PUT request with given uri and the content given as json * * @throw mitk::Exception if request went wrong * @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 * * @throw mitk::Exception if request went wrong * @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 + * @param headers the additional headers to be set to the HTTP request * @return task to wait for with resulting json object */ - pplx::task Post(const web::uri &uri, const web::json::value *content); + pplx::task Post(const web::uri &uri, + const web::json::value *content, + const std::map headers); + + /** + * @brief Executes a HTTP POST request with given uri and the content given as json + * + * @throw mitk::Exception if request went wrong + * @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 + * @param headers the additional headers to be set to the HTTP request + * @return task to wait for with resulting json object + */ + pplx::task Post(const web::uri &uri, + const std::vector *content, + const std::map headers); + + private: + /** + * @brief Use this to create and init a new request with the given headers. If needed, set the body on the resulting + * request object to avoid an automatic change of the content type header when setting the body first. + */ + http_request InitRequest(const std::map headers); + + pplx::task ExecutePost(const web::uri &uri, http_request request); + web::http::client::http_client_config m_ClientConfig; }; -} +} // namespace mitk #endif diff --git a/Modules/REST/include/mitkRESTUtil.h b/Modules/REST/include/mitkRESTUtil.h index 4abc640f96..fdc16c0a19 100644 --- a/Modules/REST/include/mitkRESTUtil.h +++ b/Modules/REST/include/mitkRESTUtil.h @@ -1,46 +1,51 @@ /*=================================================================== 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 mitkRESTUtil_h #define mitkRESTUtil_h #include #include +#include + namespace mitk { class MITKREST_EXPORT RESTUtil { public: + + typedef std::map ParamMap; + /** * @brief Converts the given std::wstring into a std::string representation */ static std::string convertToUtf8(const utility::string_t &string) { return utility::conversions::to_utf8string(string); } /** * @brief Converts the given std::string into a std::wstring representation */ static utility::string_t convertToTString(const std::string &string) { return utility::conversions::to_string_t(string); } }; } #endif diff --git a/Modules/REST/src/mitkRESTClient.cpp b/Modules/REST/src/mitkRESTClient.cpp index e6e6f2e755..8b4fa9dd9c 100644 --- a/Modules/REST/src/mitkRESTClient.cpp +++ b/Modules/REST/src/mitkRESTClient.cpp @@ -1,162 +1,214 @@ /*=================================================================== 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. ===================================================================*/ +#include #include #include -#include -#include #include +#include using http_client = web::http::client::http_client; using http_request = web::http::http_request; using http_response = web::http::http_response; using methods = web::http::methods; using status_codes = web::http::status_codes; using file_buffer = concurrency::streams::file_buffer; using streambuf = concurrency::streams::streambuf; mitk::RESTClient::RESTClient() { + m_ClientConfig.set_validate_certificates(false); } -mitk::RESTClient::~RESTClient() -{ -} +mitk::RESTClient::~RESTClient() {} -pplx::task mitk::RESTClient::Get(const web::uri &uri) +pplx::task mitk::RESTClient::Get(const web::uri &uri, + const std::map headers) { - auto client = new http_client(uri); + auto client = new http_client(uri, m_ClientConfig); http_request request; + for (auto param : headers) + { + request.headers().add(param.first, param.second); + } + return client->request(request).then([=](pplx::task responseTask) { try { auto response = responseTask.get(); auto status = response.status_code(); if (status_codes::OK != status) + { + MITK_INFO << status; + MITK_INFO << mitk::RESTUtil::convertToUtf8(response.to_string()); mitkThrow(); - + } + auto requestContentType = response.headers().content_type(); - if (_XPLATSTR("application/json") != requestContentType) - response.headers().set_content_type(_XPLATSTR("application/json")); + if (U("application/json") != requestContentType) + response.headers().set_content_type(U("application/json")); return response.extract_json().get(); } - catch (...) + catch (std::exception &e) { + MITK_INFO << e.what(); mitkThrow() << "Getting response went wrong"; } }); } -pplx::task mitk::RESTClient::Get(const web::uri &uri, const utility::string_t &filePath) +pplx::task mitk::RESTClient::Get(const web::uri &uri, + const utility::string_t &filePath, + const std::map headers) { - auto client = new http_client(uri); + auto client = new http_client(uri, m_ClientConfig); auto fileBuffer = std::make_shared>(); http_request request; + for (auto param : headers) + { + request.headers().add(param.first, param.second); + } + // Open file stream for the specified file path return file_buffer::open(filePath, std::ios::out) .then([=](streambuf outFile) -> pplx::task { *fileBuffer = outFile; return client->request(methods::GET); }) // Write the response body into the file buffer .then([=](http_response response) -> pplx::task { auto status = response.status_code(); if (status_codes::OK != status) mitkThrow() << "GET ended up with response " << RESTUtil::convertToUtf8(response.to_string()); - + return response.body().read_to_end(*fileBuffer); }) // Close the file buffer - .then([=](size_t) { - return fileBuffer->close(); - }) + .then([=](size_t) { return fileBuffer->close(); }) // Return empty JSON object - .then([=]() { - return web::json::value(); - }); + .then([=]() { return web::json::value(); }); } pplx::task mitk::RESTClient::Put(const web::uri &uri, const web::json::value *content) { - auto client = new http_client(uri); + auto client = new http_client(uri, m_ClientConfig); http_request request(methods::PUT); if (nullptr != content) request.set_body(*content); - + return client->request(request).then([=](pplx::task responseTask) { try { auto response = responseTask.get(); auto status = response.status_code(); if (status_codes::OK != status) mitkThrow(); // Parse content type to application/json if it isn't already. This is // important if the content type is e.g. application/dicom+json. auto requestContentType = response.headers().content_type(); - if (_XPLATSTR("application/json") != requestContentType) - response.headers().set_content_type(_XPLATSTR("application/json")); + if (U("application/json") != requestContentType) + response.headers().set_content_type(U("application/json")); return response.extract_json().get(); } - catch (...) + catch (std::exception &e) { + MITK_INFO << e.what(); mitkThrow() << "Getting response went wrong"; } }); } -pplx::task mitk::RESTClient::Post(const web::uri &uri, const web::json::value *content) +pplx::task mitk::RESTClient::Post(const web::uri &uri, + const std::vector *content, + const std::map headers) +{ + auto request = InitRequest(headers); + request.set_method(methods::POST); + + if (nullptr != content) + request.set_body(*content); + + return ExecutePost(uri, request); +} + +pplx::task mitk::RESTClient::Post(const web::uri &uri, + const web::json::value *content, + const std::map headers) { - auto client = new http_client(uri); - http_request request(methods::POST); + auto request = InitRequest(headers); + request.set_method(methods::POST); if (nullptr != content) request.set_body(*content); + return ExecutePost(uri, request); +} + +http_request mitk::RESTClient::InitRequest(const std::map headers) +{ + http_request request; + + for (auto param : headers) + { + request.headers().add(param.first, param.second); + } + return request; +} + +pplx::task mitk::RESTClient::ExecutePost(const web::uri &uri, http_request request) +{ + auto client = new http_client(uri, m_ClientConfig); return client->request(request).then([=](pplx::task responseTask) { try { auto response = responseTask.get(); auto status = response.status_code(); + auto requestContentType = response.headers().content_type(); + MITK_INFO << status; - if (status_codes::Created != status) + if (status_codes::OK != status) mitkThrow(); - // Parse content type to application/json if it isn't already. This is - // important if the content type is e.g. application/dicom+json. - auto requestContentType = response.headers().content_type(); - if (_XPLATSTR("application/json") != requestContentType) - response.headers().set_content_type(_XPLATSTR("application/json")); + MITK_INFO << mitk::RESTUtil::convertToUtf8(requestContentType); + if (U("application/json") != requestContentType) + { + auto json = web::json::value::object(); + json[U("test")] = web::json::value(17); + response.set_body(json); // use random json object in response body to perform return value (Linux Fix) + response.headers().set_content_type(U("application/json")); + } return response.extract_json().get(); } - catch(...) + catch (std::exception &e) { + MITK_INFO << e.what(); mitkThrow() << "Getting response went wrong"; } }); } diff --git a/Modules/REST/src/mitkRESTServer.cpp b/Modules/REST/src/mitkRESTServer.cpp index 5902d57a0f..13333f85d4 100644 --- a/Modules/REST/src/mitkRESTServer.cpp +++ b/Modules/REST/src/mitkRESTServer.cpp @@ -1,109 +1,113 @@ /*=================================================================== 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. ===================================================================*/ -#include - #include +#include #include #include #include using namespace std::placeholders; using http_listener = web::http::experimental::listener::http_listener; using http_request = web::http::http_request; +using http_response = web::http::http_response; using methods = web::http::methods; using status_codes = web::http::status_codes; namespace mitk { class RESTServer::Impl { public: Impl(const web::uri &uri); ~Impl(); - void HandleGet(const http_request &request); + void HandleRequest(const http_request &request); web::http::experimental::listener::http_listener listener; web::uri uri; }; - RESTServer::Impl::Impl(const web::uri &uri) - : uri{uri} - { - } + RESTServer::Impl::Impl(const web::uri &uri) : uri{uri} {} - RESTServer::Impl::~Impl() - { - } + RESTServer::Impl::~Impl() {} - void RESTServer::Impl::HandleGet(const http_request &request) + void RESTServer::Impl::HandleRequest(const http_request &request) { web::uri_builder builder(this->listener.uri()); builder.append(request.absolute_uri()); auto uriString = builder.to_uri().to_string(); - web::json::value content; + http_response response(status_codes::InternalError); + response.set_body(U("There went something wrong after receiving the request.")); auto context = us::GetModuleContext(); auto managerRef = context->GetServiceReference(); if (managerRef) { auto manager = context->GetService(managerRef); if (manager) { - auto data = request.extract_json().get(); - content = manager->Handle(builder.to_uri(), data); + // not every request contains JSON data + web::json::value data = {}; + if (request.headers().content_type() == U("application/json")) + { + data = request.extract_json().get(); + } + + mitk::RESTUtil::ParamMap headers; + auto begin = request.headers().begin(); + auto end = request.headers().end(); + + for (; begin != end; ++begin) + { + headers.insert(mitk::RESTUtil::ParamMap::value_type(begin->first, begin->second)); + } + + response = manager->Handle(builder.to_uri(), data, request.method(), headers); } } - request.reply(content.is_null() - ? status_codes::NotFound - : status_codes::OK); + request.reply(response); } -} - +} // namespace mitk -mitk::RESTServer::RESTServer(const web::uri &uri) - : m_Impl{std::make_unique(uri)} -{ -} +mitk::RESTServer::RESTServer(const web::uri &uri) : m_Impl{std::make_unique(uri)} {} -mitk::RESTServer::~RESTServer() -{ -} +mitk::RESTServer::~RESTServer() {} void mitk::RESTServer::OpenListener() { m_Impl->listener = http_listener(m_Impl->uri); - m_Impl->listener.support(methods::GET, std::bind(&Impl::HandleGet, m_Impl.get(), _1)); + m_Impl->listener.support(std::bind(&Impl::HandleRequest, m_Impl.get(), _1)); + m_Impl->listener.support(methods::OPTIONS, std::bind(&Impl::HandleRequest, m_Impl.get(), _1)); m_Impl->listener.open().wait(); } void mitk::RESTServer::CloseListener() { m_Impl->listener.close().wait(); } web::uri mitk::RESTServer::GetUri() { return m_Impl->uri; } diff --git a/Modules/REST/test/mitkRESTClientTest.cpp b/Modules/REST/test/mitkRESTClientTest.cpp index 9c4f7c0123..e1dc882fb7 100644 --- a/Modules/REST/test/mitkRESTClientTest.cpp +++ b/Modules/REST/test/mitkRESTClientTest.cpp @@ -1,247 +1,266 @@ /*=================================================================== 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. ===================================================================*/ #include #include #include #include #include +#include #include #include #include #include class mitkRESTClientTestSuite : public mitk::TestFixture, mitk::IRESTObserver { CPPUNIT_TEST_SUITE(mitkRESTClientTestSuite); - // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet? - MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish); - // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients - // MITK_TEST(PostRequestValidURI_ReturnsExpectedJSON); -- " -- - MITK_TEST(GetRequestInvalidURI_ThrowsException); - MITK_TEST(PutRequestInvalidURI_ThrowsException); - MITK_TEST(PostRequestInvalidURI_ThrowsException); + // MITK_TEST(GetRequestValidURI_ReturnsExpectedJSON); GET requests do not support content yet? + MITK_TEST(MultipleGetRequestValidURI_AllTasksFinish); + // MITK_TEST(PutRequestValidURI_ReturnsExpectedJSON); Does not work reliably on dart clients + // 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 m_Data; - web::json::value Notify(const web::uri &, const web::json::value &) override + web::http::http_response Notify(const web::uri &, + const web::json::value &, + const web::http::method &, + const mitk::RESTUtil::ParamMap &headers) override { - return m_Data; + auto response = web::http::http_response(); + response.set_body(m_Data); + response.set_status_code(web::http::status_codes::OK); + + return response; } /** * @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 = web::json::value(); - m_Data[_XPLATSTR("userId")] = web::json::value(1); - m_Data[_XPLATSTR("id")] = web::json::value(1); - m_Data[_XPLATSTR("title")] = web::json::value(U("this is a title")); - m_Data[_XPLATSTR("body")] = web::json::value(U("this is a body")); + m_Data[U("userId")] = web::json::value(1); + m_Data[U("id")] = web::json::value(1); + m_Data[U("title")] = web::json::value(U("this is a title")); + m_Data[U("body")] = web::json::value(U("this is a body")); us::ServiceReference serviceRef = us::GetModuleContext()->GetServiceReference(); if (serviceRef) { m_Service = us::GetModuleContext()->GetService(serviceRef); } if (!m_Service) { CPPUNIT_FAIL("Getting Service in setUp() failed"); } - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/clienttest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/clienttest"), this); } - void tearDown() override - { - m_Service->HandleDeleteObserver(this); - } + void tearDown() override { m_Service->HandleDeleteObserver(this); } void GetRequestValidURI_ReturnsExpectedJSON() { web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:8080/clienttest")) + m_Service->SendRequest(U("http://localhost:8080/clienttest")) .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 == m_Data); } void MultipleGetRequestValidURI_AllTasksFinish() { int count = 0; - // Create multiple tasks e.g. as shown below + // Create multiple tasks e.g. as shown below std::vector> tasks; for (int i = 0; i < 20; ++i) { - pplx::task singleTask = - m_Service->SendRequest(_XPLATSTR("http://localhost:8080/clienttest")) - .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; - } - }); + pplx::task singleTask = m_Service->SendRequest(U("http://localhost:8080/clienttest")) + .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.emplace_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) { + // 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(); + }) + .wait(); CPPUNIT_ASSERT_MESSAGE("Multiple Requests", 21 == count); } void PutRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; m_Service - ->SendRequest(_XPLATSTR("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put, &m_Data) + ->SendJSONRequest( + U("https://jsonplaceholder.typicode.com/posts/1"), mitk::IRESTManager::RequestType::Put, &web::json::value()) .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 == m_Data); } void PostRequestValidURI_ReturnsExpectedJSON() { // optional: link might get invalid or content is changed web::json::value result; web::json::value data; - data[_XPLATSTR("userId")] = m_Data[_XPLATSTR("userId")]; - data[_XPLATSTR("title")] = m_Data[_XPLATSTR("title")]; - data[_XPLATSTR("body")] = m_Data[_XPLATSTR("body")]; + data[U("userId")] = m_Data[U("userId")]; + data[U("title")] = m_Data[U("title")]; + data[U("body")] = m_Data[U("body")]; - m_Service->SendRequest(_XPLATSTR("https://jsonplaceholder.typicode.com/posts"), mitk::IRESTManager::RequestType::Post, &data) + m_Service + ->SendJSONRequest(U("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[_XPLATSTR("id")] = web::json::value(101); + data[U("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 PostRequestHeaders_Success() + { + mitk::RESTUtil::ParamMap headers; + headers.insert(mitk::RESTUtil::ParamMap::value_type( + U("Content-Type"), U("multipart/related; type=\"application/dicom\"; boundary=boundary"))); + + m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task resultTask) { + // Do something when a single task is done + try + { + resultTask.get(); + } + catch (const mitk::Exception &exception) + { + MITK_ERROR << exception.what(); + return; + } + }); + } + void GetException() { - //Method which makes a get request to an invalid uri + // Method which makes a get request to an invalid uri web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:1234/invalid")) + m_Service->SendRequest(U("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 + // Method which makes a put request to an invalid uri web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data) - .then([&](pplx::task resultTask) { - result = resultTask.get();}) + m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Put, &m_Data) + .then([&](pplx::task resultTask) { result = resultTask.get(); }) .wait(); } - void PutRequestInvalidURI_ThrowsException() - { - CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); - } + void PutRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PutException(), mitk::Exception); } void PostException() { - //Method which makes a post request to an invalid uri + // Method which makes a post request to an invalid uri web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data) - .then([&](pplx::task resultTask) { - result = resultTask.get(); - }) + m_Service->SendJSONRequest(U("http://localhost:1234/invalid"), mitk::IRESTManager::RequestType::Post, &m_Data) + .then([&](pplx::task resultTask) { result = resultTask.get(); }) .wait(); } - void PostRequestInvalidURI_ThrowsException() - { - CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); - } + void PostRequestInvalidURI_ThrowsException() { CPPUNIT_ASSERT_THROW(PostException(), mitk::Exception); } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTClient) diff --git a/Modules/REST/test/mitkRESTServerTest.cpp b/Modules/REST/test/mitkRESTServerTest.cpp index a386dba712..cf3ddd496c 100644 --- a/Modules/REST/test/mitkRESTServerTest.cpp +++ b/Modules/REST/test/mitkRESTServerTest.cpp @@ -1,227 +1,256 @@ /*=================================================================== 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. ===================================================================*/ #ifdef _WIN32 - #include +#include #endif #include #include #include #include #include #include #include #include #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); GET requests do not support content yet? - MITK_TEST(CloseListener_NoRequestPossible); - MITK_TEST(OpenListenerGetRequestDifferentPath_ReturnNotFound); - MITK_TEST(OpenListenerCloseAndReopen_Succeed); + MITK_TEST(OpenListener_Succeed); + MITK_TEST(TwoListenerSameHostSamePort_OnlyOneOpened); + MITK_TEST(CloseListener_Succeed); + MITK_TEST(OpenMultipleListenerCloseOne_Succeed); + MITK_TEST(OpenMultipleListenerCloseAll_Succeed); + // MITK_TEST(OpenListenerGetRequestSamePath_ReturnExpectedJSON); GET requests do not support content yet? + MITK_TEST(CloseListener_NoRequestPossible); + MITK_TEST(OpenListenerGetRequestDifferentPath_ReturnNotFound); + MITK_TEST(OpenListenerCloseAndReopen_Succeed); + MITK_TEST(HandleHeader_Succeed); CPPUNIT_TEST_SUITE_END(); public: mitk::IRESTManager *m_Service; web::json::value m_Data; - web::json::value Notify(const web::uri &, const web::json::value &) override + web::http::http_response Notify(const web::uri &, + const web::json::value &, + const web::http::method &, + const mitk::RESTUtil::ParamMap &headers) override { - return m_Data; + auto response = web::http::http_response(); + response.set_body(m_Data); + mitk::RESTUtil::ParamMap::const_iterator contentTypePos = headers.find(U("Content-Type")); + if (contentTypePos != headers.end() && contentTypePos->second == U("awesome/type")) + { + m_Data[U("result")] = web::json::value(U("awesome/type")); + } + + return response; } /** * @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 = web::json::value(); - m_Data[_XPLATSTR("userId")] = web::json::value(1); - m_Data[_XPLATSTR("id")] = web::json::value(1); - m_Data[_XPLATSTR("title")] = web::json::value(U("this is a title")); - m_Data[_XPLATSTR("body")] = web::json::value(U("this is a body")); + m_Data[U("userId")] = web::json::value(1); + m_Data[U("id")] = web::json::value(1); + m_Data[U("title")] = web::json::value(U("this is a title")); + m_Data[U("body")] = web::json::value(U("this is a body")); auto serviceRef = us::GetModuleContext()->GetServiceReference(); if (serviceRef) m_Service = us::GetModuleContext()->GetService(serviceRef); if (!m_Service) CPPUNIT_FAIL("Getting Service in setUp() failed"); } - void tearDown() override - { - m_Service->HandleDeleteObserver(this); - } + void tearDown() override { m_Service->HandleDeleteObserver(this); } void OpenListener_Succeed() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); 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() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/serverexample"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/serverexample"), this); CPPUNIT_ASSERT_MESSAGE("Open two listener with a different path,same host, same port, observer map size is two", 2 == m_Service->GetObservers().size()); CPPUNIT_ASSERT_MESSAGE("Open two listener with a different path,same host, same port, server map size is one", 1 == m_Service->GetServerMap().size()); } void CloseListener_Succeed() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); 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()); m_Service->HandleDeleteObserver(this); 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() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8090/serverexample"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8090/serverexample"), this); 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()); - m_Service->HandleDeleteObserver(this, _XPLATSTR("http://localhost:8080/servertest")); + m_Service->HandleDeleteObserver(this, U("http://localhost:8080/servertest")); CPPUNIT_ASSERT_MESSAGE("Closed one of two listeners, observer map is size is one", 1 == m_Service->GetObservers().size()); - CPPUNIT_ASSERT_MESSAGE("Closed one of two listener, server map size is one", - 1 == m_Service->GetServerMap().size()); + CPPUNIT_ASSERT_MESSAGE("Closed one of two listener, server map size is one", 1 == m_Service->GetServerMap().size()); } void OpenMultipleListenerCloseAll_Succeed() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8090/serverexample"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8090/serverexample"), this); 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()); m_Service->HandleDeleteObserver(this); 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() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); web::json::value result; - - m_Service->SendRequest(_XPLATSTR("http://localhost:8080/servertest")) + auto body = web::json::value(); + m_Service->SendRequest(U("http://localhost:8080/servertest")) .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 == m_Data); } void RequestToClosedListener() { web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:8080/servertest")) + m_Service->SendRequest(U("http://localhost:8080/servertest")) .then([&](pplx::task resultTask) { result = resultTask.get(); }) .wait(); } void CloseListener_NoRequestPossible() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); 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()); m_Service->HandleDeleteObserver(this); 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() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); web::json::value result; - m_Service->SendRequest(_XPLATSTR("http://localhost:8080/serverexample")) + m_Service->SendRequest(U("http://localhost:8080/serverexample")) .then([&](pplx::task resultTask) { result = resultTask.get(); }) .wait(); } void OpenListenerGetRequestDifferentPath_ReturnNotFound() { CPPUNIT_ASSERT_THROW(RequestToDifferentPathNotFound(), mitk::Exception); } void OpenListenerCloseAndReopen_Succeed() { - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); 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()); m_Service->HandleDeleteObserver(this); 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()); - m_Service->ReceiveRequest(_XPLATSTR("http://localhost:8080/servertest"), this); + m_Service->ReceiveRequest(U("http://localhost:8080/servertest"), this); 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()); } + + void HandleHeader_Succeed() + { + mitk::RESTUtil::ParamMap headers; + headers.insert(mitk::RESTUtil::ParamMap::value_type(U("Content-Type"), U("awesome/type"))); + + m_Service->SendRequest(U("http://localhost:8080/clienttest")).then([&](pplx::task resultTask) { + // Do something when a single task is done + try + { + auto result = resultTask.get(); + CPPUNIT_ASSERT_MESSAGE("Sent Header is not successfull transfered to server", + result[U("result")].as_string() == U("awesome/type")); + } + catch (const mitk::Exception &exception) + { + MITK_ERROR << exception.what(); + return; + } + }); + } }; MITK_TEST_SUITE_REGISTRATION(mitkRESTServer) diff --git a/Modules/RESTService/include/mitkRESTManager.h b/Modules/RESTService/include/mitkRESTManager.h index ea50ffdeea..cd0929d0ac 100644 --- a/Modules/RESTService/include/mitkRESTManager.h +++ b/Modules/RESTService/include/mitkRESTManager.h @@ -1,118 +1,157 @@ /*=================================================================== 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 namespace mitk { /** - * @class RESTManager - * @brief this is a microservice for managing REST-requests, used for non-qt applications. - * - * RESTManagerQt in the CppRestSdkQt module inherits from this class and is the equivalent microservice - * used for Qt applications. - */ + * @class RESTManager + * @brief this is a microservice for managing REST-requests, used for non-qt applications. + * + * RESTManagerQt in the CppRestSdkQt module inherits from this class and is the equivalent microservice + * used for Qt applications. + */ class MITKRESTSERVICE_EXPORT RESTManager : public IRESTManager { public: RESTManager(); ~RESTManager() override; + /** + * @brief Executes a HTTP request in the mitkRESTClient class + * + * @throw mitk::Exception if RequestType is not suported + * @param uri defines the URI the request is send to + * @param type the RequestType of the HTTP request (optional) + * @param headers the headers for the request (optional) + * @return task to wait for + */ + pplx::task SendRequest( + const web::uri &uri, + const RequestType &type = RequestType::Get, + const std::map headers = {}) override; + /** * @brief Executes a HTTP request in the mitkRESTClient class * * @throw mitk::Exception if RequestType is not suported * @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 + * @param headers the headers for the request (optional) + * @param filePath the file path to store the request to (optional) * @return task to wait for */ - pplx::task SendRequest(const web::uri &uri, - const RequestType &type = RequestType::Get, - const web::json::value *body = nullptr, - const utility::string_t &filePath = {}) override; + pplx::task SendJSONRequest(const web::uri &uri, + const RequestType &type = RequestType::Get, + const web::json::value *body = nullptr, + const std::map headers = {}, + const utility::string_t &filePath = {}) override; + + /** + * @brief Executes a HTTP request in the mitkRESTClient class + * + * @throw mitk::Exception if RequestType is not suported + * @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 headers the headers for the request (optional) + * @return task to wait for + */ + pplx::task SendBinaryRequest( + const web::uri &uri, + const RequestType &type = RequestType::Get, + const std::vector * = {}, + const std::map headers = {}) 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 + * @param method the http method of the request + * @param headers the http headers of the request + * @return the response */ - web::json::value Handle(const web::uri &uri, const web::json::value &body) override; + + web::http::http_response Handle(const web::uri &uri, + const web::json::value &body, + const web::http::method &method, + const mitk::RESTUtil::ParamMap &headers) 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) */ void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri = {}) override; /** - * @brief internal use only - */ - const std::map& GetServerMap() override; - std::map, IRESTObserver *>& GetObservers() override; + * @brief internal use only + */ + const std::map &GetServerMap() override; + std::map, IRESTObserver *> &GetObservers() override; private: /** * @brief adds an observer if a port is free, called by ReceiveRequest method * * @param uri the uri which builds the key for the observer map * @param observer the observer which is added */ void AddObserver(const web::uri &uri, IRESTObserver *observer); /** * @brief handles server management if there is already a server under a port, called by ReceiveRequest method * * @param uri the uri which which is requested to be added * @param observer the observer which proceeds the request */ void RequestForATakenPort(const web::uri &uri, IRESTObserver *observer); /** * @brief deletes an observer, called by HandleDeleteObserver method * * @param it the iterator comparing the observers in HandleDeleteObserver method * @return bool if there is another observer under the port */ bool DeleteObserver(std::map, IRESTObserver *>::iterator &it); void SetServerMap(const int port, RESTServer *server); void DeleteFromServerMap(const int port); void SetObservers(const std::pair key, IRESTObserver *observer); - std::map m_ServerMap; // Map with port server pairs + std::map m_ServerMap; // Map with port server pairs std::map, IRESTObserver *> m_Observers; // Map with all observers }; -} +} // namespace mitk #endif diff --git a/Modules/RESTService/src/mitkRESTManager.cpp b/Modules/RESTService/src/mitkRESTManager.cpp index 711be3dc65..36b365168d 100644 --- a/Modules/RESTService/src/mitkRESTManager.cpp +++ b/Modules/RESTService/src/mitkRESTManager.cpp @@ -1,217 +1,262 @@ /*=================================================================== 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. ===================================================================*/ -#include +#include #include +#include #include -#include #include #include -mitk::RESTManager::RESTManager() +mitk::RESTManager::RESTManager() {} + +mitk::RESTManager::~RESTManager() {} + +pplx::task mitk::RESTManager::SendRequest( + const web::uri &uri, const RequestType &type, const std::map headers) { + pplx::task answer; + auto client = new RESTClient; + + switch (type) + { + case RequestType::Get: + answer = client->Get(uri, headers); + break; + + default: + mitkThrow() << "Request Type not supported"; + } + + return answer; } -mitk::RESTManager::~RESTManager() +pplx::task mitk::RESTManager::SendBinaryRequest( + const web::uri &uri, + const RequestType &type, + const std::vector *content, + const std::map headers) { + pplx::task answer; + auto client = new RESTClient; + + switch (type) + { + case RequestType::Post: + if (nullptr == content) + MITK_WARN << "Content for post is empty, this will create an empty resource"; + + answer = client->Post(uri, content, headers); + break; + + default: + mitkThrow() << "Request Type not supported for binary data"; + } + + return answer; } -pplx::task mitk::RESTManager::SendRequest(const web::uri &uri, - const RequestType &type, - const web::json::value *content, - const utility::string_t &filePath) +pplx::task mitk::RESTManager::SendJSONRequest( + const web::uri &uri, + const RequestType &type, + const web::json::value *content, + const std::map headers, + const utility::string_t &filePath) { pplx::task answer; auto client = new RESTClient; switch (type) { case RequestType::Get: - answer = !filePath.empty() - ? client->Get(uri, filePath) - : client->Get(uri); + answer = !filePath.empty() ? client->Get(uri, filePath, headers) : client->Get(uri, headers); break; case RequestType::Post: if (nullptr == content) - MITK_WARN << "Content for put is empty, this will create an empty resource"; + MITK_WARN << "Content for post is empty, this will create an empty resource"; - answer = client->Post(uri, content); + answer = client->Post(uri, content, headers); break; case RequestType::Put: if (nullptr == content) MITK_WARN << "Content for put is empty, this will empty the ressource"; answer = client->Put(uri, content); break; default: mitkThrow() << "Request Type not supported"; } 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 auto port = uri.port(); // Checking if port is free to add a new Server 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(); } // If there is already a server under this port else { this->RequestForATakenPort(uri, observer); } } -web::json::value mitk::RESTManager::Handle(const web::uri &uri, const web::json::value &body) +web::http::http_response mitk::RESTManager::Handle(const web::uri &uri, + const web::json::value &body, + const web::http::method &method, + const mitk::RESTUtil::ParamMap &headers) { // Checking if there is an observer for the port and path auto key = std::make_pair(uri.port(), uri.path()); if (0 != m_Observers.count(key)) { - return m_Observers[key]->Notify(uri, body); + return m_Observers[key]->Notify(uri, body, method, headers); } // 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 web::json::value(); + web::http::http_response response(web::http::status_codes::BadGateway); + response.set_body(U("No one can handle the request under the given port.")); + return response; } } void mitk::RESTManager::HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri) { 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 (observer == obsMap) { // Check wether it is the right uri to be deleted if (uri.is_empty() || uri.path() == it->first.second) { int port = it->first.first; bool noObserverForPort = this->DeleteObserver(it); 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; } 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; } void mitk::RESTManager::RequestForATakenPort(const web::uri &uri, IRESTObserver *observer) { // Same host, means new observer but not a new server instance 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 (0 == m_Observers.count(key)) { this->AddObserver(uri, observer); } 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) { int port = it->first.first; it = m_Observers.erase(it); for (auto observer : m_Observers) { if (port == observer.first.first) { // there still exists an observer for this port return false; } } return true; } void mitk::RESTManager::SetServerMap(const int port, RESTServer *server) { m_ServerMap[port] = server; } void mitk::RESTManager::DeleteFromServerMap(const int port) { m_ServerMap.erase(port); } void mitk::RESTManager::SetObservers(const std::pair key, IRESTObserver *observer) { m_Observers[key] = observer; }