From fd0c4b8631bd82956aa7be7564b5218a85fbe561 Mon Sep 17 00:00:00 2001 From: "Parker, Peter G" <parkerpg@ornl.gov> Date: Wed, 20 Jun 2018 10:37:48 -0400 Subject: [PATCH] Refs #22608 - Apply clang-format patch. --- .../Catalog/inc/MantidCatalog/Exception.h | 24 +- Framework/Catalog/inc/MantidCatalog/OAuth.h | 23 +- Framework/Catalog/inc/MantidCatalog/ONCat.h | 43 +- .../Catalog/inc/MantidCatalog/ONCatEntity.h | 38 +- Framework/Catalog/src/OAuth.cpp | 109 ++--- Framework/Catalog/src/ONCat.cpp | 206 ++++----- Framework/Catalog/src/ONCatEntity.cpp | 187 ++++---- Framework/Catalog/test/OAuthTest.h | 24 +- Framework/Catalog/test/ONCatEntityTest.h | 107 +++-- Framework/Catalog/test/ONCatTest.h | 404 +++++++----------- Framework/Kernel/src/InternetHelper.cpp | 8 +- 11 files changed, 476 insertions(+), 697 deletions(-) diff --git a/Framework/Catalog/inc/MantidCatalog/Exception.h b/Framework/Catalog/inc/MantidCatalog/Exception.h index 1814c4deee8..9c361d5c265 100644 --- a/Framework/Catalog/inc/MantidCatalog/Exception.h +++ b/Framework/Catalog/inc/MantidCatalog/Exception.h @@ -9,38 +9,38 @@ namespace Exception { class CatalogError : public std::runtime_error { public: - explicit CatalogError(const std::string & message) : - std::runtime_error(message) {} + explicit CatalogError(const std::string &message) + : std::runtime_error(message) {} }; class InvalidCredentialsError final : public CatalogError { public: - explicit InvalidCredentialsError(const std::string & message) : - CatalogError(message) {} + explicit InvalidCredentialsError(const std::string &message) + : CatalogError(message) {} }; class TokenRejectedError final : public CatalogError { public: - explicit TokenRejectedError(const std::string & message) : - CatalogError(message) {} + explicit TokenRejectedError(const std::string &message) + : CatalogError(message) {} }; class TokenParsingError final : public CatalogError { public: - explicit TokenParsingError(const std::string & message) : - CatalogError(message) {} + explicit TokenParsingError(const std::string &message) + : CatalogError(message) {} }; class InvalidRefreshTokenError final : public CatalogError { public: - explicit InvalidRefreshTokenError(const std::string & message) : - CatalogError(message) {} + explicit InvalidRefreshTokenError(const std::string &message) + : CatalogError(message) {} }; class MalformedRepresentationError final : public CatalogError { public: - explicit MalformedRepresentationError(const std::string & message) : - CatalogError(message) {} + explicit MalformedRepresentationError(const std::string &message) + : CatalogError(message) {} }; } // namespace Exception diff --git a/Framework/Catalog/inc/MantidCatalog/OAuth.h b/Framework/Catalog/inc/MantidCatalog/OAuth.h index d3182a5e82e..27384ff034b 100644 --- a/Framework/Catalog/inc/MantidCatalog/OAuth.h +++ b/Framework/Catalog/inc/MantidCatalog/OAuth.h @@ -53,13 +53,9 @@ enum class OAuthFlow : uint8_t { class MANTID_CATALOG_DLL OAuthToken { public: OAuthToken() = delete; - OAuthToken( - const std::string & tokenType, - int expiresIn, - const std::string & accessToken, - const std::string & scope, - const boost::optional<std::string> & refreshToken - ); + OAuthToken(const std::string &tokenType, int expiresIn, + const std::string &accessToken, const std::string &scope, + const boost::optional<std::string> &refreshToken); ~OAuthToken(); std::string tokenType() const; @@ -69,9 +65,9 @@ public: boost::optional<std::string> refreshToken() const; bool isExpired() const; - bool isExpired(const DateAndTime & currentTime) const; + bool isExpired(const DateAndTime ¤tTime) const; - static OAuthToken fromJSONStream(std::istream & tokenStringStream); + static OAuthToken fromJSONStream(std::istream &tokenStringStream); private: DateAndTime m_expiresAt; @@ -85,19 +81,18 @@ private: class MANTID_CATALOG_DLL IOAuthTokenStore { public: - virtual void setToken(const boost::optional<OAuthToken> & token) = 0; + virtual void setToken(const boost::optional<OAuthToken> &token) = 0; virtual boost::optional<OAuthToken> getToken() = 0; }; class MANTID_CATALOG_DLL ConfigServiceTokenStore : public IOAuthTokenStore { public: ConfigServiceTokenStore() = default; - ConfigServiceTokenStore & operator=( - const ConfigServiceTokenStore& other - ) = default; + ConfigServiceTokenStore & + operator=(const ConfigServiceTokenStore &other) = default; ~ConfigServiceTokenStore(); - void setToken(const boost::optional<OAuthToken> & token) override; + void setToken(const boost::optional<OAuthToken> &token) override; boost::optional<OAuthToken> getToken() override; }; diff --git a/Framework/Catalog/inc/MantidCatalog/ONCat.h b/Framework/Catalog/inc/MantidCatalog/ONCat.h index 33a99002ef7..5a603471d37 100644 --- a/Framework/Catalog/inc/MantidCatalog/ONCat.h +++ b/Framework/Catalog/inc/MantidCatalog/ONCat.h @@ -109,47 +109,38 @@ public: static ONCat fromMantidSettings(); ONCat() = delete; - ONCat(const ONCat & other); + ONCat(const ONCat &other); ~ONCat(); bool isUserLoggedIn() const; - void login(const std::string & username, const std::string & password); + void login(const std::string &username, const std::string &password); void logout(); - ONCatEntity retrieve( - const std::string & resourceNamespace, - const std::string & resource, - const std::string & identifier, - const QueryParameters & queryParameters); - std::vector<ONCatEntity> list( - const std::string & resourceNamespace, - const std::string & resource, - const QueryParameters & queryParameters); + ONCatEntity retrieve(const std::string &resourceNamespace, + const std::string &resource, + const std::string &identifier, + const QueryParameters &queryParameters); + std::vector<ONCatEntity> list(const std::string &resourceNamespace, + const std::string &resource, + const QueryParameters &queryParameters); ////////////////////////////////////////////////////////////////////// // Exposed publicly for testing purposes only. ////////////////////////////////////////////////////////////////////// - ONCat( - const std::string & url, - IOAuthTokenStore_uptr tokenStore, - OAuthFlow flow, - const std::string & clientId, - const boost::optional<std::string> & clientSecret = boost::none - ); + ONCat(const std::string &url, IOAuthTokenStore_uptr tokenStore, + OAuthFlow flow, const std::string &clientId, + const boost::optional<std::string> &clientSecret = boost::none); void refreshTokenIfNeeded(); - void refreshTokenIfNeeded(const DateAndTime & currentTime); + void refreshTokenIfNeeded(const DateAndTime ¤tTime); void setInternetHelper( - std::unique_ptr<Mantid::Kernel::InternetHelper> internetHelper - ); + std::unique_ptr<Mantid::Kernel::InternetHelper> internetHelper); ////////////////////////////////////////////////////////////////////// private: - void sendAPIRequest( - const std::string & uri, - const QueryParameters & queryParameters, - std::ostream & response - ); + void sendAPIRequest(const std::string &uri, + const QueryParameters &queryParameters, + std::ostream &response); std::string m_url; IOAuthTokenStore_sptr m_tokenStore; diff --git a/Framework/Catalog/inc/MantidCatalog/ONCatEntity.h b/Framework/Catalog/inc/MantidCatalog/ONCatEntity.h index aa60ceae493..6c48f214512 100644 --- a/Framework/Catalog/inc/MantidCatalog/ONCatEntity.h +++ b/Framework/Catalog/inc/MantidCatalog/ONCatEntity.h @@ -9,7 +9,7 @@ #include <boost/optional.hpp> namespace Json { - class Value; +class Value; } namespace Mantid { @@ -81,33 +81,29 @@ public: // So, you can either supply a default value for when the field you // want is not there ... - std::string asString( - const std::string & path, const std::string defaultValue) const; - int asInt(const std::string & path, int defaultValue) const; - float asFloat(const std::string & path, float defaultValue) const; - double asDouble(const std::string & path, double defaultValue) const; - bool asBool(const std::string & path, bool defaultValue) const; + std::string asString(const std::string &path, + const std::string defaultValue) const; + int asInt(const std::string &path, int defaultValue) const; + float asFloat(const std::string &path, float defaultValue) const; + double asDouble(const std::string &path, double defaultValue) const; + bool asBool(const std::string &path, bool defaultValue) const; // ... or, write conditional logic around boost's optional results. - boost::optional<std::string> asString(const std::string & path) const; - boost::optional<int> asInt(const std::string & path) const; - boost::optional<float> asFloat(const std::string & path) const; - boost::optional<double> asDouble(const std::string & path) const; - boost::optional<bool> asBool(const std::string & path) const; + boost::optional<std::string> asString(const std::string &path) const; + boost::optional<int> asInt(const std::string &path) const; + boost::optional<float> asFloat(const std::string &path) const; + boost::optional<double> asDouble(const std::string &path) const; + boost::optional<bool> asBool(const std::string &path) const; std::string toString() const; - static ONCatEntity fromJSONStream( - std::istream & streamContent); - static std::vector<ONCatEntity> vectorFromJSONStream( - std::istream & streamContent); + static ONCatEntity fromJSONStream(std::istream &streamContent); + static std::vector<ONCatEntity> + vectorFromJSONStream(std::istream &streamContent); private: - ONCatEntity( - const std::string & id, - const std::string & type, - Content_uptr content - ); + ONCatEntity(const std::string &id, const std::string &type, + Content_uptr content); std::string m_id; std::string m_type; diff --git a/Framework/Catalog/src/OAuth.cpp b/Framework/Catalog/src/OAuth.cpp index 8adfd8e8258..e955d1476f1 100644 --- a/Framework/Catalog/src/OAuth.cpp +++ b/Framework/Catalog/src/OAuth.cpp @@ -19,52 +19,37 @@ using Mantid::Catalog::Exception::TokenParsingError; // OAuthToken //---------------------------------------------------------------------- -OAuthToken::OAuthToken( - const std::string & tokenType, - int expiresIn, - const std::string & accessToken, - const std::string & scope, - const boost::optional<std::string> & refreshToken -) : - m_expiresAt(DateAndTime::getCurrentTime() + static_cast<double>(expiresIn)), - m_tokenType(tokenType), - m_expiresIn(expiresIn), - m_accessToken(accessToken), - m_scope(scope), - m_refreshToken(refreshToken) {} +OAuthToken::OAuthToken(const std::string &tokenType, int expiresIn, + const std::string &accessToken, const std::string &scope, + const boost::optional<std::string> &refreshToken) + : m_expiresAt(DateAndTime::getCurrentTime() + + static_cast<double>(expiresIn)), + m_tokenType(tokenType), m_expiresIn(expiresIn), + m_accessToken(accessToken), m_scope(scope), m_refreshToken(refreshToken) { +} OAuthToken::~OAuthToken() {} -OAuthToken OAuthToken::fromJSONStream( - std::istream & tokenStringStream -) { +OAuthToken OAuthToken::fromJSONStream(std::istream &tokenStringStream) { try { Json::Value full_token; tokenStringStream >> full_token; - + const auto tokenType = full_token["token_type"].asString(); const auto expiresIn = - static_cast<unsigned int>(full_token["expires_in"].asUInt()); + static_cast<unsigned int>(full_token["expires_in"].asUInt()); const auto accessToken = full_token["access_token"].asString(); const auto scope = full_token["scope"].asString(); const auto parsedRefreshToken = full_token["refresh_token"].asString(); const boost::optional<std::string> refreshToken = - parsedRefreshToken == "" ? - boost::none : - boost::optional<std::string>(parsedRefreshToken); - - return OAuthToken( - tokenType, - expiresIn, - accessToken, - scope, - refreshToken - ); + parsedRefreshToken == "" + ? boost::none + : boost::optional<std::string>(parsedRefreshToken); + + return OAuthToken(tokenType, expiresIn, accessToken, scope, refreshToken); } catch (...) { - throw TokenParsingError( - "Unable to parse authentication token!" - ); + throw TokenParsingError("Unable to parse authentication token!"); } } @@ -72,25 +57,17 @@ bool OAuthToken::isExpired() const { return isExpired(DateAndTime::getCurrentTime()); } -bool OAuthToken::isExpired(const DateAndTime & currentTime) const { +bool OAuthToken::isExpired(const DateAndTime ¤tTime) const { return currentTime > m_expiresAt; } -std::string OAuthToken::tokenType() const { - return m_tokenType; -} +std::string OAuthToken::tokenType() const { return m_tokenType; } -int OAuthToken::expiresIn() const { - return m_expiresIn; -} +int OAuthToken::expiresIn() const { return m_expiresIn; } -std::string OAuthToken::accessToken() const { - return m_accessToken; -} +std::string OAuthToken::accessToken() const { return m_accessToken; } -std::string OAuthToken::scope() const { - return m_scope; -} +std::string OAuthToken::scope() const { return m_scope; } boost::optional<std::string> OAuthToken::refreshToken() const { return m_refreshToken; @@ -101,7 +78,7 @@ boost::optional<std::string> OAuthToken::refreshToken() const { //---------------------------------------------------------------------- namespace { - static const std::string CONFIG_PATH_BASE = "catalog.oncat.token."; +static const std::string CONFIG_PATH_BASE = "catalog.oncat.token."; } ConfigServiceTokenStore::~ConfigServiceTokenStore() { @@ -115,7 +92,7 @@ ConfigServiceTokenStore::~ConfigServiceTokenStore() { // * We have to save the *entire* contents of the config. This may // not be desirable. // * Ideally we would persist on every token set. - auto & config = Mantid::Kernel::ConfigService::Instance(); + auto &config = Mantid::Kernel::ConfigService::Instance(); config.saveConfig(config.getUserFilename()); } catch (...) { // It's not the end of the world if there was an error persisting @@ -125,22 +102,18 @@ ConfigServiceTokenStore::~ConfigServiceTokenStore() { } void ConfigServiceTokenStore::setToken( - const boost::optional<OAuthToken> & token -) { - auto & config = Mantid::Kernel::ConfigService::Instance(); + const boost::optional<OAuthToken> &token) { + auto &config = Mantid::Kernel::ConfigService::Instance(); if (token) { config.setString(CONFIG_PATH_BASE + "tokenType", token->tokenType()); - config.setString( - CONFIG_PATH_BASE + "expiresIn", - std::to_string(token->expiresIn()) - ); + config.setString(CONFIG_PATH_BASE + "expiresIn", + std::to_string(token->expiresIn())); config.setString(CONFIG_PATH_BASE + "accessToken", token->accessToken()); config.setString(CONFIG_PATH_BASE + "scope", token->scope()); - config.setString( - CONFIG_PATH_BASE + "refreshToken", - token->refreshToken() ? *token->refreshToken() : std::string("") - ); + config.setString(CONFIG_PATH_BASE + "refreshToken", + token->refreshToken() ? *token->refreshToken() + : std::string("")); } else { config.setString(CONFIG_PATH_BASE + "tokenType", ""); config.setString(CONFIG_PATH_BASE + "expiresIn", ""); @@ -151,17 +124,13 @@ void ConfigServiceTokenStore::setToken( } boost::optional<OAuthToken> ConfigServiceTokenStore::getToken() { - auto & config = Mantid::Kernel::ConfigService::Instance(); + auto &config = Mantid::Kernel::ConfigService::Instance(); const auto tokenType = config.getString(CONFIG_PATH_BASE + "tokenType"); const auto expiresIn = config.getString(CONFIG_PATH_BASE + "expiresIn"); - const auto accessToken = config.getString( - CONFIG_PATH_BASE + "accessToken" - ); + const auto accessToken = config.getString(CONFIG_PATH_BASE + "accessToken"); const auto scope = config.getString(CONFIG_PATH_BASE + "scope"); - const auto refreshToken = config.getString( - CONFIG_PATH_BASE + "refreshToken" - ); + const auto refreshToken = config.getString(CONFIG_PATH_BASE + "refreshToken"); // A partially written-out token is useless and is therefore // effectively the same as a token not having been written out at @@ -172,13 +141,9 @@ boost::optional<OAuthToken> ConfigServiceTokenStore::getToken() { } try { - return boost::make_optional(OAuthToken( - tokenType, - std::stoi(expiresIn), - accessToken, - scope, - boost::make_optional(refreshToken != "", refreshToken) - )); + return boost::make_optional( + OAuthToken(tokenType, std::stoi(expiresIn), accessToken, scope, + boost::make_optional(refreshToken != "", refreshToken))); } catch (std::invalid_argument &) { // Catching any std::stoi failures silently -- a malformed token is // useless and may as well not be there. diff --git a/Framework/Catalog/src/ONCat.cpp b/Framework/Catalog/src/ONCat.cpp index c0c02839f8f..7e4f9f8c27f 100644 --- a/Framework/Catalog/src/ONCat.cpp +++ b/Framework/Catalog/src/ONCat.cpp @@ -41,7 +41,7 @@ static const std::string CONFIG_PATH_BASE = "catalog.oncat."; // <externaldownload> tags in the XML. static const std::string DEFAULT_ONCAT_URL = "https://oncat.ornl.gov"; static const std::string DEFAULT_CLIENT_ID = - "d16ea847-41ce-4b30-9167-40298588e755"; + "d16ea847-41ce-4b30-9167-40298588e755"; } /** @@ -83,58 +83,43 @@ static const std::string DEFAULT_CLIENT_ID = * @return The constructed ONCat object. */ ONCat ONCat::fromMantidSettings() { - auto & config = Mantid::Kernel::ConfigService::Instance(); + auto &config = Mantid::Kernel::ConfigService::Instance(); const auto client_id = config.getString(CONFIG_PATH_BASE + "client_id"); const auto client_secret = - config.getString(CONFIG_PATH_BASE + "client_secret"); + config.getString(CONFIG_PATH_BASE + "client_secret"); const bool hasClientCredentials = client_id != "" && client_secret != ""; if (hasClientCredentials) { - g_log.debug() - << "Found client credentials in Mantid.local.properties. " - << "No user login required." - << std::endl; + g_log.debug() << "Found client credentials in Mantid.local.properties. " + << "No user login required." << std::endl; } else { g_log.debug() - << "Could not find client credentials in Mantid.local.properties. " - << "Falling back to default -- user login required." - << std::endl; + << "Could not find client credentials in Mantid.local.properties. " + << "Falling back to default -- user login required." << std::endl; } - return ONCat( - DEFAULT_ONCAT_URL, - Mantid::Kernel::make_unique<ConfigServiceTokenStore>(), - hasClientCredentials - ? OAuthFlow::CLIENT_CREDENTIALS - : OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - hasClientCredentials ? client_id : DEFAULT_CLIENT_ID, - boost::make_optional(hasClientCredentials, client_secret) - ); + return ONCat(DEFAULT_ONCAT_URL, + Mantid::Kernel::make_unique<ConfigServiceTokenStore>(), + hasClientCredentials ? OAuthFlow::CLIENT_CREDENTIALS + : OAuthFlow::RESOURCE_OWNER_CREDENTIALS, + hasClientCredentials ? client_id : DEFAULT_CLIENT_ID, + boost::make_optional(hasClientCredentials, client_secret)); } -ONCat::ONCat( - const std::string & url, - IOAuthTokenStore_uptr tokenStore, - OAuthFlow flow, - const std::string & clientId, - const boost::optional<std::string> & clientSecret -) : - m_url(url), - m_tokenStore(std::move(tokenStore)), - m_clientId(clientId), - m_clientSecret(clientSecret), - - m_flow(flow), - m_internetHelper(new Mantid::Kernel::InternetHelper()) {} - -ONCat::ONCat(const ONCat & other) : - m_url(other.m_url), - m_tokenStore(other.m_tokenStore), - m_clientId(other.m_clientId), - m_clientSecret(other.m_clientSecret), - - m_flow(other.m_flow), - m_internetHelper(new Mantid::Kernel::InternetHelper()) {} +ONCat::ONCat(const std::string &url, IOAuthTokenStore_uptr tokenStore, + OAuthFlow flow, const std::string &clientId, + const boost::optional<std::string> &clientSecret) + : m_url(url), m_tokenStore(std::move(tokenStore)), m_clientId(clientId), + m_clientSecret(clientSecret), + + m_flow(flow), m_internetHelper(new Mantid::Kernel::InternetHelper()) {} + +ONCat::ONCat(const ONCat &other) + : m_url(other.m_url), m_tokenStore(other.m_tokenStore), + m_clientId(other.m_clientId), m_clientSecret(other.m_clientSecret), + + m_flow(other.m_flow), + m_internetHelper(new Mantid::Kernel::InternetHelper()) {} ONCat::~ONCat() {} @@ -195,7 +180,8 @@ void ONCat::logout() { // spec). A "logout", then, is simply throwing away whatever token we // previously stored client-side. m_tokenStore->setToken(boost::none); - g_log.debug() << "Logging out." << std::endl;; + g_log.debug() << "Logging out." << std::endl; + ; } /** @@ -208,15 +194,14 @@ void ONCat::logout() { * @exception Mantid::Catalog::Exception::InvalidCredentialsError : * Thrown when the given credentials are not valid. */ -void ONCat::login( - const std::string & username, const std::string & password -) { +void ONCat::login(const std::string &username, const std::string &password) { if (m_flow != OAuthFlow::RESOURCE_OWNER_CREDENTIALS) { g_log.warning() - << "Unexpected usage detected! " - << "Logging in with user credentials in not required (and is not " - << "supported) when machine-to-machine credentials are being used." - << std::endl;; + << "Unexpected usage detected! " + << "Logging in with user credentials in not required (and is not " + << "supported) when machine-to-machine credentials are being used." + << std::endl; + ; return; } @@ -234,20 +219,19 @@ void ONCat::login( try { std::stringstream ss; - const int statusCode = m_internetHelper->sendRequest( - m_url + "/oauth/token", ss - ); + const int statusCode = + m_internetHelper->sendRequest(m_url + "/oauth/token", ss); if (statusCode == HTTPResponse::HTTP_OK) { m_tokenStore->setToken(OAuthToken::fromJSONStream(ss)); } - g_log.debug() << "Login was successful!" << std::endl;; - } catch (InternetError & ie) { + g_log.debug() << "Login was successful!" << std::endl; + ; + } catch (InternetError &ie) { if (ie.errorCode() == HTTPResponse::HTTP_UNAUTHORIZED) { throw InvalidCredentialsError( - "Invalid UCAMS / XCAMS credentials used for ONCat login." - ); + "Invalid UCAMS / XCAMS credentials used for ONCat login."); } throw CatalogError(ie.what()); } @@ -275,14 +259,12 @@ void ONCat::login( * * @exception Mantid::Catalog::Exception::CatalogError */ -ONCatEntity ONCat::retrieve( - const std::string & resourceNamespace, - const std::string & resource, - const std::string & identifier, - const QueryParameters & queryParameters -) { +ONCatEntity ONCat::retrieve(const std::string &resourceNamespace, + const std::string &resource, + const std::string &identifier, + const QueryParameters &queryParameters) { const auto uri = - m_url + "/" + resourceNamespace + "/" + resource + "/" + identifier; + m_url + "/" + resourceNamespace + "/" + resource + "/" + identifier; std::stringstream ss; sendAPIRequest(uri, queryParameters, ss); @@ -296,13 +278,10 @@ ONCatEntity ONCat::retrieve( * * Please see retrieve documentation for more info. */ -std::vector<ONCatEntity> ONCat::list( - const std::string & resourceNamespace, - const std::string & resource, - const QueryParameters & queryParameters -) { - const auto uri = - m_url + "/" + resourceNamespace + "/" + resource; +std::vector<ONCatEntity> ONCat::list(const std::string &resourceNamespace, + const std::string &resource, + const QueryParameters &queryParameters) { + const auto uri = m_url + "/" + resourceNamespace + "/" + resource; std::stringstream ss; sendAPIRequest(uri, queryParameters, ss); @@ -331,11 +310,13 @@ void ONCat::refreshTokenIfNeeded() { * @exception Mantid::Catalog::Exception::InvalidRefreshTokenError : * Thrown when the provider decides the current token cannot be refreshed. */ -void ONCat::refreshTokenIfNeeded(const DateAndTime & currentTime) { +void ONCat::refreshTokenIfNeeded(const DateAndTime ¤tTime) { const auto currentToken = m_tokenStore->getToken(); if (m_flow == OAuthFlow::CLIENT_CREDENTIALS) { - if (currentToken && !currentToken->isExpired(currentTime)) { return; } + if (currentToken && !currentToken->isExpired(currentTime)) { + return; + } Poco::Net::HTMLForm form(Poco::Net::HTMLForm::ENCODING_MULTIPART); form.set("client_id", m_clientId); @@ -350,22 +331,27 @@ void ONCat::refreshTokenIfNeeded(const DateAndTime & currentTime) { try { std::stringstream ss; - const int statusCode = m_internetHelper->sendRequest( - m_url + "/oauth/token", ss - ); + const int statusCode = + m_internetHelper->sendRequest(m_url + "/oauth/token", ss); if (statusCode == HTTPResponse::HTTP_OK) { m_tokenStore->setToken(OAuthToken::fromJSONStream(ss)); } g_log.debug() << "Token successfully refreshed." << std::endl; - } catch (InternetError & ie) { + } catch (InternetError &ie) { throw CatalogError(ie.what()); } } else if (m_flow == OAuthFlow::RESOURCE_OWNER_CREDENTIALS) { - if (!currentToken) { return; } - if (!currentToken->isExpired(currentTime)) { return; } + if (!currentToken) { + return; + } + if (!currentToken->isExpired(currentTime)) { + return; + } const auto currentRefreshToken = currentToken->refreshToken(); - if (!currentRefreshToken) { return; } + if (!currentRefreshToken) { + return; + } Poco::Net::HTMLForm form(Poco::Net::HTMLForm::ENCODING_MULTIPART); form.set("client_id", m_clientId); @@ -381,22 +367,20 @@ void ONCat::refreshTokenIfNeeded(const DateAndTime & currentTime) { try { std::stringstream ss; - const int statusCode = m_internetHelper->sendRequest( - m_url + "/oauth/token", ss - ); + const int statusCode = + m_internetHelper->sendRequest(m_url + "/oauth/token", ss); if (statusCode == HTTPResponse::HTTP_OK) { m_tokenStore->setToken(OAuthToken::fromJSONStream(ss)); } g_log.debug() << "Token successfully refreshed." << std::endl; - } catch (InternetError & ie) { + } catch (InternetError &ie) { if (ie.errorCode() == HTTPResponse::HTTP_UNAUTHORIZED) { // As per OAuth spec, when a refresh token is no longer valid, we // can consider ourselves logged out. logout(); throw InvalidRefreshTokenError( - "You have been logged out. Please login again." - ); + "You have been logged out. Please login again."); } throw CatalogError(ie.what()); } @@ -404,16 +388,13 @@ void ONCat::refreshTokenIfNeeded(const DateAndTime & currentTime) { } void ONCat::setInternetHelper( - std::unique_ptr<Mantid::Kernel::InternetHelper> internetHelper -) { + std::unique_ptr<Mantid::Kernel::InternetHelper> internetHelper) { m_internetHelper = std::move(internetHelper); } -void ONCat::sendAPIRequest( - const std::string & uri, - const QueryParameters & queryParameters, - std::ostream & response -) { +void ONCat::sendAPIRequest(const std::string &uri, + const QueryParameters &queryParameters, + std::ostream &response) { refreshTokenIfNeeded(); const auto tokenType = m_tokenStore->getToken()->tokenType(); @@ -421,43 +402,36 @@ void ONCat::sendAPIRequest( m_internetHelper->clearHeaders(); m_internetHelper->setMethod("GET"); - m_internetHelper->addHeader( - "Authorization", tokenType + " " + accessToken - ); + m_internetHelper->addHeader("Authorization", tokenType + " " + accessToken); std::vector<std::string> queryStringParts(queryParameters.size()); - std::transform( - queryParameters.begin(), queryParameters.end(), - queryStringParts.begin(), - [](const QueryParameter & queryParameter) -> std::string { - return queryParameter.first + "=" + queryParameter.second; - } - ); + std::transform(queryParameters.begin(), queryParameters.end(), + queryStringParts.begin(), + [](const QueryParameter &queryParameter) -> std::string { + return queryParameter.first + "=" + queryParameter.second; + }); const auto queryString = boost::algorithm::join(queryStringParts, "&"); const auto url = queryString.size() == 0 ? uri : uri + "?" + queryString; - g_log.debug() - << "About to make a call to the following ONCat URL: " << url; + g_log.debug() << "About to make a call to the following ONCat URL: " << url; try { m_internetHelper->sendRequest(url, response); - } catch (InternetError & ie) { - if ( - ie.errorCode() == HTTPResponse::HTTP_UNAUTHORIZED - ) { + } catch (InternetError &ie) { + if (ie.errorCode() == HTTPResponse::HTTP_UNAUTHORIZED) { std::string errorMessage; - switch(m_flow) { - case OAuthFlow::RESOURCE_OWNER_CREDENTIALS : - errorMessage = "You have been logged out. Please login again."; - break; - case OAuthFlow::CLIENT_CREDENTIALS : - errorMessage = + switch (m_flow) { + case OAuthFlow::RESOURCE_OWNER_CREDENTIALS: + errorMessage = "You have been logged out. Please login again."; + break; + case OAuthFlow::CLIENT_CREDENTIALS: + errorMessage = "The stored OAuth token appears to be invalid. " "There are a few cases where this might be expected, but in " "principle this should rarely happen. " "Please try again and if the problem persists contact the " "ONCat administrator at oncat-support@ornl.gov."; - break; + break; } // The ONCat API does *not* leak information in the case where a // resource exists but a user is not allowed access -- a 404 would diff --git a/Framework/Catalog/src/ONCatEntity.cpp b/Framework/Catalog/src/ONCatEntity.cpp index 862cb6ff6a5..23538caf043 100644 --- a/Framework/Catalog/src/ONCatEntity.cpp +++ b/Framework/Catalog/src/ONCatEntity.cpp @@ -21,24 +21,19 @@ namespace { class ContentError : public std::runtime_error { public: - explicit ContentError(const std::string & message) : - std::runtime_error(message) {} + explicit ContentError(const std::string &message) + : std::runtime_error(message) {} }; -Content getNestedContent( - const Content & content, const std::string & path -) { - const auto pathTokens = StringTokenizer( - path, ".", Mantid::Kernel::StringTokenizer::TOK_TRIM - ); +Content getNestedContent(const Content &content, const std::string &path) { + const auto pathTokens = + StringTokenizer(path, ".", Mantid::Kernel::StringTokenizer::TOK_TRIM); auto currentNode = content; // Use the path tokens to drill down through the JSON nodes. - for ( - auto pathToken = pathTokens.cbegin(); - pathToken != pathTokens.cend(); ++pathToken - ) { + for (auto pathToken = pathTokens.cbegin(); pathToken != pathTokens.cend(); + ++pathToken) { if (!currentNode.isMember(*pathToken)) { throw ContentError(""); } @@ -48,135 +43,113 @@ Content getNestedContent( return currentNode; } -template<typename T> -T getNestedContentValueAsType( - const Content & content, const std::string & path -); -template<> std::string getNestedContentValueAsType( - const Content & content, const std::string & path -) { return getNestedContent(content, path).asString(); } -template<> int getNestedContentValueAsType( - const Content & content, const std::string & path -) { return getNestedContent(content, path).asInt(); } -template<> float getNestedContentValueAsType( - const Content & content, const std::string & path -) { return getNestedContent(content, path).asFloat(); } -template<> double getNestedContentValueAsType( - const Content & content, const std::string & path -) { return getNestedContent(content, path).asDouble(); } -template<> bool getNestedContentValueAsType( - const Content & content, const std::string & path -) { return getNestedContent(content, path).asBool(); } - -template<typename T> -T getNestedContentValueElseDefault( - const Content & content, const std::string & path, T defaultValue -) { +template <typename T> +T getNestedContentValueAsType(const Content &content, const std::string &path); +template <> +std::string getNestedContentValueAsType(const Content &content, + const std::string &path) { + return getNestedContent(content, path).asString(); +} +template <> +int getNestedContentValueAsType(const Content &content, + const std::string &path) { + return getNestedContent(content, path).asInt(); +} +template <> +float getNestedContentValueAsType(const Content &content, + const std::string &path) { + return getNestedContent(content, path).asFloat(); +} +template <> +double getNestedContentValueAsType(const Content &content, + const std::string &path) { + return getNestedContent(content, path).asDouble(); +} +template <> +bool getNestedContentValueAsType(const Content &content, + const std::string &path) { + return getNestedContent(content, path).asBool(); +} + +template <typename T> +T getNestedContentValueElseDefault(const Content &content, + const std::string &path, T defaultValue) { try { return getNestedContentValueAsType<T>(content, path); - } catch (ContentError & ce) { + } catch (ContentError &ce) { return defaultValue; } } -template<typename T> -boost::optional<T> getNestedContentValueIfPresent( - const Content & content, const std::string & path -) { +template <typename T> +boost::optional<T> getNestedContentValueIfPresent(const Content &content, + const std::string &path) { try { return boost::make_optional(getNestedContentValueAsType<T>(content, path)); - } catch (ContentError & ce) { + } catch (ContentError &ce) { return boost::none; } } - } //---------------------------------------------------------------------- // ONCatEntity //---------------------------------------------------------------------- -ONCatEntity::ONCatEntity( - const std::string & id, - const std::string & type, - Content_uptr content -) : - m_id(id), - m_type(type), - m_content(std::move(content)) {} +ONCatEntity::ONCatEntity(const std::string &id, const std::string &type, + Content_uptr content) + : m_id(id), m_type(type), m_content(std::move(content)) {} -ONCatEntity::ONCatEntity(const ONCatEntity & other) : - m_id(other.m_id), - m_type(other.m_type), - m_content(make_unique<Content>(*other.m_content)) {} +ONCatEntity::ONCatEntity(const ONCatEntity &other) + : m_id(other.m_id), m_type(other.m_type), + m_content(make_unique<Content>(*other.m_content)) {} ONCatEntity::~ONCatEntity() {} -std::string ONCatEntity::id() const { - return m_id; -} +std::string ONCatEntity::id() const { return m_id; } -std::string ONCatEntity::type() const { - return m_type; -} +std::string ONCatEntity::type() const { return m_type; } -std::string ONCatEntity::asString( - const std::string & path, const std::string defaultValue -) const { +std::string ONCatEntity::asString(const std::string &path, + const std::string defaultValue) const { return getNestedContentValueElseDefault(*m_content, path, defaultValue); } -int ONCatEntity::asInt( - const std::string & path, int defaultValue -) const { +int ONCatEntity::asInt(const std::string &path, int defaultValue) const { return getNestedContentValueElseDefault(*m_content, path, defaultValue); } -float ONCatEntity::asFloat( - const std::string & path, float defaultValue -) const { +float ONCatEntity::asFloat(const std::string &path, float defaultValue) const { return getNestedContentValueElseDefault(*m_content, path, defaultValue); } -double ONCatEntity::asDouble( - const std::string & path, double defaultValue -) const { +double ONCatEntity::asDouble(const std::string &path, + double defaultValue) const { return getNestedContentValueElseDefault(*m_content, path, defaultValue); } -bool ONCatEntity::asBool( - const std::string & path, bool defaultValue -) const { +bool ONCatEntity::asBool(const std::string &path, bool defaultValue) const { return getNestedContentValueElseDefault(*m_content, path, defaultValue); } -boost::optional<std::string> ONCatEntity::asString( - const std::string & path -) const { +boost::optional<std::string> +ONCatEntity::asString(const std::string &path) const { return getNestedContentValueIfPresent<std::string>(*m_content, path); } -boost::optional<int> ONCatEntity::asInt( - const std::string & path -) const { +boost::optional<int> ONCatEntity::asInt(const std::string &path) const { return getNestedContentValueIfPresent<int>(*m_content, path); } -boost::optional<float> ONCatEntity::asFloat( - const std::string & path -) const { +boost::optional<float> ONCatEntity::asFloat(const std::string &path) const { return getNestedContentValueIfPresent<float>(*m_content, path); } -boost::optional<double> ONCatEntity::asDouble( - const std::string & path -) const { +boost::optional<double> ONCatEntity::asDouble(const std::string &path) const { return getNestedContentValueIfPresent<double>(*m_content, path); } -boost::optional<bool> ONCatEntity::asBool( - const std::string & path -) const { +boost::optional<bool> ONCatEntity::asBool(const std::string &path) const { return getNestedContentValueIfPresent<bool>(*m_content, path); } @@ -184,14 +157,12 @@ std::string ONCatEntity::toString() const { return m_content->toStyledString(); } -ONCatEntity ONCatEntity::fromJSONStream( - std::istream & streamContent -) { +ONCatEntity ONCatEntity::fromJSONStream(std::istream &streamContent) { auto content = make_unique<Content>(); try { streamContent >> *content; - } catch (Json::Exception & je) { + } catch (Json::Exception &je) { throw MalformedRepresentationError(je.what()); } @@ -200,47 +171,41 @@ ONCatEntity ONCatEntity::fromJSONStream( if (id == "" || type == "") { throw MalformedRepresentationError( - "Expected \"id\" and \"type\" attributes from ONCat API, but these " - "were not found." - ); + "Expected \"id\" and \"type\" attributes from ONCat API, but these " + "were not found."); } return ONCatEntity(id, type, std::move(content)); } -std::vector<ONCatEntity> ONCatEntity::vectorFromJSONStream( - std::istream & streamContent -) { +std::vector<ONCatEntity> +ONCatEntity::vectorFromJSONStream(std::istream &streamContent) { auto content = make_unique<Content>(); try { streamContent >> *content; - } catch (Json::Exception & je) { + } catch (Json::Exception &je) { throw MalformedRepresentationError(je.what()); } if (!content->isArray()) { throw MalformedRepresentationError( - "Expected JSON representation to be an array of entities." - ); + "Expected JSON representation to be an array of entities."); } std::vector<ONCatEntity> entities; - for (const auto & subContent : *content) { + for (const auto &subContent : *content) { const auto id = subContent.get("id", "").asString(); const auto type = subContent.get("type", "").asString(); if (id == "" || type == "") { throw MalformedRepresentationError( - "Expected \"id\" and \"type\" attributes from ONCat API, but these " - "were not found." - ); + "Expected \"id\" and \"type\" attributes from ONCat API, but these " + "were not found."); } - entities.push_back( - ONCatEntity(id, type, make_unique<Content>(subContent)) - ); + entities.push_back(ONCatEntity(id, type, make_unique<Content>(subContent))); } return entities; diff --git a/Framework/Catalog/test/OAuthTest.h b/Framework/Catalog/test/OAuthTest.h index ec326739a3e..c10d2e03bff 100644 --- a/Framework/Catalog/test/OAuthTest.h +++ b/Framework/Catalog/test/OAuthTest.h @@ -21,23 +21,19 @@ public: void test_oauth_token_from_json_stream() { std::stringstream tokenStringSteam; tokenStringSteam << std::string( - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " - "\"scope\": \"api:read data:read settings:read\", " - "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}" - ); + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " + "\"scope\": \"api:read data:read settings:read\", " + "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}"); const auto oauthToken = OAuthToken::fromJSONStream(tokenStringSteam); TS_ASSERT_EQUALS(oauthToken.tokenType(), std::string("Bearer")); TS_ASSERT_EQUALS(oauthToken.expiresIn(), 3600); - TS_ASSERT_EQUALS( - oauthToken.accessToken(), - std::string("2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ") - ); - TS_ASSERT_EQUALS( - oauthToken.scope(), std::string("api:read data:read settings:read")); - TS_ASSERT_EQUALS( - oauthToken.refreshToken(), std::string("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb") - ); + TS_ASSERT_EQUALS(oauthToken.accessToken(), + std::string("2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ")); + TS_ASSERT_EQUALS(oauthToken.scope(), + std::string("api:read data:read settings:read")); + TS_ASSERT_EQUALS(oauthToken.refreshToken(), + std::string("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb")); TS_ASSERT(!oauthToken.isExpired()); TS_ASSERT(oauthToken.isExpired(DateAndTime::getCurrentTime() + 3601.0)); diff --git a/Framework/Catalog/test/ONCatEntityTest.h b/Framework/Catalog/test/ONCatEntityTest.h index 54f8582632b..dc331d5c989 100644 --- a/Framework/Catalog/test/ONCatEntityTest.h +++ b/Framework/Catalog/test/ONCatEntityTest.h @@ -12,41 +12,38 @@ using Mantid::Catalog::ONCat::ONCatEntity; class ONCatEntityTest : public CxxTest::TestSuite { public: // CxxTest boilerplate. - static ONCatEntityTest *createSuite() { - return new ONCatEntityTest(); - } + static ONCatEntityTest *createSuite() { return new ONCatEntityTest(); } static void destroySuite(ONCatEntityTest *suite) { delete suite; } void test_basic_attributes() { std::string dummyRepresentation = - "{" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," - " \"type\": \"dummy\"" - "}"; + "{" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," + " \"type\": \"dummy\"" + "}"; std::stringstream ss; ss << dummyRepresentation; auto dummy = ONCatEntity::fromJSONStream(ss); - TS_ASSERT_EQUALS( - dummy.id(), std::string("3fa1d522-f1b8-4134-a56b-b61f24d20510") - ); + TS_ASSERT_EQUALS(dummy.id(), + std::string("3fa1d522-f1b8-4134-a56b-b61f24d20510")); TS_ASSERT_EQUALS(dummy.type(), std::string("dummy")); } void test_basic_attributes_of_entity_vector() { std::string dummiesRepresentation = - "[" - " {" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," - " \"type\": \"dummy\"" - " }," - " {" - " \"id\": \"4b1dec2a-0f15-416d-8d23-e08901ac4634\"," - " \"type\": \"dummy\"" - " }" - "]"; + "[" + " {" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," + " \"type\": \"dummy\"" + " }," + " {" + " \"id\": \"4b1dec2a-0f15-416d-8d23-e08901ac4634\"," + " \"type\": \"dummy\"" + " }" + "]"; std::stringstream ss; ss << dummiesRepresentation; @@ -55,62 +52,56 @@ public: TS_ASSERT_EQUALS(dummies.size(), 2); - TS_ASSERT_EQUALS( - dummies[0].id(), std::string("3fa1d522-f1b8-4134-a56b-b61f24d20510") - ); + TS_ASSERT_EQUALS(dummies[0].id(), + std::string("3fa1d522-f1b8-4134-a56b-b61f24d20510")); TS_ASSERT_EQUALS(dummies[0].type(), std::string("dummy")); - TS_ASSERT_EQUALS( - dummies[1].id(), std::string("4b1dec2a-0f15-416d-8d23-e08901ac4634") - ); + TS_ASSERT_EQUALS(dummies[1].id(), + std::string("4b1dec2a-0f15-416d-8d23-e08901ac4634")); TS_ASSERT_EQUALS(dummies[1].type(), std::string("dummy")); } void test_throws_on_malformed_json() { std::string malformedRepresentation = - "{" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," - " \"type\": \"dummy"; + "{" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," + " \"type\": \"dummy"; std::stringstream ss; ss << malformedRepresentation; - TS_ASSERT_THROWS( - ONCatEntity::fromJSONStream(ss), - MalformedRepresentationError - ); + TS_ASSERT_THROWS(ONCatEntity::fromJSONStream(ss), + MalformedRepresentationError); } void test_throws_on_malformed_representation() { std::string missingTypeRepresentation = - "{" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"" - "}"; + "{" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"" + "}"; std::stringstream ss; ss << missingTypeRepresentation; - TS_ASSERT_THROWS( - ONCatEntity::fromJSONStream(ss), - MalformedRepresentationError - ); + TS_ASSERT_THROWS(ONCatEntity::fromJSONStream(ss), + MalformedRepresentationError); } void test_nested_values_with_various_types() { std::string dummyRepresentation = - "{" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," - " \"type\": \"dummy\"," - " \"val\": {" - " \"a\": {" - " \"string\": \"value\"," - " \"int\": 1234," - " \"float\": 1234.5," - " \"double\": 1234.5," - " \"bool\": true" - " }" - " }" - "}"; + "{" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," + " \"type\": \"dummy\"," + " \"val\": {" + " \"a\": {" + " \"string\": \"value\"," + " \"int\": 1234," + " \"float\": 1234.5," + " \"double\": 1234.5," + " \"bool\": true" + " }" + " }" + "}"; std::stringstream ss; ss << dummyRepresentation; @@ -133,11 +124,11 @@ public: void test_default_values_with_various_types() { std::string dummyRepresentation = - "{" - " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," - " \"type\": \"dummy\"" - " }" - "}"; + "{" + " \"id\": \"3fa1d522-f1b8-4134-a56b-b61f24d20510\"," + " \"type\": \"dummy\"" + " }" + "}"; std::stringstream ss; ss << dummyRepresentation; diff --git a/Framework/Catalog/test/ONCatTest.h b/Framework/Catalog/test/ONCatTest.h index 933568a8d21..c06e71f54d6 100644 --- a/Framework/Catalog/test/ONCatTest.h +++ b/Framework/Catalog/test/ONCatTest.h @@ -37,43 +37,37 @@ namespace { using MockResponseMap = std::map<std::string, std::pair<int, std::string>>; using MockResponseCallCounts = std::map<std::string, unsigned int>; -using MockResponseCallMapping = std::pair<const std::basic_string<char>, unsigned int>; +using MockResponseCallMapping = + std::pair<const std::basic_string<char>, unsigned int>; class MockONCatAPI : public Mantid::Kernel::InternetHelper { public: MockONCatAPI() = delete; - MockONCatAPI( - const MockResponseMap & responseMap - ) : - Mantid::Kernel::InternetHelper(), - m_responseMap(responseMap), - m_responseCallCounts() - { - for (const auto & mapping : responseMap) { + MockONCatAPI(const MockResponseMap &responseMap) + : Mantid::Kernel::InternetHelper(), m_responseMap(responseMap), + m_responseCallCounts() { + for (const auto &mapping : responseMap) { m_responseCallCounts[mapping.first] = 0; } } - ~MockONCatAPI() { - TS_ASSERT(allResponsesCalledOnce()); - } + ~MockONCatAPI() { TS_ASSERT(allResponsesCalledOnce()); } bool allResponsesCalledOnce() const { - return std::all_of( - m_responseCallCounts.cbegin(), m_responseCallCounts.cend(), - [](const MockResponseCallMapping & mapping){ - return mapping.second == 1; - } - ); + return std::all_of(m_responseCallCounts.cbegin(), + m_responseCallCounts.cend(), + [](const MockResponseCallMapping &mapping) { + return mapping.second == 1; + }); } protected: - int sendHTTPRequest( - const std::string &url, std::ostream & responseStream - ) override { return sendHTTPSRequest(url, responseStream); } + int sendHTTPRequest(const std::string &url, + std::ostream &responseStream) override { + return sendHTTPSRequest(url, responseStream); + } - int sendHTTPSRequest( - const std::string &url, std::ostream & responseStream - ) override { + int sendHTTPSRequest(const std::string &url, + std::ostream &responseStream) override { auto mockResponse = m_responseMap.find(url); assert(mockResponse != m_responseMap.end()); @@ -97,9 +91,8 @@ private: MockResponseCallCounts m_responseCallCounts; }; -std::unique_ptr<MockONCatAPI> make_mock_oncat_api( - const MockResponseMap & responseMap -) { +std::unique_ptr<MockONCatAPI> +make_mock_oncat_api(const MockResponseMap &responseMap) { return Mantid::Kernel::make_unique<MockONCatAPI>(responseMap); } @@ -107,10 +100,11 @@ class MockTokenStore : public IOAuthTokenStore { public: MockTokenStore() : m_token(boost::none) {} - void setToken(const boost::optional<OAuthToken> & token) override { + void setToken(const boost::optional<OAuthToken> &token) override { m_token = token; } boost::optional<OAuthToken> getToken() override { return m_token; } + private: boost::optional<OAuthToken> m_token; }; @@ -122,19 +116,15 @@ IOAuthTokenStore_uptr make_mock_token_store() { IOAuthTokenStore_uptr make_mock_token_store_already_logged_in() { auto tokenStore = Mantid::Kernel::make_unique<MockTokenStore>(); tokenStore->setToken(OAuthToken( - "Bearer", - 3600, - "2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ", - "api:read data:read settings:read", - boost::make_optional<std::string>("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb") - )); + "Bearer", 3600, "2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ", + "api:read data:read settings:read", + boost::make_optional<std::string>("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb"))); return std::move(tokenStore); } const static std::string DUMMY_URL = "https://not.a.real.url"; const static std::string DUMMY_CLIENT_ID = - "0e527a36-297d-4cb4-8a35-84f6b11248d7"; - + "0e527a36-297d-4cb4-8a35-84f6b11248d7"; } //---------------------------------------------------------------------- @@ -148,53 +138,37 @@ public: static void destroySuite(ONCatTest *suite) { delete suite; } void test_login_with_invalid_credentials_throws() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); + ONCat oncat(DUMMY_URL, make_mock_token_store(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); TS_ASSERT(!oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_UNAUTHORIZED, - "{\"error\": \"invalid_grant\", " - "\"error_description\": \"Invalid credentials given.\"}" - ) - } - })); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_UNAUTHORIZED, + "{\"error\": \"invalid_grant\", " + "\"error_description\": \"Invalid credentials given.\"}")}})); - TS_ASSERT_THROWS( - oncat.login("user", "does_not_exist"), - InvalidCredentialsError - ); + TS_ASSERT_THROWS(oncat.login("user", "does_not_exist"), + InvalidCredentialsError); TS_ASSERT(!oncat.isUserLoggedIn()); } void test_login_with_valid_credentials_is_successful() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); + ONCat oncat(DUMMY_URL, make_mock_token_store(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); TS_ASSERT(!oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " - "\"scope\": \"api:read data:read settings:read\", " - "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}" - ) - } - })); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " + "\"scope\": \"api:read data:read settings:read\", " + "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}")}})); oncat.login("user", "does_exist"); @@ -202,24 +176,17 @@ public: } void test_refreshing_token_when_needed() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); - - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " - "\"scope\": \"api:read data:read settings:read\", " - "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}" - ) - } - })); + ONCat oncat(DUMMY_URL, make_mock_token_store(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); + + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " + "\"scope\": \"api:read data:read settings:read\", " + "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}")}})); oncat.login("user", "does_exist"); @@ -228,41 +195,31 @@ public: oncat.refreshTokenIfNeeded(); TS_ASSERT(oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"7dS7flfhsf7ShndHJSFknfskfeu789\", " - "\"scope\": \"api:read data:read settings:read\", " - "\"refresh_token\": \"sdagSDGF87dsgljerg6gdfgddfgfdg\"}" - ) - } - })); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"7dS7flfhsf7ShndHJSFknfskfeu789\", " + "\"scope\": \"api:read data:read settings:read\", " + "\"refresh_token\": \"sdagSDGF87dsgljerg6gdfgddfgfdg\"}")}})); oncat.refreshTokenIfNeeded(DateAndTime::getCurrentTime() + 3601.0); TS_ASSERT(oncat.isUserLoggedIn()); } void test_logged_out_when_refreshing_fails() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); - - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " - "\"scope\": \"api:read data:read settings:read\", " - "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}" - ) - } - })); + ONCat oncat(DUMMY_URL, make_mock_token_store(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); + + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " + "\"scope\": \"api:read data:read settings:read\", " + "\"refresh_token\": \"eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb\"}")}})); oncat.login("user", "does_exist"); @@ -271,89 +228,66 @@ public: oncat.refreshTokenIfNeeded(); TS_ASSERT(oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_UNAUTHORIZED, - "{\"error\": \"invalid_grant\", " - "\"error_description\": \"Bearer token not found.\"}" - ) - } - })); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_UNAUTHORIZED, + "{\"error\": \"invalid_grant\", " + "\"error_description\": \"Bearer token not found.\"}")}})); TS_ASSERT_THROWS( - oncat.refreshTokenIfNeeded(DateAndTime::getCurrentTime() + 3601.0), - InvalidRefreshTokenError - ); + oncat.refreshTokenIfNeeded(DateAndTime::getCurrentTime() + 3601.0), + InvalidRefreshTokenError); TS_ASSERT(!oncat.isUserLoggedIn()); } void test_retrieve_entity() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store_already_logged_in(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); + ONCat oncat(DUMMY_URL, make_mock_token_store_already_logged_in(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); TS_ASSERT(oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/api/instruments/HB2C?facility=HFIR", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"facility\": \"HFIR\"," - "\"name\": \"HB2C\"," - "\"id\": \"HB2C\"," - "\"type\": \"instrument\"}" - ) - } - })); - - const auto entity = oncat.retrieve("api", "instruments", "HB2C", { - QueryParameter("facility", "HFIR") - }); + oncat.setInternetHelper( + make_mock_oncat_api({{DUMMY_URL + "/api/instruments/HB2C?facility=HFIR", + std::make_pair(HTTPResponse::HTTP_OK, + "{\"facility\": \"HFIR\"," + "\"name\": \"HB2C\"," + "\"id\": \"HB2C\"," + "\"type\": \"instrument\"}")}})); + + const auto entity = oncat.retrieve("api", "instruments", "HB2C", + {QueryParameter("facility", "HFIR")}); TS_ASSERT_EQUALS(entity.id(), std::string("HB2C")); TS_ASSERT_EQUALS(entity.asString("name"), std::string("HB2C")); } void test_list_entities() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store_already_logged_in(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); + ONCat oncat(DUMMY_URL, make_mock_token_store_already_logged_in(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); TS_ASSERT(oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/api/instruments?facility=HFIR", std::make_pair( - HTTPResponse::HTTP_OK, - "[" - " {" - " \"facility\": \"HFIR\"," - " \"name\": \"HB2C\"," - " \"id\": \"HB2C\"," - " \"type\": \"instrument\"" - " }," - " {" - " \"facility\": \"HFIR\"," - " \"name\": \"CG1D\"," - " \"id\": \"CG1D\"," - " \"type\": \"instrument\"" - " }" - "]" - ) - } - })); - - const auto entities = oncat.list("api", "instruments", { - QueryParameter("facility", "HFIR") - }); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/api/instruments?facility=HFIR", + std::make_pair(HTTPResponse::HTTP_OK, "[" + " {" + " \"facility\": \"HFIR\"," + " \"name\": \"HB2C\"," + " \"id\": \"HB2C\"," + " \"type\": \"instrument\"" + " }," + " {" + " \"facility\": \"HFIR\"," + " \"name\": \"CG1D\"," + " \"id\": \"CG1D\"," + " \"type\": \"instrument\"" + " }" + "]")}})); + + const auto entities = + oncat.list("api", "instruments", {QueryParameter("facility", "HFIR")}); TS_ASSERT_EQUALS(entities.size(), 2); TS_ASSERT_EQUALS(entities[0].id(), std::string("HB2C")); @@ -363,74 +297,51 @@ public: } void test_send_api_request_logs_out_with_invalid_grant() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store_already_logged_in(), - OAuthFlow::RESOURCE_OWNER_CREDENTIALS, - DUMMY_CLIENT_ID - ); + ONCat oncat(DUMMY_URL, make_mock_token_store_already_logged_in(), + OAuthFlow::RESOURCE_OWNER_CREDENTIALS, DUMMY_CLIENT_ID); TS_ASSERT(oncat.isUserLoggedIn()); - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/api/instruments?facility=HFIR", std::make_pair( - HTTPResponse::HTTP_UNAUTHORIZED, "{}" - ) - } - })); + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/api/instruments?facility=HFIR", + std::make_pair(HTTPResponse::HTTP_UNAUTHORIZED, "{}")}})); TS_ASSERT_THROWS( - oncat.list("api", "instruments", {QueryParameter("facility", "HFIR")}), - TokenRejectedError - ); + oncat.list("api", "instruments", {QueryParameter("facility", "HFIR")}), + TokenRejectedError); TS_ASSERT(!oncat.isUserLoggedIn()); } void test_client_credentials_flow_with_refresh() { - ONCat oncat( - DUMMY_URL, - make_mock_token_store(), - OAuthFlow::CLIENT_CREDENTIALS, - DUMMY_CLIENT_ID, - boost::make_optional<std::string>( - "9a2ad07a-a139-438b-8116-08c5452f96ad" - ) - ); - - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " - "\"scope\": \"api:read data:read settings:read\"}" - ) - }, { - DUMMY_URL + "/api/instruments/HB2C?facility=HFIR", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"facility\": \"HFIR\"," - "\"name\": \"HB2C\"," - "\"id\": \"HB2C\"," - "\"type\": \"instrument\"}" - ) - } - })); - - oncat.retrieve("api", "instruments", "HB2C", { - QueryParameter("facility", "HFIR") - }); - - oncat.setInternetHelper(make_mock_oncat_api({ - { - DUMMY_URL + "/oauth/token", std::make_pair( - HTTPResponse::HTTP_OK, - "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " - "\"access_token\": \"987JHGFiusdvs72fAkjhsKJH32tkjk\", " - "\"scope\": \"api:read data:read settings:read\"}" - ), - } - })); + ONCat oncat(DUMMY_URL, make_mock_token_store(), + OAuthFlow::CLIENT_CREDENTIALS, DUMMY_CLIENT_ID, + boost::make_optional<std::string>( + "9a2ad07a-a139-438b-8116-08c5452f96ad")); + + oncat.setInternetHelper(make_mock_oncat_api( + {{DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ\", " + "\"scope\": \"api:read data:read settings:read\"}")}, + {DUMMY_URL + "/api/instruments/HB2C?facility=HFIR", + std::make_pair(HTTPResponse::HTTP_OK, + "{\"facility\": \"HFIR\"," + "\"name\": \"HB2C\"," + "\"id\": \"HB2C\"," + "\"type\": \"instrument\"}")}})); + + oncat.retrieve("api", "instruments", "HB2C", + {QueryParameter("facility", "HFIR")}); + + oncat.setInternetHelper(make_mock_oncat_api({{ + DUMMY_URL + "/oauth/token", + std::make_pair( + HTTPResponse::HTTP_OK, + "{\"token_type\": \"Bearer\", \"expires_in\": 3600, " + "\"access_token\": \"987JHGFiusdvs72fAkjhsKJH32tkjk\", " + "\"scope\": \"api:read data:read settings:read\"}"), }})); oncat.refreshTokenIfNeeded(DateAndTime::getCurrentTime() + 3601.0); } @@ -439,12 +350,9 @@ public: ConfigServiceTokenStore tokenStore; const auto testToken = boost::make_optional(OAuthToken( - "Bearer", - 3600, - "2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ", - "api:read data:read settings:read", - boost::make_optional<std::string>("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb") - )); + "Bearer", 3600, "2KSL5aEnLvIudMHIjc7LcBWBCfxOHZ", + "api:read data:read settings:read", + boost::make_optional<std::string>("eZEiz7LbgFrkL5ZHv7R4ck9gOzXexb"))); tokenStore.setToken(testToken); diff --git a/Framework/Kernel/src/InternetHelper.cpp b/Framework/Kernel/src/InternetHelper.cpp index b516afa6590..0766661b2c9 100644 --- a/Framework/Kernel/src/InternetHelper.cpp +++ b/Framework/Kernel/src/InternetHelper.cpp @@ -136,11 +136,9 @@ void InternetHelper::createRequest(Poco::URI &uri) { m_request->setContentType(m_contentType); } - m_request->set( - "User-Agent", - // Use standard User-Agent format as per MDN documentation. - std::string("Mantid/") + MantidVersion::version() - ); + m_request->set("User-Agent", + // Use standard User-Agent format as per MDN documentation. + std::string("Mantid/") + MantidVersion::version()); if (m_method == "POST") { // HTTP states that the 'Content-Length' header should not be included // if the 'Transfer-Encoding' header is set. UNKNOWN_CONTENT_LENGTH -- GitLab