diff options
author | Jürgen Gehring <juergen.gehring@bmw.de> | 2015-06-11 06:57:47 -0700 |
---|---|---|
committer | Jürgen Gehring <juergen.gehring@bmw.de> | 2015-06-11 06:57:47 -0700 |
commit | 6c463fcc3dcee619925f08ea09e19a86b9e581cc (patch) | |
tree | 17e765e0623c58778150605d1cd0340c658ce6ab /src/CommonAPI | |
parent | 1d83eb38e546e0165f1ad6821f04445b2b9b19d2 (diff) | |
download | genivi-common-api-runtime-6c463fcc3dcee619925f08ea09e19a86b9e581cc.tar.gz |
CommonAPI 3.1.1
Diffstat (limited to 'src/CommonAPI')
39 files changed, 844 insertions, 4910 deletions
diff --git a/src/CommonAPI/Address.cpp b/src/CommonAPI/Address.cpp new file mode 100644 index 0000000..2315a9c --- /dev/null +++ b/src/CommonAPI/Address.cpp @@ -0,0 +1,122 @@ +// Copyright (C) 2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <sstream> + +#include <CommonAPI/Address.hpp> + +namespace CommonAPI { + +Address::Address(const std::string &_address) { + // TODO: handle error situation (_address is no valid CommonAPI address) + setAddress(_address); +} + +Address::Address(const std::string &_domain, + const std::string &_interface, + const std::string &_instance) + : domain_(_domain), + interface_(_interface), + instance_(_instance) { +} + +Address::Address(const Address &_source) + : domain_(_source.domain_), + interface_(_source.interface_), + instance_(_source.instance_) { +} + +Address::~Address() { +} + +bool +Address::operator ==(const Address &_other) const { + return (domain_ == _other.domain_ && + interface_ == _other.interface_ && + instance_ == _other.instance_); +} + +bool +Address::operator !=(const Address &_other) const { + return (domain_ != _other.domain_ || + interface_ != _other.interface_ || + instance_ != _other.instance_); +} + +bool +Address::operator<(const Address &_other) const { + if (domain_ < _other.domain_) + return true; + + if (domain_ == _other.domain_) { + if (interface_ < _other.interface_) + return true; + + if (interface_ == _other.interface_) { + if (instance_ < _other.instance_) + return true; + } + } + + return false; +} + +std::string +Address::getAddress() const { + return (domain_ + ":" + interface_ + ":" + instance_); +} + +void +Address::setAddress(const std::string &_address) { + std::istringstream addressStream(_address); + if (std::getline(addressStream, domain_, ':')) { + if (std::getline(addressStream, interface_, ':')) { + if(!std::getline(addressStream, instance_, ':')) { + if(std::getline(addressStream, instance_)) { + } + } + } + } +} + +const std::string & +Address::getDomain() const { + return domain_; +} + +void +Address::setDomain(const std::string &_domain) { + domain_ = _domain; +} + +const std::string & +Address::getInterface() const { + return interface_; +} + +void +Address::setInterface(const std::string &_interface) { + interface_ = _interface; +} + +const std::string & +Address::getInstance() const { + return instance_; +} + +void +Address::setInstance(const std::string &_instance) { + instance_ = _instance; +} + +std::ostream & +operator<<(std::ostream &_out, const Address &_address) { + _out << _address.domain_ + << ":" << _address.interface_ + << ":" << _address.instance_; + return _out; +} + +} // namespace CommonAPI diff --git a/src/CommonAPI/Attribute.h b/src/CommonAPI/Attribute.h deleted file mode 100644 index 51990c3..0000000 --- a/src/CommonAPI/Attribute.h +++ /dev/null @@ -1,137 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_ATTRIBUTE_H_ -#define COMMONAPI_ATTRIBUTE_H_ - -#include "types.h" -#include "Event.h" - -#include <cstdint> -#include <functional> -#include <future> -#include <memory> - - -namespace CommonAPI { - -/** - * \brief Class representing a read only attribute - * - * Class representing a read only attribute - */ -template <typename _ValueType> -class ReadonlyAttribute { - public: - typedef _ValueType ValueType; - typedef std::function<void(const CallStatus&, _ValueType)> AttributeAsyncCallback; - - virtual ~ReadonlyAttribute() { } - - /** - * \brief Get value of attribute, usually from remote. Synchronous call. - * - * Get value of attribute, usually from remote. Synchronous call. - * - * @param value Reference to be filled with value. - * @return Call status of the operation. - */ - virtual void getValue(CallStatus& callStaus, _ValueType& value) const = 0; - - /** - * \brief Get value of attribute, usually from remote. Asynchronous call. - * - * Get value of attribute, usually from remote. Asynchronous call. - * - * @param attributeAsyncCallback std::function object for the callback to be invoked. - * @return std::future containing the call status of the operation. - */ - virtual std::future<CallStatus> getValueAsync(AttributeAsyncCallback attributeAsyncCallback) = 0; -}; - -/** - * \brief Class representing a read and writable attribute - * - * Class representing a read and writable attribute - */ -template <typename _ValueType> -class Attribute: public ReadonlyAttribute<_ValueType> { - public: - typedef typename ReadonlyAttribute<_ValueType>::ValueType ValueType; - typedef typename ReadonlyAttribute<_ValueType>::AttributeAsyncCallback AttributeAsyncCallback; - - virtual ~Attribute() { } - - /** - * \brief Set value of attribute, usually to remote. Synchronous call. - * - * Set value of attribute, usually to remote. Synchronous call. - * - * @param requestValue Value to be set - * @param callStatus call status reference will be filled with status of the operation - * @param responseValue Reference which will contain the actuall value set by the remote. - */ - virtual void setValue(const _ValueType& requestValue, CallStatus& callStatus, _ValueType& responseValue) = 0; - - /** - * \brief Set value of attribute, usually to remote. Asynchronous call. - * - * Set value of attribute, usually to remote. Asynchronous call. - * - * @param requestValue Value to be set - * @param attributeAsyncCallback std::function object for the callback to be invoked. - * @return std::future containing the call status of the operation. - */ - virtual std::future<CallStatus> setValueAsync(const _ValueType& requestValue, - AttributeAsyncCallback attributeAsyncCallback) = 0; -}; - -/** - * \brief Class representing an observable attribute - * - * Class representing an observable attribute - */ -template <typename _AttributeBaseClass> -class _ObservableAttributeImpl: public _AttributeBaseClass { - public: - typedef typename _AttributeBaseClass::ValueType ValueType; - typedef typename _AttributeBaseClass::AttributeAsyncCallback AttributeAsyncCallback; - typedef Event<ValueType> ChangedEvent; - - virtual ~_ObservableAttributeImpl() { } - - /** - * \brief Returns the event handler for the remote change notifiaction event - * - * Returns the event handler for the remote change notifiaction event - * - * @return The event handler object - */ - virtual ChangedEvent& getChangedEvent() = 0; -}; - -template <typename _ValueType> -struct ObservableReadonlyAttribute: _ObservableAttributeImpl< ReadonlyAttribute<_ValueType> > { -}; - -template <typename _ValueType> -struct ObservableAttribute: _ObservableAttributeImpl< Attribute<_ValueType> > { -}; - -#ifdef WIN32 -struct WINDummyAttribute { - WINDummyAttribute() {} -}; -#endif - -} // namespace CommonAPI - -#endif // COMMONAPI_ATTRIBUTE_H_ diff --git a/src/CommonAPI/AttributeExtension.h b/src/CommonAPI/AttributeExtension.h deleted file mode 100644 index 4cea9b1..0000000 --- a/src/CommonAPI/AttributeExtension.h +++ /dev/null @@ -1,56 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMON_API_DBUS_ATTRIBUTE_EXTENSION_H_ -#define COMMON_API_DBUS_ATTRIBUTE_EXTENSION_H_ - -#include "types.h" -#include "Event.h" - -#include <cstdint> -#include <functional> -#include <memory> - - -namespace CommonAPI { - -template<typename _AttributeType> -class AttributeExtension { - public: - _AttributeType& getBaseAttribute() { - return baseAttribute_; - } - - protected: - AttributeExtension() = delete; - AttributeExtension(_AttributeType& baseAttribute): baseAttribute_(baseAttribute) { - } - - _AttributeType& baseAttribute_; -}; - -#ifdef WIN32 -template<typename _AttributeType> -class WINDummyAttributeExtension : public CommonAPI::AttributeExtension<_AttributeType> { - typedef AttributeExtension<_AttributeType> __baseClass_t; - WINDummyAttribute dummyAttribute; -public: - WINDummyAttributeExtension() {}; - WINDummyAttributeExtension(Proxy& proxy) : - AttributeExtension<_AttributeType>(dummyAttribute) {} - - ~WINDummyAttributeExtension() {} -}; -#endif - -} // namespace CommonAPI - -#endif // COMMON_API_DBUS_ATTRIBUTE_EXTENSION_H_ diff --git a/src/CommonAPI/ByteBuffer.h b/src/CommonAPI/ByteBuffer.h deleted file mode 100644 index e92b157..0000000 --- a/src/CommonAPI/ByteBuffer.h +++ /dev/null @@ -1,19 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef COMMONAPI_BYTE_BUFFER_H_ -#define COMMONAPI_BYTE_BUFFER_H_ - -#include <vector> -#include <cstdint> - -namespace CommonAPI { - -typedef std::vector<uint8_t> ByteBuffer; - -} // namespace CommonAPI - -#endif // COMMONAPI_BYTE_BUFFER_H_ diff --git a/src/CommonAPI/CommonAPI.h b/src/CommonAPI/CommonAPI.h deleted file mode 100644 index 27c0767..0000000 --- a/src/CommonAPI/CommonAPI.h +++ /dev/null @@ -1,25 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef COMMONAPI_H_ -#define COMMONAPI_H_ - - -#ifndef COMMONAPI_INTERNAL_COMPILATION -#define COMMONAPI_INTERNAL_COMPILATION -#endif - -#include "Runtime.h" -#include "Factory.h" -#include "AttributeExtension.h" -#include "ByteBuffer.h" -#include "types.h" - -#undef COMMONAPI_INTERNAL_COMPILATION - - -#endif /* COMMONAPI_H_ */ diff --git a/src/CommonAPI/Configuration.cpp b/src/CommonAPI/Configuration.cpp deleted file mode 100644 index d15a75a..0000000 --- a/src/CommonAPI/Configuration.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include <fstream> - -#include "Configuration.h" -#include "utils.h" - - -namespace CommonAPI { - -std::unordered_map<std::string, std::string> knownMiddlewareAliases_; -std::unordered_map<std::string, std::string> knownMiddlewarePaths_; -std::unordered_map<std::string, std::vector<std::string> > knownGeneratedPaths_; -std::vector<std::string> librarySearchPaths_; -std::string defaultBindingIdentifier_ = ""; - - -const Configuration& Configuration::getInstance() { - static Configuration* instance = NULL; - if (!instance) { - instance = new Configuration(); - instance->retrieveCommonApiConfiguration(); - } - return *instance; -} - -const std::vector<std::string>& Configuration::getLibrarySearchPaths() const { - return librarySearchPaths_; -} - -const std::string& Configuration::getMiddlewareNameForAlias(const std::string& alias) const { - auto foundMiddlewareName = knownMiddlewareAliases_.find(alias); - if (foundMiddlewareName != knownMiddlewareAliases_.end()) { - return foundMiddlewareName->second; - } else { - return alias; - } -} - -const std::string& Configuration::getMiddlewareLibraryPath(const std::string& middlewareIdentifier) const { - auto foundMiddlewarePath = knownMiddlewarePaths_.find(middlewareIdentifier); - if (foundMiddlewarePath == knownMiddlewarePaths_.end()) { - static const std::string emptyReturn = ""; - return emptyReturn; - } - return foundMiddlewarePath->second; -} - -const std::vector<std::string>& Configuration::getGenericLibraryPaths(const std::string& middlewareIdentifier) const { - const auto& generatedPathsForMiddleware = knownGeneratedPaths_.find(middlewareIdentifier); - if (generatedPathsForMiddleware != knownGeneratedPaths_.end()) { - return generatedPathsForMiddleware->second; - } - static const std::vector<std::string> emptyReturn; - return emptyReturn; -} - -const std::string& Configuration::getDefaultMiddlewareIdentifier() const { - return defaultBindingIdentifier_; -} - -void Configuration::readConfigFile(std::ifstream& addressConfigFile) { - std::string currentlyParsedBindingIdentifier = ""; - - std::string readLine; - - while (addressConfigFile.good()) { - getline(addressConfigFile, readLine); - const size_t readLineLength = readLine.length(); - - if (strncmp(readLine.c_str(), CATEGORY_IDENTIFIER_BINDING, strlen(CATEGORY_IDENTIFIER_BINDING)) == 0 - && readLine[readLineLength - 1] == CATEGORY_ENDING) { - - std::string newBindingIdentifier = readLine.substr( - strlen(CATEGORY_IDENTIFIER_BINDING), - readLineLength - (strlen(CATEGORY_IDENTIFIER_BINDING) + 1)); - - trim(newBindingIdentifier); - if (containsOnlyAlphanumericCharacters(newBindingIdentifier)) { - currentlyParsedBindingIdentifier = newBindingIdentifier; - } - - } else if (currentlyParsedBindingIdentifier != "") { - std::vector<std::string> parameterElements = split(readLine, '='); - if (parameterElements.size() == 2) { - - if (parameterElements.at(0) == BINDING_PARAMETER_ALIAS) { - std::vector<std::string> aliases = split(parameterElements.at(1), ':'); - for (const std::string& singleAlias: aliases) { - knownMiddlewareAliases_.insert( {singleAlias, currentlyParsedBindingIdentifier}); - } - - } else if (parameterElements.at(0) == BINDING_PARAMETER_LIBPATH) { - knownMiddlewarePaths_.insert( {currentlyParsedBindingIdentifier, parameterElements.at(1)}); - - } else if (parameterElements.at(0) == BINDING_PARAMETER_GENPATH) { - std::vector<std::string> paths = split(parameterElements.at(1), ':'); - auto alreadyKnownPaths = knownGeneratedPaths_.find(currentlyParsedBindingIdentifier); - - if (alreadyKnownPaths == knownGeneratedPaths_.end()) { - const std::vector<std::string> pathSet(paths.begin(), paths.end()); - knownGeneratedPaths_.insert( {currentlyParsedBindingIdentifier, std::move(pathSet)} ); - } else { - alreadyKnownPaths->second.insert(alreadyKnownPaths->second.end(), paths.begin(), paths.end()); - } - } - - } else if (parameterElements.size() == 1) { - if (parameterElements.at(0) == BINDING_PARAMETER_DEFAULT && defaultBindingIdentifier_ == "") { - defaultBindingIdentifier_ = currentlyParsedBindingIdentifier; - } - } - } - } -} - - -void Configuration::readEnvironmentVariables() { - librarySearchPaths_ = split(COMMONAPI_STD_LIB_PATH, ':'); - - bool errorOccured = false; -#ifdef WIN32 - char* environmentBindingPath; - size_t len; - errno_t err = _dupenv_s(&environmentBindingPath, &len, COMMONAPI_ENVIRONMENT_BINDING_PATH); - if (err != 0 || environmentBindingPath == NULL) { - errorOccured = true; - } -#else - const char* environmentBindingPath = getenv(COMMONAPI_ENVIRONMENT_BINDING_PATH); - if (!environmentBindingPath) { - errorOccured = true; - } -#endif - - if (!errorOccured) { - std::vector<std::string> environmentPaths = split(environmentBindingPath, ':'); - librarySearchPaths_.insert(librarySearchPaths_.begin(), environmentPaths.begin(), environmentPaths.end()); - } -} - - -void Configuration::retrieveCommonApiConfiguration() { - readEnvironmentVariables(); - - std::string fqnOfConfigFile = getCurrentBinaryFileFQN(); - fqnOfConfigFile += COMMONAPI_CONFIG_SUFFIX; - - std::ifstream commonapiConfigFile; - commonapiConfigFile.open(fqnOfConfigFile.c_str()); - - if (commonapiConfigFile.is_open()) { - readConfigFile(commonapiConfigFile); - commonapiConfigFile.close(); - } - - commonapiConfigFile.clear(); - std::vector<std::string> splittedConfigFQN = split(fqnOfConfigFile, '/'); - std::string globalConfigFQN = COMMONAPI_GLOBAL_CONFIG_ROOT + splittedConfigFQN.at(splittedConfigFQN.size() - 1); - commonapiConfigFile.open(globalConfigFQN); - if (commonapiConfigFile.is_open()) { - readConfigFile(commonapiConfigFile); - commonapiConfigFile.close(); - } - commonapiConfigFile.clear(); - - commonapiConfigFile.open(COMMONAPI_GLOBAL_CONFIG_FQN); - if (commonapiConfigFile.is_open()) { - readConfigFile(commonapiConfigFile); - commonapiConfigFile.close(); - } -} - - -} // namespace CommonAPI diff --git a/src/CommonAPI/Configuration.h b/src/CommonAPI/Configuration.h deleted file mode 100644 index 554518e..0000000 --- a/src/CommonAPI/Configuration.h +++ /dev/null @@ -1,121 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef COMMONAPI_CONFIGURATION_H_ -#define COMMONAPI_CONFIGURATION_H_ - - -#include <unordered_map> -#include <vector> -#include <string> -#include <cstring> - - -namespace CommonAPI { - - -static const char COMMONAPI_CONFIG_SUFFIX[] = ".conf"; -static const char COMMONAPI_GLOBAL_CONFIG_ROOT[] = "/etc/CommonAPI/"; -static const char COMMONAPI_GLOBAL_CONFIG_FQN[] = "/etc/CommonAPI/CommonAPI.conf"; - -static const char COMMONAPI_STD_LIB_PATH[] = "/usr/lib:/usr/local/lib/"; -static const char COMMONAPI_ENVIRONMENT_BINDING_PATH[] = "COMMONAPI_BINDING_PATH"; - -static const char CATEGORY_ENDING = '}'; - -static const char CATEGORY_IDENTIFIER_BINDING[] = "{binding:"; - -static const char BINDING_PARAMETER_ALIAS[] = "alias"; -static const char BINDING_PARAMETER_LIBPATH[] = "libpath"; -static const char BINDING_PARAMETER_GENPATH[] = "genpath"; -static const char BINDING_PARAMETER_DEFAULT[] = "default"; - - -/** - * Represents the contents of all parsed CommonAPI Configuration files. - * - * For more information on how to configure CommonAPI, see attached documentation. - */ -class Configuration { - public: - /** - * Returns the instance of the Configuration. - * - * When first calling this method, all configuration files that are found are parsed and - * the values are stored within this class. - * - * @return The singleton instance of the CommonAPI Configuration. - */ - static const Configuration& getInstance(); - - Configuration(const Configuration&) = delete; - Configuration& operator=(const Configuration&) = delete; - Configuration(Configuration&&) = delete; - Configuration& operator=(Configuration&&) = delete; - - /** - * Returns the search paths on which binding specific libraries may be found. - * - * Default search paths are /usr/lib and /usr/local/lib, those two will always be returned. - * If additional search paths have been configured, those will also be returned. - * - * @return - */ - const std::vector<std::string>& getLibrarySearchPaths() const; - - /** - * Returns the actual middleware identifier for the given alias. - * - * If no such alias has been configured, the given alias itself will be returned. - * - * @return The middleware identifier or the given alias itself, if no mapping to a middleware identifier was found. - */ - const std::string& getMiddlewareNameForAlias(const std::string& alias) const; - - /** - * Returns the specified library path for the given middleware identifier. - * - * If a path to a specific library has been configured for the given middleware identifier, this path will be returned. - * If no such path has been configured, the empty string will be returned. - * - * @return The path to the middleware library, if any is known, the empty string "" otherwise. - */ - const std::string& getMiddlewareLibraryPath(const std::string& middlewareIdentifier) const; - - /** - * Returns the paths to other generic libraries configured for a specific binding. - * - * This function is meant to be called by middleware libraries. Will return all configured paths to - * generic libraries. You likely wil want to use the utility functions provided in <CommonAPI/utils.h> - * to do the loading. To arrange and time the loading is responsibility of the middleware only. - * - * @return A vector containing all generic libraries associated with the given middlewareIdentifier. - */ - const std::vector<std::string>& getGenericLibraryPaths(const std::string& middlewareIdentifier) const; - - /** - * Returns the configured default middleware identifier. - * - * If no default has been configured, the empty string "" will be returned. - * - * @return The configured default middleware identifier. - */ - const std::string& getDefaultMiddlewareIdentifier() const; - - private: - Configuration() = default; - - void readConfigFile(std::ifstream& addressConfigFile); - void retrieveCommonApiConfiguration(); - void readEnvironmentVariables(); -}; - - - -} // namespace CommonAPI - -#endif /* COMMONAPI_CONFIGURATION_H_ */ diff --git a/src/CommonAPI/ContainerUtils.cpp b/src/CommonAPI/ContainerUtils.cpp index 08fe2bc..887ac91 100644 --- a/src/CommonAPI/ContainerUtils.cpp +++ b/src/CommonAPI/ContainerUtils.cpp @@ -1,12 +1,10 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +// Copyright (C) 2014-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. -#include "ContainerUtils.h" -#include "types.h" +#include <CommonAPI/ContainerUtils.hpp> +#include <CommonAPI/Types.hpp> namespace CommonAPI { @@ -26,4 +24,4 @@ bool SharedPointerClientIdContentEqual::operator()(const std::shared_ptr<ClientI } } -} // namespace std +} // namespace std diff --git a/src/CommonAPI/ContainerUtils.h b/src/CommonAPI/ContainerUtils.h deleted file mode 100644 index a4423ab..0000000 --- a/src/CommonAPI/ContainerUtils.h +++ /dev/null @@ -1,33 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef FUNCTIONALHASH_H_ -#define FUNCTIONALHASH_H_ - -#include <functional> -#include <memory> - -namespace CommonAPI { -class ClientId; - -struct SharedPointerClientIdContentHash : public std::unary_function<std::shared_ptr<ClientId>, size_t> { - size_t operator()(const std::shared_ptr<ClientId>& t) const; -}; - -struct SharedPointerClientIdContentEqual : public std::binary_function<std::shared_ptr<ClientId>, std::shared_ptr<ClientId>, bool> { - bool operator()(const std::shared_ptr<ClientId>& a, const std::shared_ptr<ClientId>& b) const; -}; - - -} // namespace std - - -#endif /* FUNCTIONALHASH_H_ */ diff --git a/src/CommonAPI/Event.h b/src/CommonAPI/Event.h deleted file mode 100644 index 3d059b2..0000000 --- a/src/CommonAPI/Event.h +++ /dev/null @@ -1,193 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_EVENT_H_ -#define COMMONAPI_EVENT_H_ - -#include <functional> -#include <list> -#include <tuple> -#include <mutex> - -namespace CommonAPI { - -enum class SubscriptionStatus { - RETAIN, - CANCEL -}; - -/** - * \brief Class representing an event - * - * Class representing an event - */ -template<typename ... _Arguments> -class Event { -public: - typedef std::tuple<_Arguments...> ArgumentsTuple; - typedef std::function<void(const _Arguments&...)> Listener; - typedef std::function<SubscriptionStatus(const _Arguments&...)> CancellableListener; - typedef std::list<CancellableListener> ListenersList; - typedef typename ListenersList::iterator Subscription; - - class CancellableListenerWrapper; - - /** - * \brief Subscribe a listener to this event - * - * Subscribe a listener to this event. - * ATTENTION: You should not build new proxies or register services in callbacks - * from events. This can cause a deadlock or assert. Instead, you should set a - * trigger for your application to do this on the next iteration of your event loop - * if needed. The preferred solution is to build all proxies you need at the - * beginning and react to events appropriatly for each. - * - * @param listener A listener to be added - * @return A token identifying this subscription - */ - virtual Subscription subscribe(Listener listener); - - /** - * \brief Subscribe a cancellable listener to this event - * - * Subscribe a cancellable listener to this event - * ATTENTION: You should not build new proxies or register services in callbacks - * from events. This can cause a deadlock or assert. Instead, you should set a - * trigger for your application to do this on the next iteration of your event loop - * if needed. The preferred solution is to build all proxies you need at the - * beginning and react to events appropriatly for each. - * - * @param listener A cancellable listener to be added - * @return A token identifying this subscription - */ - Subscription subscribeCancellableListener(CancellableListener listener); - - /** - * \brief Remove a listener from this event - * - * Remove a listener from this event - * Note: Do not call this inside a listener notification callback it will deadlock! Use cancellable listeners instead. - * - * @param listenerSubscription A listener token to be removed - * @return true, if the removed subscription was the last one - */ - void unsubscribe(Subscription listenerSubscription); - - virtual ~Event() { - } - -protected: - // Returns false if all subscriptions were cancelled - // Does not send *Removed events! - SubscriptionStatus notifyListeners(const _Arguments&... eventArguments); - - // Events sent during subscribe() - virtual void onFirstListenerAdded(const CancellableListener& listener) { - } - virtual void onListenerAdded(const CancellableListener& listener) { - } - - // Events sent during unsubscribe() - virtual void onListenerRemoved(const CancellableListener& listener) { } - virtual void onLastListenerRemoved(const CancellableListener& listener) { } - - inline bool hasListeners() const; - -//private: - ListenersList listenersList_; - std::mutex listenerListMutex_; -}; - -template<typename ... _Arguments> -class Event<_Arguments...>::CancellableListenerWrapper { -public: - CancellableListenerWrapper(Listener&& listener) : - listener_(std::move(listener)) { - } - - SubscriptionStatus operator()(const _Arguments&... eventArguments) { - listener_(eventArguments...); - return SubscriptionStatus::RETAIN; - } - -private: - Listener listener_; -}; - -template<typename ... _Arguments> -typename Event<_Arguments...>::Subscription Event<_Arguments...>::subscribe(Listener listener) { - return subscribeCancellableListener(CancellableListenerWrapper(std::move(listener))); -} - -template<typename ... _Arguments> -typename Event<_Arguments...>::Subscription Event<_Arguments...>::subscribeCancellableListener(CancellableListener listener) { - listenerListMutex_.lock(); - const bool firstListenerAdded = listenersList_.empty(); - - listenersList_.emplace_front(std::move(listener)); - Subscription listenerSubscription = listenersList_.begin(); - listenerListMutex_.unlock(); - - if (firstListenerAdded) { - onFirstListenerAdded(*listenerSubscription); - } - - onListenerAdded(*listenerSubscription); - - return listenerSubscription; -} - -template<typename ... _Arguments> -void Event<_Arguments...>::unsubscribe(Subscription listenerSubscription) { - const CancellableListener cancellableListener = *listenerSubscription; - - listenerListMutex_.lock(); - listenersList_.erase(listenerSubscription); - const bool lastListenerRemoved = listenersList_.empty(); - listenerListMutex_.unlock(); - - onListenerRemoved(cancellableListener); - - if (lastListenerRemoved) { - onLastListenerRemoved(cancellableListener); - } -} - -template<typename ... _Arguments> -SubscriptionStatus Event<_Arguments...>::notifyListeners(const _Arguments&... eventArguments) { - listenerListMutex_.lock(); - for (auto iterator = listenersList_.begin(); iterator != listenersList_.end();) { - const CancellableListener& cancellableListener = *iterator; - const SubscriptionStatus listenerSubscriptionStatus = cancellableListener(eventArguments...); - - if (listenerSubscriptionStatus == SubscriptionStatus::CANCEL) { - auto listenerIterator = iterator; - iterator++; - listenersList_.erase(listenerIterator); - } else - iterator++; - } - - const bool lEmpty = listenersList_.empty(); - - listenerListMutex_.unlock(); - - return lEmpty ? SubscriptionStatus::CANCEL : SubscriptionStatus::RETAIN; -} - -template<typename ... _Arguments> -bool Event<_Arguments...>::hasListeners() const { - return !listenersList_.empty(); -} - -} // namespace CommonAPI - -#endif // COMMONAPI_EVENT_H_ diff --git a/src/CommonAPI/Factory.cpp b/src/CommonAPI/Factory.cpp deleted file mode 100644 index bc1d696..0000000 --- a/src/CommonAPI/Factory.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "Factory.h" - -namespace CommonAPI { - -std::shared_ptr<Runtime> Factory::getRuntime() { - return runtime_; -} - -} // namespace CommonAPI diff --git a/src/CommonAPI/Factory.h b/src/CommonAPI/Factory.h deleted file mode 100644 index 3760953..0000000 --- a/src/CommonAPI/Factory.h +++ /dev/null @@ -1,369 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_FACTORY_H_ -#define COMMONAPI_FACTORY_H_ - -#include <cassert> -#include <memory> -#include <sstream> -#include <string> -#include <unordered_map> -#include <vector> - -#include "MiddlewareInfo.h" -#include "Proxy.h" -#include "Stub.h" -#include "types.h" -#include "utils.h" -#include "AttributeExtension.h" - - -namespace CommonAPI { - - -class Factory; -class ServicePublisher; - - -template<template<typename ...> class _ProxyType, template<typename> class _AttributeExtension> -struct DefaultAttributeProxyFactoryHelper; - - -template<template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> -std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> createProxyWithDefaultAttributeExtension(Factory* specificFactory, const std::string& participantId, const std::string& domain); - - -/** - * \brief The main CommonAPI access class. A factory is responsible for creation and destruction of service objects. - * - * The main CommonAPI access class. A factory is responsible for creation and destruction of service objects. - * This includes proxies and stubs. It also provides service discovery methods. - */ -class Factory { - public: - typedef std::function<void(std::vector<std::string>&) > GetAvailableServiceInstancesCallback; - typedef std::function<void(bool)> IsServiceInstanceAliveCallback; - - - /** - * \brief Creates factory. Don't call manually. - * - * Creates factory. Don't call manually. - */ - Factory(const std::shared_ptr<Runtime> runtime, - const MiddlewareInfo* middlewareInfo): - runtime_(runtime), - middlewareInfo_(middlewareInfo) { - } - - /** - * \brief Creates factory. Don't call manually. - * - * Creates factory. Don't call manually. - */ - Factory(const std::shared_ptr<Runtime> runtime, - const MiddlewareInfo* middlewareInfo, - const std::string factoryName, - const bool nullOnInvalidName) : - runtime_(runtime), - middlewareInfo_(middlewareInfo) { - } - - virtual ~Factory() {} - - /** - * \brief Build a proxy for the specified address - * - * Build a proxy for the specified address. - * Template this method call for the desired proxy type and attribute extension. - * - * @param participantId The participant ID of the common API address (last part) - * @param serviceName The service name of the common API address (middle part) - * @param domain The domain of the common API address (first part) - * @return a shared pointer to the constructed proxy - */ - template<template<typename ...> class _ProxyClass, typename ... _AttributeExtensions> - std::shared_ptr< - _ProxyClass< -#ifdef WIN32 - CommonAPI::WINDummyAttributeExtension<WINDummyAttribute>, -#endif - _AttributeExtensions...> - > - buildProxy(const std::string& participantId, - const std::string& serviceName, - const std::string& domain) { - std::shared_ptr<Proxy> abstractMiddlewareProxy = createProxy(_ProxyClass<_AttributeExtensions...>::getInterfaceId(), participantId, serviceName, domain); - - if(abstractMiddlewareProxy) { - auto returnProxy = std::make_shared< - _ProxyClass< -#ifdef WIN32 - CommonAPI::WINDummyAttributeExtension<WINDummyAttribute>, -#endif - _AttributeExtensions...> - >(abstractMiddlewareProxy); - - return returnProxy; - } - else { - return NULL; - } - } - - /** - * \brief Build a proxy for the specified address - * - * Build a proxy for the specified address. - * Template this method call for the desired proxy type and attribute extensions. - * - * @param serviceAddress The common API address - * @return a shared pointer to the constructed proxy - */ - template<template<typename ...> class _ProxyClass, typename ... _AttributeExtensions > - std::shared_ptr< - _ProxyClass< -#ifdef WIN32 - CommonAPI::WINDummyAttributeExtension<WINDummyAttribute>, -#endif - _AttributeExtensions...> - > - buildProxy(const std::string& serviceAddress) { - std::string domain; - std::string serviceName; - std::string participantId; - if (!splitValidAddress(serviceAddress, domain, serviceName, participantId)) { - return false; - } - - return buildProxy<_ProxyClass, _AttributeExtensions...>(participantId, serviceName, domain); - } - - /** - * \brief Build a proxy for the specified address with one extension for all attributes - * - * Build a proxy for the specified address with one extension for all attributes - * Template this method call for the desired proxy type and attribute extensions. - * - * @param participantId The participant ID of the common API address (last part) - * @param serviceName The service name of the common API address (middle part) - * @param domain The domain of the common API address (first part) - * @return a shared pointer to the constructed proxy - */ - template <template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> - std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> - buildProxyWithDefaultAttributeExtension(const std::string& participantId, - const std::string& serviceName, - const std::string& domain); - - /** - * \brief Build a proxy for the specified address with one extension for all attributes - * - * Build a proxy for the specified address with one extension for all attributes - * Template this method call for the desired proxy type attribute extension. - * - * @param serviceAddress The common API address - * @return a shared pointer to the constructed proxy - */ - template <template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> - std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> - buildProxyWithDefaultAttributeExtension(const std::string& serviceAddress); - - /** - * \brief Get a pointer to the runtime of this factory. - * - * Get a pointer to the runtime of this factory. - * - * @return the Runtime - */ - std::shared_ptr<Runtime> getRuntime(); - - /** - * \brief Register a service stub under a specified address - * - * Register a service stub under a specified address. The service will be registered - * with the ServicePublisher that is provided by the runtime which you also retrieved - * this factory from. It is recommended to use the ServicePublisher for registering - * and unregistering purposes. - * - * @param stub The stub pointer - * @param participantId The participant ID of the common API address (last part) - * @param serviceName The service name of the common API address (middle part) - * @param domain The domain of the common API address (first part) - * @return Was the registration successful - * - * @deprecated Use CommonAPI::Runtime->getServicePublisher()->registerService() instead. - * Purpose for this change is to make service management (esp. deregistering) independent - * from factory instances. - */ - template<typename _Stub> - COMMONAPI_DEPRECATED bool registerService(std::shared_ptr<_Stub> stub, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain); - - /** - * \brief Register a service stub under a specified address - * - * Register a service stub under a specified address. The service will be registered - * with the ServicePublisher that is provided by the runtime which you also retrieved - * this factory from. It is recommended to use the ServicePublisher for registering - * and unregistering purposes. - * - * @param stub The stub pointer - * @param serviceAddress The common API address - * @return Was the registration successful - * - * @deprecated Use CommonAPI::Runtime->getServicePublisher()->registerService() instead. - * Purpose for this change is to make service management (esp. deregistering) independent - * from factory instances. - */ - template<typename _Stub> - COMMONAPI_DEPRECATED bool registerService(std::shared_ptr<_Stub> stub, const std::string& serviceAddress); - - /** - * \brief Unregister a service stub associated with a specified address - * - * Unregister a service stub associated with a specified address. - * - * @param participantId The participant ID of the common API address (last part) - * @param serviceName The service name of the common API address (middle part) - * @param domain The domain of the common API address (first part) - * @return Was the deregistration successful - * - * @deprecated Use CommonAPI::Runtime->getServicePublisher()->unregisterService() instead. - * Purpose for this change is to make service management (esp. deregistering) independent - * from factory instances. - */ - COMMONAPI_DEPRECATED virtual bool unregisterService(const std::string& participantId, const std::string& serviceName, const std::string& domain) = 0; - - /** - * \brief Unregister a service stub associated with a specified address - * - * Unregister a service stub associated with a specified address - * - * @param serviceAddress The common API address - * @return Was the deregistration successful - * - * @deprecated Use CommonAPI::Runtime->getServicePublisher()->unregisterService() instead. - * Purpose for this change is to make service management (esp. deregistering) independent - * from factory instances. - */ - COMMONAPI_DEPRECATED bool unregisterService(const std::string& serviceAddress); - - /** - * \brief Get all instances of a specific service name available. Synchronous call. - * - * Get all instances of a specific service name available. Synchronous call. - * - * @param serviceName The service name of the common API address (middle part) - * @param serviceDomainName The domain of the common API address (first part) - * @return A vector of strings containing the available complete common api addresses. - */ - virtual std::vector<std::string> getAvailableServiceInstances(const std::string& serviceName, const std::string& serviceDomainName = "local") = 0; - - /** - * \brief Is a particular complete common api address available. Synchronous call. - * - * Is a particular complete common api address available. Synchronous call. - * - * @param serviceAddress The common API address - * @return Is alive - */ - virtual bool isServiceInstanceAlive(const std::string& serviceAddress) = 0; - - /** - * \brief Is a particular complete common api address available. Synchronous call. - * - * Is a particular complete common api address available. Synchronous call. - * - * @param serviceInstanceID The participant ID of the common API address (last part) - * @param serviceName The service name of the common API address (middle part) - * @param serviceDomainName The domain of the common API address (first part) - * @return Is alive - */ - virtual bool isServiceInstanceAlive(const std::string& serviceInstanceID, const std::string& serviceName, const std::string& serviceDomainName = "local") = 0; - - /** - * \brief Get all instances of a specific service name available. Asynchronous call. - * - * Get all instances of a specific service name available. Asynchronous call. - * - * @param serviceName The service name of the common API address (middle part) - * @param serviceDomainName The domain of the common API address (first part) - */ - virtual void getAvailableServiceInstancesAsync(GetAvailableServiceInstancesCallback callback, const std::string& serviceName, const std::string& serviceDomainName = "local") = 0; - - /** - * \brief Tells whether a particular service instance is available. Asynchronous call. - * - * Tells whether a particular service instance is available. Asynchronous call. - * - * @param serviceAddress The common API address of the service - */ - virtual void isServiceInstanceAliveAsync(IsServiceInstanceAliveCallback callback, const std::string& serviceAddress) = 0; - - /** - * \brief Tells whether a particular service instance is available. Asynchronous call. - * - * Tells whether a particular service instance is available. Asynchronous call. - * - * @param serviceInstanceID The participant ID of the common API address (last part) of the service - * @param serviceName The service name of the common API address (middle part) of the service - * @param serviceDomainName The domain of the common API address (first part) of the service - */ - virtual void isServiceInstanceAliveAsync(IsServiceInstanceAliveCallback callback, const std::string& serviceInstanceID, const std::string& serviceName, const std::string& serviceDomainName = "local") = 0; - - protected: - virtual std::shared_ptr<Proxy> createProxy(const char* interfaceId, const std::string& participantId, const std::string& serviceName, const std::string& domain) = 0; - - /** - * @deprecated Use CommonAPI::ServicePublisher::registerService() instead. - */ - COMMONAPI_DEPRECATED virtual bool registerAdapter(std::shared_ptr<StubBase> stubBase, - const char* interfaceId, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain) { - return false; - } - std::shared_ptr<Runtime> runtime_; - private: - - const MiddlewareInfo* middlewareInfo_; - - inline bool splitValidAddress(const std::string& serviceAddress, std::string& domain, std::string& serviceName, std::string& participantId) { - std::istringstream addressStream(serviceAddress); - if(!std::getline(addressStream, domain, ':')) { - return false; - } - if(!std::getline(addressStream, serviceName, ':')) { - return false; - } - if(!std::getline(addressStream, participantId, ':')) { - return false; - } - if(std::getline(addressStream, participantId)) { - return false; - } - return true; - } - - friend class ServicePublisher; -}; - - -} // namespace CommonAPI - -#include "Factory.hpp" - -#endif // COMMONAPI_FACTORY_H_ diff --git a/src/CommonAPI/Factory.hpp b/src/CommonAPI/Factory.hpp deleted file mode 100644 index 0804996..0000000 --- a/src/CommonAPI/Factory.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef COMMONAPI_FACTORY_IMPL_H_ -#define COMMONAPI_FACTORY_IMPL_H_ - -#include "Runtime.h" -#include "ServicePublisher.h" - -namespace CommonAPI { - -template <template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> -std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> -Factory::buildProxyWithDefaultAttributeExtension(const std::string& participantId, - const std::string& serviceName, - const std::string& domain) { - - std::shared_ptr<Proxy> abstractMiddlewareProxy = createProxy(DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t::getInterfaceId(), participantId, serviceName, domain); - if (abstractMiddlewareProxy) { - return std::make_shared<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t>(abstractMiddlewareProxy); - } - return NULL; -} - -template <template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> -std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> -Factory::buildProxyWithDefaultAttributeExtension(const std::string& serviceAddress) { - - std::string domain; - std::string serviceName; - std::string participantId; - if(!splitValidAddress(serviceAddress, domain, serviceName, participantId)) { - return std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t>(); - } - - return buildProxyWithDefaultAttributeExtension<_ProxyClass, _AttributeExtension>(participantId, serviceName, domain); -} - -template<typename _Stub> -COMMONAPI_DEPRECATED bool Factory::registerService(std::shared_ptr<_Stub> stub, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain) { - - std::shared_ptr<StubBase> stubBase = std::dynamic_pointer_cast<StubBase>(stub); - return registerAdapter(stubBase, _Stub::StubAdapterType::getInterfaceId(), participantId, serviceName, domain); -} - -template<typename _Stub> -COMMONAPI_DEPRECATED bool Factory::registerService(std::shared_ptr<_Stub> stub, const std::string& serviceAddress) { - std::string domain; - std::string serviceName; - std::string participantId; - if(!splitValidAddress(serviceAddress, domain, serviceName, participantId)) { - return false; - } - - std::shared_ptr<StubBase> stubBase = std::dynamic_pointer_cast<StubBase>(stub); - return registerAdapter(stubBase, _Stub::StubAdapterType::getInterfaceId(), participantId, serviceName, domain); -} - -COMMONAPI_DEPRECATED inline bool Factory::unregisterService(const std::string& serviceAddress) { - return runtime_->getServicePublisher()->unregisterService(serviceAddress); -} - -} //namespace CommonAPI - -#endif // COMMONAPI_FACTORY_IMPL_H_ diff --git a/src/CommonAPI/IniFileReader.cpp b/src/CommonAPI/IniFileReader.cpp new file mode 100644 index 0000000..1637591 --- /dev/null +++ b/src/CommonAPI/IniFileReader.cpp @@ -0,0 +1,114 @@ +// Copyright (C) 2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <fstream> +#include <sstream> + +#include <CommonAPI/IniFileReader.hpp> +#include <CommonAPI/Logger.hpp> +#include <CommonAPI/Utils.hpp> + +namespace CommonAPI { + +const std::map<std::string, std::string> & +IniFileReader::Section::getMappings() const { + return mappings_; +} + +std::string +IniFileReader::Section::getValue(const std::string &_key) const { + auto it = mappings_.find(_key); + if (it != mappings_.end()) { + return it->second; + } + return (""); +} + +bool +IniFileReader::load(const std::string &_path) { + std::ifstream configStream(_path); + if (configStream.is_open()) { + COMMONAPI_INFO("Loading ini file from ", _path); + + int lineCounter(0); + std::string currentSectionName; + std::shared_ptr<Section> currentSection; + + while (!configStream.eof()) { + std::string line; + std::getline(configStream, line); + lineCounter++; + + trim(line); + + std::size_t start = line.find('['); + if (start == 0) { + std::size_t end = line.find(']'); + if (end != line.npos) { + currentSectionName = line.substr(++start, --end); + if (sections_.end() == sections_.find(currentSectionName)) { + currentSection = std::make_shared<Section>(); + if (currentSection) { + sections_[currentSectionName] = currentSection; + } + } else { + COMMONAPI_ERROR("Double definition of section \'", + currentSectionName, + "\' ignoring definition (line ", + lineCounter, + ")"); + currentSection = nullptr; + } + } else { + COMMONAPI_ERROR("Missing \']\' in section definition (line ", + lineCounter, ")"); + } + } else if (currentSection) { + std::size_t pos = line.find('='); + if (pos != line.npos) { + std::string key = line.substr(0, pos); + trim(key); + if (currentSection->mappings_.end() + != currentSection->mappings_.find(key)) { + COMMONAPI_ERROR("Double definition for key \'", + key, + "'\' in section \'", + currentSectionName, + "\' (line ", + lineCounter, + ")"); + } else { + std::string value = line.substr(pos+1); + trim(value); + currentSection->mappings_[key] = value; + } + } else if (line.size() > 0) { + COMMONAPI_ERROR("Missing \'=\' in key=value definition (line ", + lineCounter, ")"); + } + } + } + } + return true; +} + +const std::map<std::string, std::shared_ptr<IniFileReader::Section>> & +IniFileReader::getSections() const { + return sections_; +} + +std::shared_ptr<IniFileReader::Section> +IniFileReader::getSection(const std::string &_name) const { + std::shared_ptr<IniFileReader::Section> section; + + auto sectionIterator = sections_.find(_name); + if (sectionIterator != sections_.end()) { + section = sectionIterator->second; + } + + return section; +} + +} // namespace CommonAPI diff --git a/src/CommonAPI/InputStream.cpp b/src/CommonAPI/InputStream.cpp deleted file mode 100644 index 42dbec8..0000000 --- a/src/CommonAPI/InputStream.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "InputStream.h" - -namespace CommonAPI { - -InputStream& operator>>(InputStream& inputStream, bool& boolValue) { - return inputStream.readValue(boolValue); -} - -InputStream& operator>>(InputStream& inputStream, int8_t& int8Value) { - return inputStream.readValue(int8Value); -} - -InputStream& operator>>(InputStream& inputStream, int16_t& int16Value) { - return inputStream.readValue(int16Value); -} - -InputStream& operator>>(InputStream& inputStream, int32_t& int32Value) { - return inputStream.readValue(int32Value); -} - -InputStream& operator>>(InputStream& inputStream, int64_t& int64Value) { - return inputStream.readValue(int64Value); -} - -InputStream& operator>>(InputStream& inputStream, uint8_t& uint8Value) { - return inputStream.readValue(uint8Value); -} - -InputStream& operator>>(InputStream& inputStream, uint16_t& uint16Value) { - return inputStream.readValue(uint16Value); -} - -InputStream& operator>>(InputStream& inputStream, uint32_t& uint32Value) { - return inputStream.readValue(uint32Value); -} - -InputStream& operator>>(InputStream& inputStream, uint64_t& uint64Value) { - return inputStream.readValue(uint64Value); -} - -InputStream& operator>>(InputStream& inputStream, float& floatValue) { - return inputStream.readValue(floatValue); -} - -InputStream& operator>>(InputStream& inputStream, double& doubleValue) { - return inputStream.readValue(doubleValue); -} - -InputStream& operator>>(InputStream& inputStream, std::string& stringValue) { - return inputStream.readValue(stringValue); -} - -InputStream& operator>>(InputStream& inputStream, Version& versionValue) { - return inputStream.readVersionValue(versionValue); -} - -InputStream& operator>>(InputStream& inputStream, SerializableStruct& serializableStruct) { - inputStream.beginReadSerializableStruct(serializableStruct); - serializableStruct.readFromInputStream(inputStream); - inputStream.endReadSerializableStruct(serializableStruct); - - return inputStream; -} - -InputStream& operator>>(InputStream& inputStream, SerializableVariant& serializableVariant) { - inputStream.readSerializableVariant(serializableVariant); - return inputStream; -} - -} diff --git a/src/CommonAPI/InputStream.h b/src/CommonAPI/InputStream.h deleted file mode 100644 index 786a991..0000000 --- a/src/CommonAPI/InputStream.h +++ /dev/null @@ -1,341 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_INPUT_STREAM_H_ -#define COMMONAPI_INPUT_STREAM_H_ - -#include "ByteBuffer.h" -#include "SerializableStruct.h" -#include "SerializableVariant.h" -#include "types.h" - -#include <cstdint> -#include <functional> -#include <memory> -#include <string> -#include <unordered_map> -#include <vector> -#include <type_traits> - -namespace CommonAPI { - -class InputStream { -public: - virtual ~InputStream() {} - virtual bool hasError() const = 0; - - virtual InputStream& readValue(bool& boolValue) = 0; - - virtual InputStream& readValue(int8_t& int8Value) = 0; - virtual InputStream& readValue(int16_t& int16Value) = 0; - virtual InputStream& readValue(int32_t& int32Value) = 0; - virtual InputStream& readValue(int64_t& int64Value) = 0; - - virtual InputStream& readValue(uint8_t& uint8Value) = 0; - virtual InputStream& readValue(uint16_t& uint16Value) = 0; - virtual InputStream& readValue(uint32_t& uint32Value) = 0; - virtual InputStream& readValue(uint64_t& uint64Value) = 0; - - virtual InputStream& readValue(float& floatValue) = 0; - virtual InputStream& readValue(double& doubleValue) = 0; - - virtual InputStream& readValue(std::string& stringValue) = 0; - - virtual InputStream& readValue(ByteBuffer& byteBufferValue) = 0; - - virtual InputStream& readEnumValue(int8_t& int8BackingTypeValue) = 0; - virtual InputStream& readEnumValue(int16_t& int16BackingTypeValue) = 0; - virtual InputStream& readEnumValue(int32_t& int32BackingTypeValue) = 0; - virtual InputStream& readEnumValue(int64_t& int64BackingTypeValue) = 0; - virtual InputStream& readEnumValue(uint8_t& uint8BackingTypeValue) = 0; - virtual InputStream& readEnumValue(uint16_t& uint16BackingTypeValue) = 0; - virtual InputStream& readEnumValue(uint32_t& uint32BackingTypeValue) = 0; - virtual InputStream& readEnumValue(uint64_t& uint64BackingTypeValue) = 0; - - template<typename _EnumBackingType, typename _EnumType> - InputStream& readEnumValue(_EnumType& enumValue); - - virtual InputStream& readVersionValue(Version& versionValue) = 0; - - virtual void beginReadSerializableStruct(const SerializableStruct& serializableStruct) = 0; - virtual void endReadSerializableStruct(const SerializableStruct& serializableStruct) = 0; - - virtual void beginReadSerializablePolymorphicStruct(uint32_t& serialId) = 0; - virtual void endReadSerializablePolymorphicStruct(const uint32_t& serialId) = 0; - - virtual void readSerializableVariant(SerializableVariant& serializableVariant) = 0; - - virtual char* readRawData(const size_t numBytesToRead) = 0; - - virtual void beginReadBoolVector() = 0; - virtual void beginReadInt8Vector() = 0; - virtual void beginReadInt16Vector() = 0; - virtual void beginReadInt32Vector() = 0; - virtual void beginReadInt64Vector() = 0; - virtual void beginReadUInt8Vector() = 0; - virtual void beginReadUInt16Vector() = 0; - virtual void beginReadUInt32Vector() = 0; - virtual void beginReadUInt64Vector() = 0; - virtual void beginReadFloatVector() = 0; - virtual void beginReadDoubleVector() = 0; - virtual void beginReadStringVector() = 0; - virtual void beginReadByteBufferVector() = 0; - virtual void beginReadVersionVector() = 0; - - virtual void beginReadInt8EnumVector() = 0; - virtual void beginReadInt16EnumVector() = 0; - virtual void beginReadInt32EnumVector() = 0; - virtual void beginReadInt64EnumVector() = 0; - virtual void beginReadUInt8EnumVector() = 0; - virtual void beginReadUInt16EnumVector() = 0; - virtual void beginReadUInt32EnumVector() = 0; - virtual void beginReadUInt64EnumVector() = 0; - - virtual void beginReadVectorOfSerializableStructs() = 0; - virtual void beginReadVectorOfSerializableVariants() = 0; - virtual void beginReadVectorOfVectors() = 0; - virtual void beginReadVectorOfMaps() = 0; - - virtual void beginReadVectorOfSerializablePolymorphicStructs() = 0; - - virtual bool hasMoreVectorElements() = 0; - virtual void endReadVector() = 0; - - virtual void beginReadMap() = 0; - virtual bool hasMoreMapElements() = 0; - virtual void endReadMap() = 0; - virtual void beginReadMapElement() = 0; - virtual void endReadMapElement() = 0; -}; - -template<typename _EnumBackingType, typename _EnumType> -InputStream& InputStream::readEnumValue(_EnumType& enumValue) { - _EnumBackingType enumBackingValue; - - readEnumValue(enumBackingValue); - enumValue = static_cast<_EnumType>(enumBackingValue); - - return *this; -} - -InputStream& operator>>(InputStream& inputStream, bool& boolValue); - -InputStream& operator>>(InputStream& inputStream, int8_t& int8Value); - -InputStream& operator>>(InputStream& inputStream, int16_t& int16Value); - -InputStream& operator>>(InputStream& inputStream, int32_t& int32Value); - -InputStream& operator>>(InputStream& inputStream, int64_t& int64Value); - -InputStream& operator>>(InputStream& inputStream, uint8_t& uint8Value); - -InputStream& operator>>(InputStream& inputStream, uint16_t& uint16Value); - -InputStream& operator>>(InputStream& inputStream, uint32_t& uint32Value); - -InputStream& operator>>(InputStream& inputStream, uint64_t& uint64Value); - -InputStream& operator>>(InputStream& inputStream, float& floatValue); - -InputStream& operator>>(InputStream& inputStream, double& doubleValue); - -InputStream& operator>>(InputStream& inputStream, std::string& stringValue); - -InputStream& operator>>(InputStream& inputStream, Version& versionValue); - -InputStream& operator>>(InputStream& inputStream, SerializableStruct& serializableStruct); - -template<typename _SerializablePolymorphicStructType> -typename std::enable_if<std::is_base_of<SerializablePolymorphicStruct, _SerializablePolymorphicStructType>::value, - InputStream>::type& -operator>>(InputStream& inputStream, - std::shared_ptr<_SerializablePolymorphicStructType>& serializablePolymorphicStruct) { - uint32_t serialId; - - inputStream.beginReadSerializablePolymorphicStruct(serialId); - if (!inputStream.hasError()) { - _SerializablePolymorphicStructType* instancePtr = _SerializablePolymorphicStructType::createInstance(serialId); - serializablePolymorphicStruct.reset(instancePtr); - if (instancePtr != NULL) { - instancePtr->readFromInputStream(inputStream); - } - - inputStream.endReadSerializablePolymorphicStruct(serialId); - } - - return inputStream; -} - -InputStream& operator>>(InputStream& inputStream, SerializableVariant& serializableVariant); - -template<typename _VectorElementType> -class InputStreamGenericTypeVectorHelper { -public: - static void beginReadVector(InputStream& inputStream, const std::vector<_VectorElementType>& vectorValue) { - doBeginReadVector(inputStream, vectorValue); - } - -private: - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<bool>& vectorValue) { - inputStream.beginReadBoolVector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<int8_t>& vectorValue) { - inputStream.beginReadInt8Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<int16_t>& vectorValue) { - inputStream.beginReadInt16Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<int32_t>& vectorValue) { - inputStream.beginReadInt32Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<int64_t>& vectorValue) { - inputStream.beginReadInt64Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<uint8_t>& vectorValue) { - inputStream.beginReadUInt8Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<uint16_t>& vectorValue) { - inputStream.beginReadUInt16Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<uint32_t>& vectorValue) { - inputStream.beginReadUInt32Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<uint64_t>& vectorValue) { - inputStream.beginReadUInt64Vector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<float>& vectorValue) { - inputStream.beginReadFloatVector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<double>& vectorValue) { - inputStream.beginReadDoubleVector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<std::string>& vectorValue) { - inputStream.beginReadStringVector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<ByteBuffer>& vectorValue) { - inputStream.beginReadByteBufferVector(); - } - static inline void doBeginReadVector(InputStream& inputStream, const std::vector<Version>& vectorValue) { - inputStream.beginReadVersionVector(); - } - - template<typename _PointerType, - typename = typename std::enable_if< - std::is_base_of<SerializablePolymorphicStruct, _PointerType>::value>::type> - static inline void doBeginReadVector(InputStream& inputStream, - const std::vector<std::shared_ptr<_PointerType>>& vectorValue) { - inputStream.beginReadVectorOfSerializablePolymorphicStructs(); - } - - template<typename _InnerVectorElementType> - static inline void doBeginReadVector(InputStream& inputStream, - const std::vector<std::vector<_InnerVectorElementType>>& vectorValue) { - inputStream.beginReadVectorOfVectors(); - } - - template<typename _InnerKeyType, typename _InnerValueType, typename _InnerHashType> - static inline void doBeginReadVector(InputStream& inputStream, - const std::vector<std::unordered_map<_InnerKeyType, _InnerValueType, _InnerHashType>>& vectorValue) { - inputStream.beginReadVectorOfMaps(); - } - - template<typename _InnerKeyType, typename _InnerValueType> - static inline void doBeginReadVector(InputStream& inputStream, - const std::vector<std::unordered_map<_InnerKeyType, _InnerValueType>>& vectorValue) { - inputStream.beginReadVectorOfMaps(); - } -}; - -template<typename _VectorElementType, bool _IsSerializableStruct = false> -struct InputStreamSerializableStructVectorHelper: InputStreamGenericTypeVectorHelper<_VectorElementType> { -}; - -template<typename _VectorElementType> -struct InputStreamSerializableStructVectorHelper<_VectorElementType, true> { - static void beginReadVector(InputStream& inputStream, const std::vector<_VectorElementType>& vectorValue) { - inputStream.beginReadVectorOfSerializableStructs(); - } -}; - -template<typename _VectorElementType, bool _IsSerializableVariant = false> -struct InputStreamSerializableVariantVectorHelper: InputStreamSerializableStructVectorHelper<_VectorElementType, - std::is_base_of<SerializableStruct, _VectorElementType>::value> { -}; - -template<typename _VectorElementType> -struct InputStreamSerializableVariantVectorHelper<_VectorElementType, true> { - static void beginReadVector(InputStream& inputStream, const std::vector<_VectorElementType>& vectorValue) { - inputStream.beginReadVectorOfSerializableVariants(); - } -}; - -template<typename _VectorElementType> -struct InputStreamVectorHelper: InputStreamSerializableVariantVectorHelper<_VectorElementType, - std::is_base_of<SerializableVariant, _VectorElementType>::value> { -}; - -/** - * Handles all reading of vectors from a given #InputStream. The given vector may contain any types for which a - * (specialized) operator>>() is provided. For basic types, such an operator already is provided as a templated operator. - * The vector does not need to be initialized in any way. - * - * @tparam _ElementType The type of the values that are contained in the vector that is to be read from the given stream. - * @param val The vector in which the retrieved values are to be stored - * @param inputStream The stream which the vector is to be read from - * @return The given inputStream to allow for successive reading - */ -template<typename _VectorElementType> -InputStream& operator>>(InputStream& inputStream, std::vector<_VectorElementType>& vectorValue) { - InputStreamVectorHelper<_VectorElementType>::beginReadVector(inputStream, vectorValue); - - while (inputStream.hasMoreVectorElements()) { - _VectorElementType element; - - inputStream >> element; - - if (inputStream.hasError()) - break; - - vectorValue.push_back(std::move(element)); - } - - inputStream.endReadVector(); - return inputStream; -} - -template<typename _KeyType, typename _ValueType, typename _HasherType> -InputStream& operator>>(InputStream& inputStream, std::unordered_map<_KeyType, _ValueType, _HasherType>& mapValue) { - typedef typename std::unordered_map<_KeyType, _ValueType, _HasherType>::value_type MapValueType; - - inputStream.beginReadMap(); - - while (inputStream.hasMoreMapElements()) { - _KeyType elementKey; - _ValueType elementValue; - - inputStream.beginReadMapElement(); - inputStream >> elementKey >> elementValue; - inputStream.endReadMapElement(); - - if (inputStream.hasError()) - break; - - mapValue.insert(MapValueType(std::move(elementKey), std::move(elementValue))); - } - - inputStream.endReadMap(); - return inputStream; -} - -} // namespace CommonAPI - -#endif // COMMONAPI_INPUT_STREAM_H_ diff --git a/src/CommonAPI/Logger.cpp b/src/CommonAPI/Logger.cpp new file mode 100644 index 0000000..4514bd7 --- /dev/null +++ b/src/CommonAPI/Logger.cpp @@ -0,0 +1,152 @@ +// Copyright (C) 2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <iostream> + +#include <CommonAPI/Logger.hpp> +#include <CommonAPI/Runtime.hpp> + +namespace CommonAPI { + +#if defined(USE_CONSOLE) || defined(USE_FILE) +std::mutex Logger::mutex_; +#endif + +#ifdef USE_CONSOLE +bool Logger::useConsole_(true); +#endif + +#ifdef USE_FILE +std::shared_ptr<std::ofstream> Logger::file_; +#endif + +#ifdef USE_DLT +bool Logger::useDlt_(false); +#endif + +#if defined(USE_CONSOLE) || defined(USE_FILE) || defined(USE_DLT) +Logger::Level Logger::maximumLogLevel_(Logger::Level::LL_INFO); +#endif + +Logger::Logger() { +#ifdef USE_DLT + DLT_REGISTER_APP("CAPI", "CAPI"); + std::string context = Runtime::getProperty("LogContext"); + if (context == "") context = "CAPI"; + DLT_REGISTER_CONTEXT(dlt_, context.c_str(), "CAPI"); +#endif +} + +void +Logger::init(bool _useConsole, const std::string &_fileName, bool _useDlt, const std::string &_level) { +#ifdef USE_CONSOLE + useConsole_ = _useConsole; +#endif +#ifdef USE_FILE + if (_fileName != "") { + file_ = std::make_shared<std::ofstream>(); + if (file_) + file_->open(_fileName.c_str(), std::ofstream::out | std::ofstream::app); + } +#endif +#ifdef USE_DLT + useDlt_ = _useDlt; +#endif +#if defined(USE_CONSOLE) || defined(USE_FILE) || defined(USE_DLT) + maximumLogLevel_ = stringAsLevel(_level); +#endif +} + +void +Logger::doLog(Level _level, const std::string &_message) { +#ifdef USE_CONSOLE + if (useConsole_) { + std::lock_guard<std::mutex> consoleGuard(mutex_); + std::cout << "[CAPI][" << levelAsString(_level) << "] " << _message << std::endl; + } +#endif +#ifdef USE_FILE + if (file_ && file_->is_open()) { + std::lock_guard<std::mutex> consoleGuard(mutex_); + (*(file_.get())) << "[CAPI][" << levelAsString(_level) << "] " << _message << std::endl; + } +#endif +#ifdef USE_DLT + if (useDlt_) { + DLT_LOG_STRING(dlt_, levelAsDlt(_level), _message.c_str()); + } +#endif +} + +#if defined(USE_CONSOLE) || defined(USE_FILE) || defined(USE_DLT) +Logger::Level +Logger::stringAsLevel(const std::string &_level) { + if (_level == "fatal") + return Level::LL_FATAL; + + if (_level == "error") + return Level::LL_ERROR; + + if (_level == "warning") + return Level::LL_WARNING; + + if (_level == "info") + return Level::LL_INFO; + + if (_level == "debug") + return Level::LL_DEBUG; + + if (_level == "verbose") + return Level::LL_VERBOSE; + + return Level::LL_INFO; +} +#endif + +#if defined(USE_CONSOLE) || defined(USE_FILE) +std::string +Logger::levelAsString(Logger::Level _level) { + switch (_level) { + case Level::LL_FATAL: + return "FATAL"; + case Level::LL_ERROR: + return "ERROR"; + case Level::LL_WARNING: + return "WARNING"; + case Level::LL_INFO: + return "INFO"; + case Level::LL_DEBUG: + return "DEBUG"; + case Level::LL_VERBOSE: + return "VERBOSE"; + default: + return ""; + } +} +#endif + +#ifdef USE_DLT +DltLogLevelType +Logger::levelAsDlt(Logger::Level _level) { + switch (_level) { + case Level::LL_FATAL: + return DLT_LOG_FATAL; + case Level::LL_ERROR: + return DLT_LOG_ERROR; + case Level::LL_WARNING: + return DLT_LOG_WARN; + case Level::LL_INFO: + return DLT_LOG_INFO; + case Level::LL_DEBUG: + return DLT_LOG_DEBUG; + case Level::LL_VERBOSE: + return DLT_LOG_VERBOSE; + default: + return DLT_LOG_DEFAULT; + } +} +#endif + +} //namespace CommonAPI diff --git a/src/CommonAPI/MainLoopContext.cpp b/src/CommonAPI/MainLoopContext.cpp index b13cd89..c8bcb41 100644 --- a/src/CommonAPI/MainLoopContext.cpp +++ b/src/CommonAPI/MainLoopContext.cpp @@ -1,12 +1,9 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "MainLoopContext.h" +// Copyright (C) 2013-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. +#include <CommonAPI/MainLoopContext.hpp> namespace CommonAPI { @@ -14,6 +11,10 @@ int64_t getCurrentTimeInMs() { return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); } +const std::string &MainLoopContext::getName() const { + return name_; +} + DispatchSourceListenerSubscription MainLoopContext::subscribeForDispatchSources(DispatchSourceAddedCallback dispatchAddedCallback, DispatchSourceRemovedCallback dispatchRemovedCallback) { dispatchSourceListeners_.emplace_front(dispatchAddedCallback, dispatchRemovedCallback); return dispatchSourceListeners_.begin(); @@ -96,4 +97,4 @@ bool MainLoopContext::isInitialized() { return dispatchSourceListeners_.size() > 0 || watchListeners_.size() > 0; } -} //Namespace CommonAPI +} // namespace CommonAPI diff --git a/src/CommonAPI/MainLoopContext.h b/src/CommonAPI/MainLoopContext.h deleted file mode 100644 index 3c4e7c1..0000000 --- a/src/CommonAPI/MainLoopContext.h +++ /dev/null @@ -1,294 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_MAIN_LOOP_CONTEXT_H_ -#define COMMONAPI_MAIN_LOOP_CONTEXT_H_ - - -#include <stdint.h> - -#ifdef WIN32 -#include <WinSock2.h> -#else -#include <poll.h> -#endif - -#ifdef WIN32 -#undef max -#endif - -#include <limits> -#include <vector> -#include <chrono> -#include <list> -#include <functional> - -namespace CommonAPI { - -enum class DispatchPriority { - VERY_HIGH, - HIGH, - DEFAULT, - LOW, - VERY_LOW -}; - - -int64_t getCurrentTimeInMs(); - - -/** - * \brief Describes a basic element that periodically needs to be dispatched. - * - * A DispatchSource is not directly related to a file descriptor, but - * may be dependent on a watch that manages a file descriptor. If this - * is the case, the corresponding Watch will provide information about - * which DispatchSources are dependent. - */ -struct DispatchSource { - virtual ~DispatchSource() {} - - /** - * Indicates whether this source is ready to be dispatched. - * "Prepare" will be called before polling the file descriptors. - * - * @return 'true' if the source is ready to be dispatched. - */ - virtual bool prepare(int64_t& timeout) = 0; - - /** - * Indicates whether this source is ready to be dispatched. - * "Check" will be called after polling the file descriptors. - * - * @return 'true' if the source is ready to be dispatched. - */ - virtual bool check() = 0; - - /** - * The return value indicates whether this dispatch source currently has - * more data to dispatch. The mainloop may chose to ignore the return value. - * - * @return 'true' if there currently is more to dispatch, 'false' if not. - */ - virtual bool dispatch() = 0; -}; - - -/** - * \brief Describes an element that manages a file descriptor. - * - * The watch is ready to be dispatched whenever it's managed file descriptor - * has events in it's revents-field. - * - * It is possible that there are DispatchSources of which the dispatch readiness - * directly depends on the dispatching of the watch. If this is the case, such - * DispatchSources can be retrieved from this Watch. - */ -struct Watch { - virtual ~Watch() {} - - /** - * \brief Dispatches the watch. - * - * Should only be called once the associated file descriptor has events ready. - * - * @param eventFlags The events that shall be retrieved from the file descriptor. - */ - virtual void dispatch(unsigned int eventFlags) = 0; - - /** - * \brief Returns the file descriptor that is managed by this watch. - * - * @return The associated file descriptor. - */ - virtual const pollfd& getAssociatedFileDescriptor() = 0; - - /** - * \brief Returns a vector of all dispatch sources that depend on the watched file descriptor. - * - * The returned vector will not be empty if and only if there are any sources - * that depend on availability of data of the watched file descriptor. Whenever this - * Watch is dispatched, those sources likely also need to be dispatched. - */ - virtual const std::vector<DispatchSource*>& getDependentDispatchSources() = 0; -}; - -const int64_t TIMEOUT_INFINITE = std::numeric_limits<int64_t>::max(); -const int64_t TIMEOUT_NONE = 0; - - -/** - * \brief Describes a basic timeout. - * - * Timeouts will be taken into consideration when waiting in a call to poll - * for a file descriptor to become ready. When the lowest known timeout expires, - * the call to poll will return, regardless of whether a file descriptor was ready - * or not. - */ -struct Timeout { - virtual ~Timeout() {} - - /** - * Needs to be called when this timeout is expired. - * - * @return 'true' if the timeout shall be rescheduled, 'false' if it shall be removed. - */ - virtual bool dispatch() = 0; - - /** - * \brief The timeout interval in milliseconds. - * - * Returns TIMEOUT_INFINITE for "dispatch never", TIMEOUT_NONE for "dispatch immediately", - * or any positive value as an interval of time in milliseconds that needs to pass before - * this timeout is to be dispatched. - */ - virtual int64_t getTimeoutInterval() const = 0; - - /** - * \brief Returns the point in time at which this timeout needs to be dispatched next. - * - * After a initialization and after each dispatch, this timeout will re-calculate it's next - * ready time. This value may be ignored if a different mechanism for monitoring timeout intervals - * is used. - */ - virtual int64_t getReadyTime() const = 0; -}; - - -typedef std::function<void(DispatchSource*, const DispatchPriority)> DispatchSourceAddedCallback; -typedef std::function<void(DispatchSource*)> DispatchSourceRemovedCallback; -typedef std::function<void(Watch*, const DispatchPriority)> WatchAddedCallback; -typedef std::function<void(Watch*)> WatchRemovedCallback; -typedef std::function<void(Timeout*, const DispatchPriority)> TimeoutSourceAddedCallback; -typedef std::function<void(Timeout*)> TimeoutSourceRemovedCallback; -typedef std::function<void()> WakeupCallback; - -typedef std::list<std::pair<DispatchSourceAddedCallback, DispatchSourceRemovedCallback>> DispatchSourceListenerList; -typedef std::list<std::pair<WatchAddedCallback, WatchRemovedCallback>> WatchListenerList; -typedef std::list<std::pair<TimeoutSourceAddedCallback, TimeoutSourceRemovedCallback>> TimeoutSourceListenerList; -typedef std::list<WakeupCallback> WakeupListenerList; - -typedef DispatchSourceListenerList::iterator DispatchSourceListenerSubscription; -typedef WatchListenerList::iterator WatchListenerSubscription; -typedef TimeoutSourceListenerList::iterator TimeoutSourceListenerSubscription; -typedef WakeupListenerList::iterator WakeupListenerSubscription; - - -/** - * \brief Provides hooks for your Main Loop implementation. - * - * By registering callbacks with this class, you will be notified about all DispatchSources, - * Watches, Timeouts and Wakeup-Events that need to be handled by your Main Loop implementation. - * - */ -class MainLoopContext { - public: - MainLoopContext() {} - MainLoopContext(const MainLoopContext&) = delete; - MainLoopContext& operator=(const MainLoopContext&) = delete; - MainLoopContext(MainLoopContext&&) = delete; - MainLoopContext& operator=(MainLoopContext&&) = delete; - - /** - * \brief Registers for all DispatchSources that are added or removed. - */ - DispatchSourceListenerSubscription subscribeForDispatchSources(DispatchSourceAddedCallback dispatchAddedCallback, DispatchSourceRemovedCallback dispatchRemovedCallback); - - /** - * \brief Registers for all Watches that are added or removed. - */ - WatchListenerSubscription subscribeForWatches(WatchAddedCallback watchAddedCallback, WatchRemovedCallback watchRemovedCallback); - - /** - * \brief Registers for all Timeouts that are added or removed. - */ - TimeoutSourceListenerSubscription subscribeForTimeouts(TimeoutSourceAddedCallback timeoutAddedCallback, TimeoutSourceRemovedCallback timeoutRemovedCallback); - - /** - * \brief Registers for all Wakeup-Events that need to interrupt a call to "poll". - */ - WakeupListenerSubscription subscribeForWakeupEvents(WakeupCallback wakeupCallback); - - /** - * \brief Unsubscribes your listeners for DispatchSources. - */ - void unsubscribeForDispatchSources(DispatchSourceListenerSubscription subscription); - - /** - * \brief Unsubscribes your listeners for Watches. - */ - void unsubscribeForWatches(WatchListenerSubscription subscription); - - /** - * \brief Unsubscribes your listeners for Timeouts. - */ - void unsubscribeForTimeouts(TimeoutSourceListenerSubscription subscription); - - /** - * \brief Unsubscribes your listeners for Wakeup-Events. - */ - void unsubscribeForWakeupEvents(WakeupListenerSubscription subscription); - - /** - * \brief Notifies all listeners about a new DispatchSource. - */ - void registerDispatchSource(DispatchSource* dispatchSource, const DispatchPriority dispatchPriority = DispatchPriority::DEFAULT); - - /** - * \brief Notifies all listeners about the removal of a DispatchSource. - */ - void deregisterDispatchSource(DispatchSource* dispatchSource); - - /** - * \brief Notifies all listeners about a new Watch. - */ - void registerWatch(Watch* watch, const DispatchPriority dispatchPriority = DispatchPriority::DEFAULT); - - /** - * \brief Notifies all listeners about the removal of a Watch. - */ - void deregisterWatch(Watch* watch); - - /** - * \brief Notifies all listeners about a new Timeout. - */ - void registerTimeoutSource(Timeout* timeoutEvent, const DispatchPriority dispatchPriority = DispatchPriority::DEFAULT); - - /** - * \brief Notifies all listeners about the removal of a Timeout. - */ - void deregisterTimeoutSource(Timeout* timeoutEvent); - - /** - * \brief Notifies all listeners about a wakeup event that just happened. - */ - void wakeup(); - - /** - * \brief Will return true if at least one subscribe for DispatchSources or Watches has been called. - * - * This function will be used to prevent creation of a factory if a mainloop context is given, but - * no listeners have been registered. This is done in order to ensure correct use of the mainloop context. - */ - bool isInitialized(); - - private: - DispatchSourceListenerList dispatchSourceListeners_; - WatchListenerList watchListeners_; - TimeoutSourceListenerList timeoutSourceListeners_; - WakeupListenerList wakeupListeners_; -}; - - -} // namespace CommonAPI - - -#endif /* MAIN_LOOP_CONTEXT_H_ */ diff --git a/src/CommonAPI/MiddlewareInfo.h b/src/CommonAPI/MiddlewareInfo.h deleted file mode 100644 index 7a138b3..0000000 --- a/src/CommonAPI/MiddlewareInfo.h +++ /dev/null @@ -1,47 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef MIDDLEWAREINFO_H_ -#define MIDDLEWAREINFO_H_ - - -#include <memory> -#include <cstring> -#include "types.h" - - -namespace CommonAPI { - - -class Runtime; - - -typedef std::shared_ptr<Runtime> (*MiddlewareRuntimeLoadFunction) (); - - -struct MiddlewareInfo { - const char* middlewareName_; - MiddlewareRuntimeLoadFunction getInstance_; - Version version_; - - MiddlewareInfo(const char* middlewareName, - MiddlewareRuntimeLoadFunction middlewareRuntimeLoadFunction, - Version version): - middlewareName_(middlewareName), - getInstance_(middlewareRuntimeLoadFunction), - version_(version) {} -}; - - -} // namespace CommonAPI - - -#endif /* MIDDLEWAREINFO_H_ */ diff --git a/src/CommonAPI/OutputStream.h b/src/CommonAPI/OutputStream.h deleted file mode 100644 index 3cedf27..0000000 --- a/src/CommonAPI/OutputStream.h +++ /dev/null @@ -1,555 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_OUTPUT_STREAM_H_ -#define COMMONAPI_OUTPUT_STREAM_H_ - -#include "ByteBuffer.h" -#include "SerializableStruct.h" -#include "SerializableVariant.h" -#include "types.h" -#include <iostream> - -#include <cstdint> -#include <functional> -#include <memory> -#include <string> -#include <unordered_map> -#include <vector> -#include <type_traits> - -namespace CommonAPI { - -class SerializableVariant; - -class TypeOutputStream { -public: - virtual ~TypeOutputStream() {} - - virtual void writeBoolType() = 0; - - virtual void writeInt8Type() = 0; - virtual void writeInt16Type() = 0; - virtual void writeInt32Type() = 0; - virtual void writeInt64Type() = 0; - - virtual void writeUInt8Type() = 0; - virtual void writeUInt16Type() = 0; - virtual void writeUInt32Type() = 0; - virtual void writeUInt64Type() = 0; - - virtual void writeInt8EnumType() = 0; - virtual void writeInt16EnumType() = 0; - virtual void writeInt32EnumType() = 0; - virtual void writeInt64EnumType() = 0; - - virtual void writeUInt8EnumType() = 0; - virtual void writeUInt16EnumType() = 0; - virtual void writeUInt32EnumType() = 0; - virtual void writeUInt64EnumType() = 0; - - virtual void writeFloatType() = 0; - virtual void writeDoubleType() = 0; - - virtual void writeStringType() = 0; - virtual void writeByteBufferType() = 0; - virtual void writeVersionType() = 0; - - virtual void beginWriteVectorType() = 0; - virtual void endWriteVectorType() = 0; - - virtual void beginWriteMapType() = 0; - virtual void endWriteMapType() = 0; - - virtual void beginWriteStructType() = 0; - virtual void endWriteStructType() = 0; - - virtual void writeVariantType() = 0; - - virtual std::string retrieveSignature() = 0; -}; - -template<typename _Type> -struct TypeWriter; - -template<typename _Type> -struct BasicTypeWriter; - -template<> -struct BasicTypeWriter<bool> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeBoolType(); - } -}; - -template<> -struct BasicTypeWriter<int8_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeInt8Type(); - } -}; - -template<> -struct BasicTypeWriter<int16_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeInt16Type(); - } -}; - -template<> -struct BasicTypeWriter<int32_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeInt32Type(); - } -}; - -template<> -struct BasicTypeWriter<int64_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeInt64Type(); - } -}; - -template<> -struct BasicTypeWriter<uint8_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeUInt8Type(); - } -}; - -template<> -struct BasicTypeWriter<uint16_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeUInt16Type(); - } -}; - -template<> -struct BasicTypeWriter<uint32_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeUInt32Type(); - } -}; - -template<> -struct BasicTypeWriter<uint64_t> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeUInt64Type(); - } -}; - -template<> -struct BasicTypeWriter<float> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeFloatType(); - } -}; - -template<> -struct BasicTypeWriter<double> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeDoubleType(); - } -}; - -template<> -struct BasicTypeWriter<std::string> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeStringType(); - } -}; - -template<> -struct BasicTypeWriter<CommonAPI::ByteBuffer> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeByteBufferType(); - } -}; - -template<> -struct BasicTypeWriter<CommonAPI::Version> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeVersionType(); - } -}; - -template<typename _VectorElementType> -struct BasicTypeWriter<std::vector<_VectorElementType>> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.beginWriteVectorType(); - TypeWriter<_VectorElementType>::writeType(typeStream); - } -}; - -template<typename _KeyType, typename _ValueType> -struct BasicTypeWriter<std::unordered_map<_KeyType, _ValueType>> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.beginWriteMapType(); - - BasicTypeWriter<_KeyType>::writeType(typeStream); - BasicTypeWriter<_ValueType>::writeType(typeStream); - - typeStream.endWriteMapType(); - } -}; - -template<typename _Type, bool _IsStructType = false> -struct StructTypeWriter: public BasicTypeWriter<_Type> { -}; - -template<typename _Type> -struct StructTypeWriter<_Type, true> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.beginWriteStructType(); - _Type::writeToTypeOutputStream(typeStream); - typeStream.endWriteStructType(); - } -}; - -template<typename _Type, bool _IsVariantType = false> -struct VariantTypeWriter: public StructTypeWriter<_Type, std::is_base_of<SerializableStruct, _Type>::value> { -}; - -template<typename _Type> -struct VariantTypeWriter<_Type, true> { - inline static void writeType(TypeOutputStream& typeStream) { - typeStream.writeVariantType(); - } -}; - -template<typename _Type> -struct TypeWriter: public VariantTypeWriter<_Type, std::is_base_of<SerializableVariant, _Type>::value> { -}; - -class OutputStream { -public: - virtual ~OutputStream() { - } - virtual bool hasError() const = 0; - - virtual OutputStream& writeValue(const bool& boolValue) = 0; - - virtual OutputStream& writeValue(const int8_t& int8Value) = 0; - virtual OutputStream& writeValue(const int16_t& int16Value) = 0; - virtual OutputStream& writeValue(const int32_t& int32Value) = 0; - virtual OutputStream& writeValue(const int64_t& int64Value) = 0; - - virtual OutputStream& writeValue(const uint8_t& uint8Value) = 0; - virtual OutputStream& writeValue(const uint16_t& uint16Value) = 0; - virtual OutputStream& writeValue(const uint32_t& uint32Value) = 0; - virtual OutputStream& writeValue(const uint64_t& uint64Value) = 0; - - virtual OutputStream& writeValue(const float& floatValue) = 0; - virtual OutputStream& writeValue(const double& doubleValue) = 0; - - virtual OutputStream& writeValue(const std::string& stringValue) = 0; - - virtual OutputStream& writeValue(const ByteBuffer& byteBufferValue) = 0; - - virtual OutputStream& writeEnumValue(const int8_t& int8BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const int16_t& int16BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const int32_t& int32BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const int64_t& int64BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const uint8_t& uint8BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const uint16_t& uint16BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const uint32_t& uint32BackingTypeValue) = 0; - virtual OutputStream& writeEnumValue(const uint64_t& uint64BackingTypeValue) = 0; - - virtual OutputStream& writeVersionValue(const Version& versionValue) = 0; - - virtual void beginWriteSerializableStruct(const SerializableStruct& serializableStruct) = 0; - virtual void endWriteSerializableStruct(const SerializableStruct& serializableStruct) = 0; - - virtual void beginWriteSerializablePolymorphicStruct(const std::shared_ptr<SerializablePolymorphicStruct>& serializableStruct) = 0; - virtual void endWriteSerializablePolymorphicStruct(const std::shared_ptr<SerializablePolymorphicStruct>& serializableStruct) = 0; - - virtual void beginWriteSerializableVariant(const SerializableVariant& serializableVariant) = 0; - virtual void endWriteSerializableVariant(const SerializableVariant& serializableVariant) = 0; - - virtual void beginWriteBoolVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt8Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt16Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt32Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt64Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt8Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt16Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt32Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt64Vector(uint32_t sizeOfVector) = 0; - virtual void beginWriteFloatVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteDoubleVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteStringVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteByteBufferVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteVersionVector(uint32_t sizeOfVector) = 0; - - virtual void beginWriteInt8EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt16EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt32EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteInt64EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt8EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt16EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt32EnumVector(uint32_t sizeOfVector) = 0; - virtual void beginWriteUInt64EnumVector(uint32_t sizeOfVector) = 0; - - virtual void beginWriteVectorOfSerializableStructs(uint32_t sizeOfVector) = 0; - virtual void beginWriteVectorOfSerializableVariants(uint32_t sizeOfVector) = 0; - virtual void beginWriteVectorOfVectors(uint32_t sizeOfVector) = 0; - virtual void beginWriteVectorOfMaps(uint32_t sizeOfVector) = 0; - - virtual void beginWriteVectorOfSerializablePolymorphicStructs(uint32_t sizeOfVector) = 0; - - virtual void endWriteVector() = 0; - - virtual void beginWriteMap(size_t elementCount) = 0; - virtual void endWriteMap() = 0; - virtual void beginWriteMapElement() = 0; - virtual void endWriteMapElement() = 0; - - virtual bool writeRawData(const char* rawDataPtr, const size_t sizeInByte) = 0; -}; - -inline OutputStream& operator<<(OutputStream& outputStream, const bool& boolValue) { - return outputStream.writeValue(boolValue); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const int8_t& int8Value) { - return outputStream.writeValue(int8Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const int16_t& int16Value) { - return outputStream.writeValue(int16Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const int32_t& int32Value) { - return outputStream.writeValue(int32Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const int64_t& int64Value) { - return outputStream.writeValue(int64Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const uint8_t& uint8Value) { - return outputStream.writeValue(uint8Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const uint16_t& uint16Value) { - return outputStream.writeValue(uint16Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const uint32_t& uint32Value) { - return outputStream.writeValue(uint32Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const uint64_t& uint64Value) { - return outputStream.writeValue(uint64Value); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const float& floatValue) { - return outputStream.writeValue(floatValue); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const double& doubleValue) { - return outputStream.writeValue(doubleValue); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const std::string& stringValue) { - return outputStream.writeValue(stringValue); -} - -inline OutputStream& operator<<(OutputStream& outputStream, const Version& versionValue) { - return outputStream.writeVersionValue(versionValue); -} - -template<typename _SerializablePolymorphicStructType> -typename std::enable_if<std::is_base_of<SerializablePolymorphicStruct, _SerializablePolymorphicStructType>::value, - OutputStream>::type& -operator<<(OutputStream& outputStream, - const std::shared_ptr<_SerializablePolymorphicStructType>& serializablePolymorphicStruct) { - outputStream.beginWriteSerializablePolymorphicStruct(serializablePolymorphicStruct); - serializablePolymorphicStruct->writeToOutputStream(outputStream); - outputStream.endWriteSerializablePolymorphicStruct(serializablePolymorphicStruct); - - return outputStream; -} - -inline OutputStream& operator<<(OutputStream& outputStream, const SerializableStruct& serializableStruct) { - outputStream.beginWriteSerializableStruct(serializableStruct); - serializableStruct.writeToOutputStream(outputStream); - outputStream.endWriteSerializableStruct(serializableStruct); - - return outputStream; -} - -inline OutputStream& operator<<(OutputStream& outputStream, const SerializableVariant& serializableVariant) { - outputStream.beginWriteSerializableVariant(serializableVariant); - serializableVariant.writeToOutputStream(outputStream); - outputStream.endWriteSerializableVariant(serializableVariant); - - return outputStream; -} - -template<typename _VectorElementType> -class OutStreamGenericVectorHelper { -public: - static void beginWriteVector(OutputStream& outputStream, const std::vector<_VectorElementType>& vectorValue) { - doBeginWriteVector(outputStream, vectorValue); - } - -private: - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<bool>& vectorValue) { - outputStream.beginWriteBoolVector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<int8_t>& vectorValue) { - outputStream.beginWriteInt8Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<int16_t>& vectorValue) { - outputStream.beginWriteInt16Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<int32_t>& vectorValue) { - outputStream.beginWriteInt32Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<int64_t>& vectorValue) { - outputStream.beginWriteInt64Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<uint8_t>& vectorValue) { - outputStream.beginWriteUInt8Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<uint16_t>& vectorValue) { - outputStream.beginWriteUInt16Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<uint32_t>& vectorValue) { - outputStream.beginWriteUInt32Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<uint64_t>& vectorValue) { - outputStream.beginWriteUInt64Vector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<float>& vectorValue) { - outputStream.beginWriteFloatVector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<double>& vectorValue) { - outputStream.beginWriteDoubleVector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<std::string>& vectorValue) { - outputStream.beginWriteStringVector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<ByteBuffer>& vectorValue) { - outputStream.beginWriteByteBufferVector(vectorValue.size()); - } - static inline void doBeginWriteVector(OutputStream& outputStream, const std::vector<Version>& vectorValue) { - outputStream.beginWriteVersionVector(vectorValue.size()); - } - - template<typename _PointerType, - typename = typename std::enable_if< - std::is_base_of<SerializablePolymorphicStruct, _PointerType>::value>::type> - static inline void doBeginWriteVector(OutputStream& outputStream, - const std::vector<std::shared_ptr<_PointerType>>& vectorValue) { - outputStream.beginWriteVectorOfSerializablePolymorphicStructs(vectorValue.size()); - } - - template<typename _InnerVectorElementType> - static inline void doBeginWriteVector(OutputStream& outputStream, - const std::vector<std::vector<_InnerVectorElementType>>& vectorValue) { - outputStream.beginWriteVectorOfVectors(vectorValue.size()); - } - - template<typename _InnerKeyType, typename _InnerValueType, typename _InnerHashType> - static inline void doBeginWriteVector(OutputStream& outputStream, - const std::vector<std::unordered_map<_InnerKeyType, _InnerValueType, _InnerHashType>>& vectorValue) { - outputStream.beginWriteVectorOfMaps(vectorValue.size()); - } - - template<typename _InnerKeyType, typename _InnerValueType> - static inline void doBeginWriteVector(OutputStream& outputStream, - const std::vector<std::unordered_map<_InnerKeyType, _InnerValueType>>& vectorValue) { - outputStream.beginWriteVectorOfMaps(vectorValue.size()); - } -}; - -template<typename _VectorElementType, bool _IsSerializableStruct = false> -struct OutputStreamSerializableStructVectorHelper: public OutStreamGenericVectorHelper<_VectorElementType> { -}; - -template<typename _VectorElementType> -struct OutputStreamSerializableStructVectorHelper<_VectorElementType, true> { - static void beginWriteVector(OutputStream& outputStream, const std::vector<_VectorElementType>& vectorValue) { - outputStream.beginWriteVectorOfSerializableStructs(vectorValue.size()); - } -}; - -template<typename _VectorElementType, bool _IsSerializableVariant = false> -struct OutputStreamSerializableVariantVectorHelper: public OutputStreamSerializableStructVectorHelper< - _VectorElementType, - std::is_base_of<SerializableStruct, _VectorElementType>::value> { -}; - -template<typename _VectorElementType> -struct OutputStreamSerializableVariantVectorHelper<_VectorElementType, true> { - static void beginWriteVector(OutputStream& outputStream, const std::vector<_VectorElementType>& vectorValue) { - outputStream.beginWriteVectorOfSerializableVariants(vectorValue.size()); - } -}; - -template<typename _VectorElementType> -struct OutputStreamVectorHelper: OutputStreamSerializableVariantVectorHelper<_VectorElementType, - std::is_base_of<SerializableVariant, _VectorElementType>::value> { -}; - -/** - * Handles all writing of vectors to a given #OutputStream. The given vector may contain any types that are - * defined as basic types within the context of CommonAPI, as well as any types derived from those basic types. - * - * @tparam _ElementType The type of the elements that are contained in the given vector. - * @param val The vector that is to be written into the given stream - * @param outputStream The stream which is to be written into - * @return The given outputStream to allow for successive writing. - * @see operator<<(OutputStream&, const _BasicType&) - * @see SerializableStruct - * @see SerializableVariant - */ -template<typename _VectorElementType> -OutputStream& operator<<(OutputStream& outputStream, const std::vector<_VectorElementType>& vectorValue) { - OutputStreamVectorHelper<_VectorElementType>::beginWriteVector(outputStream, vectorValue); - const size_t elementCount = vectorValue.size(); - - for (size_t i = 0; i < elementCount; i++) { - outputStream << vectorValue[i]; - - if (outputStream.hasError()) - break; - } - - outputStream.endWriteVector(); - return outputStream; -} - -template<typename _KeyType, typename _ValueType, typename _HasherType> -OutputStream& operator<<(OutputStream& outputStream, - const std::unordered_map<_KeyType, _ValueType, _HasherType>& mapValue) { - typedef typename std::unordered_map<_KeyType, _ValueType, _HasherType>::const_iterator MapConstIterator; - - const size_t elementCount = mapValue.size(); - outputStream.beginWriteMap(elementCount); - - for (MapConstIterator iter = mapValue.cbegin(); iter != mapValue.cend(); iter++) { - outputStream.beginWriteMapElement(); - outputStream << iter->first << iter->second; - if (outputStream.hasError()) - return outputStream; - outputStream.endWriteMapElement(); - } - - outputStream.endWriteMap(); - return outputStream; -} - -} // namespace CommonAPI - -#endif // COMMONAPI_OUTPUT_STREAM_H_ diff --git a/src/CommonAPI/Proxy.cpp b/src/CommonAPI/Proxy.cpp new file mode 100644 index 0000000..072fc30 --- /dev/null +++ b/src/CommonAPI/Proxy.cpp @@ -0,0 +1,15 @@ +// Copyright (C) 2013-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <CommonAPI/Proxy.hpp> + +namespace CommonAPI { + +const Address & +Proxy::getAddress() const { + return address_; +} + +} // namespace CommonAPI diff --git a/src/CommonAPI/Proxy.h b/src/CommonAPI/Proxy.h deleted file mode 100644 index b427824..0000000 --- a/src/CommonAPI/Proxy.h +++ /dev/null @@ -1,54 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_PROXY_H_ -#define COMMONAPI_PROXY_H_ - -#include "Attribute.h" - -#include <cstdint> -#include <memory> -#include <type_traits> - -namespace CommonAPI { - -typedef Event<AvailabilityStatus> ProxyStatusEvent; -typedef ReadonlyAttribute<Version> InterfaceVersionAttribute; - - -class Proxy { - public: - virtual ~Proxy() { } - - // The addressing scheme has the following format: "domain:service:instance" - virtual std::string getAddress() const = 0; - - // i.e. "local" - virtual const std::string& getDomain() const = 0; - - // i.e. "com.bmw.infotainment" - virtual const std::string& getServiceId() const = 0; - - // i.e. "com.bmw.infotainment.low" - virtual const std::string& getInstanceId() const = 0; - - virtual bool isAvailable() const = 0; - - virtual bool isAvailableBlocking() const = 0; - - virtual ProxyStatusEvent& getProxyStatusEvent() = 0; - - virtual InterfaceVersionAttribute& getInterfaceVersionAttribute() = 0; -}; - -} // namespace CommonAPI - -#endif // COMMONAPI_PROXY_H_ diff --git a/src/CommonAPI/ProxyManager.cpp b/src/CommonAPI/ProxyManager.cpp new file mode 100644 index 0000000..ac3b263 --- /dev/null +++ b/src/CommonAPI/ProxyManager.cpp @@ -0,0 +1,18 @@ +// Copyright (C) 2013-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <CommonAPI/ProxyManager.hpp> +#include <CommonAPI/Runtime.hpp> + +namespace CommonAPI { + +std::shared_ptr<Proxy> +ProxyManager::createProxy( + const std::string &_domain, const std::string &_interface, const std::string &_instance, + const ConnectionId_t &_connection) const { + return Runtime::get()->createProxy(_domain, _interface, _instance, _connection); +} + +} // namespace CommonAPI diff --git a/src/CommonAPI/ProxyManager.h b/src/CommonAPI/ProxyManager.h deleted file mode 100644 index ecb8799..0000000 --- a/src/CommonAPI/ProxyManager.h +++ /dev/null @@ -1,92 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_PROXY_MANAGER_H_ -#define COMMONAPI_PROXY_MANAGER_H_ - -#include "types.h" -#include "Event.h" -#include "Proxy.h" -#include "Factory.h" - -#include <functional> -#include <future> -#include <string> -#include <vector> - - -namespace CommonAPI { - -class ProxyManager { - public: - typedef std::function<void(const CallStatus&, const std::vector<std::string>&)> GetAvailableInstancesCallback; - typedef std::function<void(const CallStatus&, const AvailabilityStatus&)> GetInstanceAvailabilityStatusCallback; - - typedef Event<std::string, AvailabilityStatus> InstanceAvailabilityStatusChangedEvent; - - ProxyManager() { }; - ProxyManager(ProxyManager&&) = delete; - ProxyManager(const ProxyManager&) = delete; - - virtual ~ProxyManager() { } - - virtual void getAvailableInstances(CommonAPI::CallStatus&, std::vector<std::string>& availableInstances) = 0; - virtual std::future<CallStatus> getAvailableInstancesAsync(GetAvailableInstancesCallback callback) = 0; - - virtual void getInstanceAvailabilityStatus(const std::string& instanceAddress, - CallStatus& callStatus, - AvailabilityStatus& availabilityStatus) = 0; - - virtual std::future<CallStatus> getInstanceAvailabilityStatusAsync(const std::string&, - GetInstanceAvailabilityStatusCallback callback) = 0; - - virtual InstanceAvailabilityStatusChangedEvent& getInstanceAvailabilityStatusChangedEvent() = 0; - - template<template<typename ...> class _ProxyClass, typename ... _AttributeExtensions> - std::shared_ptr< - _ProxyClass< -#ifdef WIN32 - CommonAPI::WINDummyAttributeExtension<WINDummyAttribute>, -#endif - _AttributeExtensions...> - > - buildProxy(const std::string& instanceName) { - std::shared_ptr<Proxy> abstractMiddlewareProxy = createProxy(instanceName); - if (abstractMiddlewareProxy) { - auto returnProxy = std::make_shared< - _ProxyClass< -#ifdef WIN32 - CommonAPI::WINDummyAttributeExtension<WINDummyAttribute>, -#endif - _AttributeExtensions...> - >(abstractMiddlewareProxy); - return returnProxy; - } - return NULL; - } - - template <template<typename ...> class _ProxyClass, template<typename> class _AttributeExtension> - std::shared_ptr<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t> - buildProxyWithDefaultAttributeExtension(const std::string& instanceName) { - std::shared_ptr<Proxy> abstractMiddlewareProxy = createProxy(instanceName); - if (abstractMiddlewareProxy) { - return std::make_shared<typename DefaultAttributeProxyFactoryHelper<_ProxyClass, _AttributeExtension>::class_t>(abstractMiddlewareProxy); - } - return NULL; - } - - protected: - virtual std::shared_ptr<Proxy> createProxy(const std::string& instanceName) = 0; -}; - -} // namespace CommonAPI - -#endif // COMMONAPI_PROXY_MANAGER_H_ diff --git a/src/CommonAPI/Runtime.cpp b/src/CommonAPI/Runtime.cpp index bc5c4dc..95c2832 100644 --- a/src/CommonAPI/Runtime.cpp +++ b/src/CommonAPI/Runtime.cpp @@ -1,393 +1,409 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include <sys/types.h> -#include <sys/stat.h> -#ifndef WIN32 -#include <dirent.h> +// Copyright (C) 2013-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#ifdef WIN32 +#include <Windows.h> +#else #include <dlfcn.h> +#include <unistd.h> #endif -#include <algorithm> -#include <iostream> -#include <unordered_map> -#include <stdexcept> +#include <sys/stat.h> -#include "Runtime.h" -#include "Configuration.h" -#include "utils.h" +#include <algorithm> +#include <CommonAPI/Factory.hpp> +#include <CommonAPI/IniFileReader.hpp> +#include <CommonAPI/Logger.hpp> +#include <CommonAPI/Runtime.hpp> namespace CommonAPI { +const char *COMMONAPI_DEFAULT_BINDING = "dbus"; +const char *COMMONAPI_DEFAULT_FOLDER = "/usr/local/lib/commonapi"; +const char *COMMONAPI_DEFAULT_CONFIG_FILE = "commonapi.ini"; +const char *COMMONAPI_DEFAULT_CONFIG_FOLDER = "/etc"; -static std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>* registeredRuntimeLoadFunctions_; -static bool isDynamic_ = false; - -static const char COMMONAPI_LIB_PREFIX[] = "libCommonAPI-"; -static const char MIDDLEWARE_INFO_SYMBOL_NAME[] = "middlewareInfo"; +std::map<std::string, std::string> properties__; +std::shared_ptr<Runtime> Runtime::theRuntime__ = std::make_shared<Runtime>(); -#ifndef WIN32 -bool Runtime::tryLoadLibrary(const std::string& libraryPath, - void** sharedLibraryHandle, - MiddlewareInfo** foundMiddlewareInfo) { - - //In case we find an already loaded library again while looking for another one, - //there is no need to look at it - if (dlopen(libraryPath.c_str(), RTLD_NOLOAD)) { - return false; - } - - //In order to place symbols of the newly loaded library ahead of already resolved symbols, we need - //RTLD_DEEPBIND. This is necessary for this case: A library already is linked at compile time, but while - //trying to resolve another library dynamically we might find the very same library again. - //dlopen() doesn't know about the compile time linked library and will close it if dlclose() ever is - //called, thereby causing memory corruptions. Therefore, we must be able to access the middlewareInfo - //of the newly dlopened library in order to determine whether it already has been linked. - *sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND); - if (*sharedLibraryHandle == NULL) { - return false; - } - - *foundMiddlewareInfo = static_cast<MiddlewareInfo*>(dlsym(*sharedLibraryHandle, MIDDLEWARE_INFO_SYMBOL_NAME)); - - //In this context, a resolved value of NULL it is just as invalid as if dlerror() was set additionally. - if (!*foundMiddlewareInfo) { - dlclose(*sharedLibraryHandle); - return false; - } - - if (!(*foundMiddlewareInfo)->middlewareName_ || !(*foundMiddlewareInfo)->getInstance_) { - dlclose(sharedLibraryHandle); - return false; - } - - return true; +std::string +Runtime::getProperty(const std::string &_name) { + auto foundProperty = properties__.find(_name); + if (foundProperty != properties__.end()) + return foundProperty->second; + return ""; } -bool Runtime::checkAndLoadLibrary(const std::string& libraryPath, - const std::string& requestedBindingIdentifier, - bool keepLibrary) { - - void* sharedLibraryHandle = NULL; - MiddlewareInfo* foundMiddlewareInfo; - if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { - return false; - } - - if (foundMiddlewareInfo->middlewareName_ != requestedBindingIdentifier) { - //If library was linked at compile time (and therefore an appropriate runtime loader is registered), - //the library must not be closed! - auto foundRegisteredRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundMiddlewareInfo->middlewareName_); - if (foundRegisteredRuntimeLoader == registeredRuntimeLoadFunctions_->end()) { - dlclose(sharedLibraryHandle); - } - return false; - } - - if (!keepLibrary) { - dlclose(sharedLibraryHandle); - } else { - //Extend visibility to make symbols available to all other libraries that are loaded afterwards, - //e.g. libraries containing generated binding specific code. - sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); - if (!sharedLibraryHandle) { - return false; - } - registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); - } - - return true; +void +Runtime::setProperty(const std::string &_name, const std::string &_value) { + properties__[_name] = _value; } -bool Runtime::checkAndLoadDefaultLibrary(std::string& foundBindingIdentifier, const std::string& libraryPath) { - void* sharedLibraryHandle = NULL; - MiddlewareInfo* foundMiddlewareInfo; - if (!tryLoadLibrary(libraryPath, &sharedLibraryHandle, &foundMiddlewareInfo)) { - return false; - } - - //Extend visibility to make symbols available to all other linked libraries, - //e.g. libraries containing generated binding specific code - sharedLibraryHandle = dlopen(libraryPath.c_str(), RTLD_NOW | RTLD_GLOBAL); - if (!sharedLibraryHandle) { - return false; - } - registeredRuntimeLoadFunctions_->insert( {foundMiddlewareInfo->middlewareName_, foundMiddlewareInfo->getInstance_} ); - foundBindingIdentifier = foundMiddlewareInfo->middlewareName_; - - return true; +std::shared_ptr<Runtime> Runtime::get() { + theRuntime__->init(); + return theRuntime__; } -const std::vector<std::string> Runtime::readDirectory(const std::string& path) { - std::vector<std::string> result; - struct stat filestat; - - DIR *directory = opendir(path.c_str()); - - if (!directory) { - return std::vector<std::string>(); - } - - struct dirent* entry; - - while ((entry = readdir(directory))) { - const std::string fqnOfEntry = path + entry->d_name; - - if (stat(fqnOfEntry.c_str(), &filestat)) { - continue; - } - if (S_ISDIR(filestat.st_mode)) { - continue; - } - - if (strncmp(COMMONAPI_LIB_PREFIX, entry->d_name, strlen(COMMONAPI_LIB_PREFIX)) != 0) { - continue; - } - - const char* fileNamePtr = entry->d_name; - while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { - if (strncmp(".so", fileNamePtr, 3) == 0) { - break; - } - } - - if (fileNamePtr) { - result.push_back(fqnOfEntry); - } - } - - closedir (directory); - - std::sort( result.begin(), result.end() ); - - return result; +Runtime::Runtime() + : defaultBinding_(COMMONAPI_DEFAULT_BINDING), + defaultFolder_(COMMONAPI_DEFAULT_FOLDER) { } -#endif -struct LibraryVersion { - int32_t major; - int32_t minor; - int32_t revision; -}; - -bool operator<(LibraryVersion const& lhs, LibraryVersion const& rhs) { - if (lhs.major == rhs.major) { - if (lhs.minor == rhs.minor) { - return lhs.revision < rhs.revision; - } - return lhs.minor < rhs.minor; - } - return lhs.major < rhs.major; +Runtime::~Runtime() { + // intentionally left empty } +bool +Runtime::registerFactory(const std::string &_binding, std::shared_ptr<Factory> _factory) { + COMMONAPI_DEBUG("Registering factory for binding=", _binding); + bool isRegistered(false); #ifndef WIN32 -std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(const std::string& requestedMiddlewareName, LoadState& loadState) { - const std::string& middlewareLibraryPath = Configuration::getInstance().getMiddlewareLibraryPath(requestedMiddlewareName); - - if (middlewareLibraryPath != "") { - if (!checkAndLoadLibrary(middlewareLibraryPath, requestedMiddlewareName, true)) { - //A path for requestedMiddlewareName was configured, but no corresponding library was found - loadState = LoadState::CONFIGURATION_ERROR; - return std::shared_ptr<Runtime>(NULL); - } else { - const std::string currentBinaryFQN = getCurrentBinaryFileFQN(); - const uint32_t lastPathSeparatorPosition = currentBinaryFQN.find_last_of("/\\"); - const std::string currentBinaryPath = currentBinaryFQN.substr(0, lastPathSeparatorPosition + 1); - auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); - if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - return (foundRuntimeLoader->second)(); - } - //One should not get here - loadState = LoadState::BINDING_ERROR; - return std::shared_ptr<Runtime>(NULL); - } - } - - const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); - - LibraryVersion highestVersionFound = {0, 0, 0}; - std::string fqnOfHighestVersion = ""; - - for (const std::string& singleSearchPath: librarySearchPaths) { - std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); - - for (const std::string& fqnOfEntry : orderedLibraries) { - std::string versionString; - LibraryVersion currentLibraryVersion = {-1, -1, -1}; - - const char* fileNamePtr = fqnOfEntry.c_str(); - while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { - if (strncmp(".so", fileNamePtr, 3) == 0) { - break; - } - } - - const char* positionOfFirstDot = strchr(fileNamePtr + 1, '.'); - if (positionOfFirstDot) { - versionString = positionOfFirstDot + 1; - } - - std::vector<std::string> versionElements = split(versionString, '.'); - if (versionElements.size() >= 1 && containsOnlyDigits(versionElements[0])) { - currentLibraryVersion.major = strtol(versionElements[0].c_str(), NULL, 0); - } - if (versionElements.size() >= 3 && containsOnlyDigits(versionElements[2])) { - currentLibraryVersion.minor = strtol(versionElements[1].c_str(), NULL, 0); - currentLibraryVersion.revision = strtol(versionElements[2].c_str(), NULL, 0); - } - - if (highestVersionFound < currentLibraryVersion) { - if (!checkAndLoadLibrary(fqnOfEntry, requestedMiddlewareName, false)) { - continue; - } - highestVersionFound = currentLibraryVersion; - fqnOfHighestVersion = fqnOfEntry; - } - } - } - - if (fqnOfHighestVersion != "") { - checkAndLoadLibrary(fqnOfHighestVersion, requestedMiddlewareName, true); - - auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(requestedMiddlewareName); - if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - std::shared_ptr<Runtime> loadedRuntime = foundRuntimeLoader->second(); - if (!loadedRuntime) { - loadState = LoadState::BINDING_ERROR; - } - return loadedRuntime; - } - } - - loadState = LoadState::NO_LIBRARY_FOUND; - - return std::shared_ptr<Runtime>(); + std::lock_guard<std::mutex> itsLock(factoriesMutex_); +#endif + if (_binding == defaultBinding_) { + defaultFactory_ = _factory; + } else { + auto foundFactory = factories_.find(_binding); + if (foundFactory == factories_.end()) { + factories_[_binding] = _factory; + isRegistered = true; + } + } + return isRegistered; } - -std::shared_ptr<Runtime> Runtime::checkDynamicLibraries(LoadState& loadState) { - const std::vector<std::string>& librarySearchPaths = Configuration::getInstance().getLibrarySearchPaths(); - - for (const std::string& singleSearchPath : librarySearchPaths) { - std::vector<std::string> orderedLibraries = readDirectory(singleSearchPath); - - for (const std::string& fqnOfEntry: orderedLibraries) { - std::string foundBindingName; - if (!checkAndLoadDefaultLibrary(foundBindingName, fqnOfEntry)) { - continue; - } - - auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(foundBindingName); - if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - return (foundRuntimeLoader->second)(); - } - } - } - - loadState = LoadState::NO_LIBRARY_FOUND; - - return std::shared_ptr<Runtime>(); -} +bool +Runtime::unregisterFactory(const std::string &_binding) { + COMMONAPI_DEBUG("Unregistering factory for binding=", _binding); +#ifndef WIN32 + std::lock_guard<std::mutex> itsLock(factoriesMutex_); #endif - -void Runtime::registerRuntimeLoader(const std::string& middlewareName, const MiddlewareRuntimeLoadFunction& middlewareRuntimeLoadFunction) { - if (!registeredRuntimeLoadFunctions_) { - registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); - } - if (!isDynamic_) { - registeredRuntimeLoadFunctions_->insert( {middlewareName, middlewareRuntimeLoadFunction}); - } + if (_binding == defaultBinding_) { + defaultFactory_.reset(); + } else { + factories_.erase(_binding); + } + return true; } - -std::shared_ptr<Runtime> Runtime::load() { - LoadState dummyState; - return load(dummyState); +/* + * Private + */ +void Runtime::init() { + static bool isInitialized(false); +#ifndef WIN32 + std::lock_guard<std::mutex> itsLock(mutex_); +#endif + if (!isInitialized) { + // Determine default configuration file + const char *config = getenv("COMMONAPI_CONFIG"); + if (config) { + defaultConfig_ = config; + } else { + defaultConfig_ = COMMONAPI_DEFAULT_CONFIG_FOLDER; + defaultConfig_ += "/"; + defaultConfig_ += COMMONAPI_DEFAULT_CONFIG_FILE; + } + + // TODO: evaluate return parameter and decide what to do + (void)readConfiguration(); + + // Determine default ipc & shared library folder + const char *binding = getenv("COMMONAPI_DEFAULT_BINDING"); + if (binding) + defaultBinding_ = binding; + + const char *folder = getenv("COMMONAPI_DEFAULT_FOLDER"); + if (folder) + defaultFolder_ = folder; + + // Log settings + COMMONAPI_INFO("Using default binding \'", defaultBinding_, "\'"); + COMMONAPI_INFO("Using default shared library folder \'", defaultFolder_, "\'"); + COMMONAPI_INFO("Using default configuration file \'", defaultConfig_, "\'"); + + isInitialized = true; + } } - -std::shared_ptr<Runtime> Runtime::load(LoadState& loadState) { - isDynamic_ = true; - loadState = LoadState::SUCCESS; - if(!registeredRuntimeLoadFunctions_) { - registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); - } - - const std::string& defaultBindingIdentifier = Configuration::getInstance().getDefaultMiddlewareIdentifier(); - if (defaultBindingIdentifier != "") { - const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->find(defaultBindingIdentifier); - if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - return (defaultRuntimeLoader->second)(); - } - +bool +Runtime::readConfiguration() { +#define MAX_PATH_LEN 255 + std::string config; + char currentDirectory[MAX_PATH_LEN]; #ifdef WIN32 - return std::shared_ptr<Runtime>(); + if (GetCurrentDirectory(MAX_PATH_LEN, currentDirectory)) { #else - return checkDynamicLibraries(defaultBindingIdentifier, loadState); + if (getcwd(currentDirectory, MAX_PATH_LEN)) { #endif + config = currentDirectory; + config += "/"; + config += COMMONAPI_DEFAULT_CONFIG_FILE; + + struct stat s; + if (stat(config.c_str(), &s) != 0) { + config = defaultConfig_; + } + } + + IniFileReader reader; + if (!reader.load(config)) + return false; + + std::shared_ptr<IniFileReader::Section> section + = reader.getSection("logging"); + if (section) { + std::string itsConsole = section->getValue("console"); + std::string itsFile = section->getValue("file"); + std::string itsDlt = section->getValue("dlt"); + std::string itsLevel = section->getValue("level"); + + Logger::init((itsConsole == "true"), + itsFile, + (itsDlt == "true"), + itsLevel); + } + + section = reader.getSection("default"); + if (section) { + std::string binding = section->getValue("binding"); + if ("" != binding) + defaultBinding_ = binding; + + std::string folder = section->getValue("folder"); + if ("" != folder) + defaultFolder_ = folder; + } + + section = reader.getSection("proxy"); + if (section) { + for (auto m : section->getMappings()) { + COMMONAPI_DEBUG("Adding proxy mapping: ", m.first, " --> ", m.second); + libraries_[m.first][true] = m.second; + } + } + + section = reader.getSection("stub"); + if (section) { + for (auto m : section->getMappings()) { + COMMONAPI_DEBUG("Adding stub mapping: ", m.first, " --> ", m.second); + libraries_[m.first][false] = m.second; + } + } + + return true; +} - } else { - const auto defaultRuntimeLoader = registeredRuntimeLoadFunctions_->begin(); - if (defaultRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - return (defaultRuntimeLoader->second)(); - } -#ifdef WIN32 - return std::shared_ptr<Runtime>(); -#else - return checkDynamicLibraries(loadState); -#endif - } +std::shared_ptr<Proxy> +Runtime::createProxy( + const std::string &_domain, const std::string &_interface, const std::string &_instance, + const ConnectionId_t &_connectionId) { + + // Check whether we already know how to create such proxies... + std::shared_ptr<Proxy> proxy = createProxyHelper(_domain, _interface, _instance, _connectionId); + if (!proxy) { + // ...it seems do not, lets try to load a library that does... + std::lock_guard<std::mutex> itsGuard(loadMutex_); + std::string library = getLibrary(_domain, _interface, _instance, true); + if (loadLibrary(library)) { + proxy = createProxyHelper(_domain, _interface, _instance, _connectionId); + } + } + return proxy; } +std::shared_ptr<Proxy> +Runtime::createProxy( + const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<MainLoopContext> _context) { + + // Check whether we already know how to create such proxies... + std::shared_ptr<Proxy> proxy = createProxyHelper(_domain, _interface, _instance, _context); + if (!proxy) { + // ...it seems do not, lets try to load a library that does... + std::lock_guard<std::mutex> itsGuard(loadMutex_); + std::string library = getLibrary(_domain, _interface, _instance, true); + if (loadLibrary(library)) { + proxy = createProxyHelper(_domain, _interface, _instance, _context); + } + } + return proxy; +} -std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias) { - LoadState dummyState; - return load(middlewareIdOrAlias, dummyState); + +bool +Runtime::registerStub(const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<StubBase> _stub, const ConnectionId_t &_connectionId) { + + bool isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _connectionId); + if (!isRegistered) { + std::string library = getLibrary(_domain, _interface, _instance, false); + std::lock_guard<std::mutex> itsGuard(loadMutex_); + if (loadLibrary(library)) { + isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _connectionId); + } + } + return isRegistered; } -std::shared_ptr<Runtime> Runtime::load(const std::string& middlewareIdOrAlias, LoadState& loadState) { - isDynamic_ = true; - loadState = LoadState::SUCCESS; - if (!registeredRuntimeLoadFunctions_) { - registeredRuntimeLoadFunctions_ = new std::unordered_map<std::string, MiddlewareRuntimeLoadFunction>(); - } +bool +Runtime::registerStub(const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<StubBase> _stub, std::shared_ptr<MainLoopContext> _context) { + + bool isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _context); + if (!isRegistered) { + std::string library = getLibrary(_domain, _interface, _instance, false); + std::lock_guard<std::mutex> itsGuard(loadMutex_); + if (loadLibrary(library)) { + isRegistered = registerStubHelper(_domain, _interface, _instance, _stub, _context); + } + } + return isRegistered; +} - const std::string middlewareName = Configuration::getInstance().getMiddlewareNameForAlias(middlewareIdOrAlias); +bool +Runtime::unregisterStub(const std::string &_domain, const std::string &_interface, const std::string &_instance) { + for (auto factory : factories_) { + if (factory.second->unregisterStub(_domain, _interface, _instance)) + return true; + } - auto foundRuntimeLoader = registeredRuntimeLoadFunctions_->find(middlewareName); - if (foundRuntimeLoader != registeredRuntimeLoadFunctions_->end()) { - return (foundRuntimeLoader->second)(); - } + return (defaultFactory_ ? defaultFactory_->unregisterStub(_domain, _interface, _instance) : false); +} -#ifdef WIN32 - return std::shared_ptr<Runtime>(); -#else - return checkDynamicLibraries(middlewareName, loadState); -#endif +std::string +Runtime::getLibrary( + const std::string &_domain, const std::string &_interface, const std::string &_instance, + bool _isProxy) { + + std::string library; + std::string address = _domain + ":" + _interface + ":" + _instance; + + COMMONAPI_DEBUG("Loading library for ", address, (_isProxy ? " proxy." : " stub.")); + + auto libraryIterator = libraries_.find(address); + if (libraryIterator != libraries_.end()) { + auto addressIterator = libraryIterator->second.find(_isProxy); + if (addressIterator != libraryIterator->second.end()) { + library = addressIterator->second; + return library; + } + } + + // If no library was explicitely configured, check whether property + // "LibraryBase" is set. If yes, use it, if not build default library + // name. + library = getProperty("LibraryBase"); + if (library != "") { + library = "lib" + library + "-" + defaultBinding_; + } else { + library = "lib" + _domain + "__" + _interface + "__" + _instance; + std::replace(library.begin(), library.end(), '.', '_'); + } + + return library; } +bool +Runtime::loadLibrary(const std::string &_library) { + std::string itsLibrary(_library); + + // TODO: decide whether this really is a good idea... + #ifdef WIN32 + if (itsLibrary.rfind(".dll") != itsLibrary.length() - 4) { + itsLibrary += ".dll"; + } + #else + if (itsLibrary.rfind(".so") != itsLibrary.length() - 3) { + itsLibrary += ".so"; + } + #endif + + bool isLoaded(true); + if (loadedLibraries_.end() == loadedLibraries_.find(itsLibrary)) { + #ifdef WIN32 + if (LoadLibrary(itsLibrary.c_str()) != 0) { + loadedLibraries_.insert(itsLibrary); + COMMONAPI_DEBUG("Loading interface library \"", itsLibrary, "\" succeeded."); + } else { + COMMONAPI_ERROR("Loading interface library \"", itsLibrary, "\" failed (", GetLastError(), ")"); + isLoaded = false; + } + #else + if (dlopen(itsLibrary.c_str(), RTLD_LAZY | RTLD_GLOBAL) != 0) { + loadedLibraries_.insert(itsLibrary); + COMMONAPI_DEBUG("Loading interface library \"", itsLibrary, "\" succeeded."); + } + else { + COMMONAPI_ERROR("Loading interface library \"", itsLibrary, "\" failed (", dlerror(), ")"); + isLoaded = false; + } + #endif + } + return isLoaded; +} -std::shared_ptr<MainLoopContext> Runtime::getNewMainLoopContext() const { - return std::make_shared<MainLoopContext>(); +std::shared_ptr<Proxy> +Runtime::createProxyHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance, + const std::string &_connectionId) { + std::lock_guard<std::mutex> itsLock(factoriesMutex_); + for (auto factory : factories_) { + std::shared_ptr<Proxy> proxy + = factory.second->createProxy(_domain, _interface, _instance, _connectionId); + if (proxy) + return proxy; + } + return (defaultFactory_ ? + defaultFactory_->createProxy(_domain, _interface, _instance, _connectionId) + : nullptr); } -std::shared_ptr<Factory> Runtime::createFactory(const std::string factoryName, - const bool nullOnInvalidName) { - return createFactory(std::shared_ptr<MainLoopContext>(NULL), factoryName, nullOnInvalidName); +std::shared_ptr<Proxy> +Runtime::createProxyHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<MainLoopContext> _context ) { + std::lock_guard<std::mutex> itsLock(factoriesMutex_); + for (auto factory : factories_) { + std::shared_ptr<Proxy> proxy + = factory.second->createProxy(_domain, _interface, _instance, _context); + if (proxy) + return proxy; + } + return (defaultFactory_ ? + defaultFactory_->createProxy(_domain, _interface, _instance, _context) : + nullptr); } -std::shared_ptr<Factory> Runtime::createFactory(std::shared_ptr<MainLoopContext> mainLoopContext, - const std::string factoryName, - const bool nullOnInvalidName) { - if(mainLoopContext && !mainLoopContext->isInitialized()) { - return std::shared_ptr<Factory>(NULL); - } - return doCreateFactory(mainLoopContext, factoryName, nullOnInvalidName); +bool +Runtime::registerStubHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<StubBase> _stub, const std::string &_connectionId) { + bool isRegistered(false); + std::lock_guard<std::mutex> itsLock(factoriesMutex_); + for (auto factory : factories_) { + isRegistered = factory.second->registerStub(_domain, _interface, _instance, _stub, _connectionId); + if (isRegistered) + return isRegistered; + } + return (defaultFactory_ ? + defaultFactory_->registerStub(_domain, _interface, _instance, _stub, _connectionId) : + false); } +bool +Runtime::registerStubHelper(const std::string &_domain, const std::string &_interface, const std::string &_instance, + std::shared_ptr<StubBase> _stub, std::shared_ptr<MainLoopContext> _context) { + bool isRegistered(false); + std::lock_guard<std::mutex> itsLock(factoriesMutex_); + for (auto factory : factories_) { + isRegistered = factory.second->registerStub(_domain, _interface, _instance, _stub, _context); + if (isRegistered) + return isRegistered; + } + return (defaultFactory_ ? + defaultFactory_->registerStub(_domain, _interface, _instance, _stub, _context) : + false); +} -} // namespace CommonAPI +} //Namespace CommonAPI diff --git a/src/CommonAPI/Runtime.h b/src/CommonAPI/Runtime.h deleted file mode 100644 index 15fc05c..0000000 --- a/src/CommonAPI/Runtime.h +++ /dev/null @@ -1,203 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_RUNTIME_H_ -#define COMMONAPI_RUNTIME_H_ - - -#include "MiddlewareInfo.h" -#include "MainLoopContext.h" - -#include <memory> -#include <unordered_map> -#include <string> -#include <cassert> -#include <cstring> -#include <mutex> - - -namespace CommonAPI { - - -class Factory; -class Runtime; -class MainLoopContext; -class ServicePublisher; - -/** - * \brief Represents the CommonAPI runtime bindings available. - * - * Represents the CommonAPI runtime bindings available. - */ -class Runtime { - public: - enum class LoadState { - SUCCESS, - NO_LIBRARY_FOUND, - CONFIGURATION_ERROR, - BINDING_ERROR - }; - - virtual ~Runtime() {} - - /** - * \brief Loads the default runtime. - * - * Loads the runtime for the default middleware binding. This can be - * * One of the middleware bindings that were linked at compile time - * * The first middleware binding that is encountered when resolving bindings at runtime - * * The middleware binding that was configured as default in the corresponding configuration - * file (throws an error if no such binding exists) - * - * @return The runtime object for the default binding, or null if any error occurred - */ - static std::shared_ptr<Runtime> load(); - - /** - * \brief Loads the default runtime and notifies the caller of any errors. - * - * Loads the runtime for the default middleware binding. This can be - * * One of the middleware bindings that were linked at compile time - * * The first middleware binding that is encountered when resolving bindings at runtime - * * The middleware binding that was configured as default in the corresponding configuration - * file (throws an error if no such binding exists) - * - * @param loadState: An enumeration that will be set appropriately after loading has finished or - * aborted. May be used for debugging purposes. - * - * @return The runtime object for the default binding, or null if any error occurred. In the latter - * case, loadState will be set to an appropriate value. - */ - static std::shared_ptr<Runtime> load(LoadState& loadState); - - /** - * \brief Loads specified runtime. - * - * Loads the runtime for the specified middleware binding. The given well known name can be either - * the well known name defined by a binding, or a configured alias for a binding. - * - * @param middlewareIdOrAlias A well known name or an alias for a binding - * - * @return The runtime object for specified binding, or null if any error occurred. - */ - static std::shared_ptr<Runtime> load(const std::string& middlewareIdOrAlias); - - /** - * \brief Loads specified runtime. - * - * Loads the runtime for the specified middleware binding. The given well known name can be either - * the well known name defined by a binding, or a configured alias for a binding. - * - * @param middlewareIdOrAlias A well known name or an alias for a binding. - * @param loadState: An enumeration that will be set appropriately after loading has finished or - * aborted. May be used for debugging purposes. - * - * @return The runtime object for specified binding, or null if any error occurred. In the latter - * case, loadState will be set to an appropriate value. - */ - static std::shared_ptr<Runtime> load(const std::string& middlewareIdOrAlias, LoadState& loadState); - - /** - * \brief Called by bindings to register their runtime loaders. Do not call from applications. - * - * Called by bindings to register their runtime loaders. Do not call from applications. - */ - static void registerRuntimeLoader(const std::string& middlewareName, const MiddlewareRuntimeLoadFunction& middlewareRuntimeLoadFunction); - - /** - * \brief Returns new MainLoopContext. - * - * Creates and returns a new MainLoopContext object. This context can be used to take - * complete control over the order and time of execution of the abstract middleware - * dispatching mechanism. Make sure to register all callback functions before subsequently - * handing it to createFactory(), as during creation of the factory object the callbacks may - * already be called. - * - * @return A new MainLoopContext object - */ - std::shared_ptr<MainLoopContext> getNewMainLoopContext() const; - - /** - * \brief Create a factory for the loaded runtime. - * - * Create a factory for the loaded runtime - * - * @param mainLoopContext: In case mainloop integration shall be used, a std::shared_ptr<MainLoopContext> can be passed in. - * If no parameter is given, internal threading will handle sending and receiving of messages automatically. - * If the mainloop context is not initialized, no factory will be returned. See documentation of - * MainLoopContext::isInitialized(). - * - * @param factoryName: If additional configuration parameters for the specific middleware factory shall be provided, - * the appropriate set of parameters may be identified by this name. See accompanying documentation for - * usage of configuration files. - * - * @param nullOnInvalidName: If a factoryName is provided, this parameter determines whether the standard configuration - * for factories shall be used if the specific parameter set cannot be found, or if instead no factory - * shall be returned in this case. - * - * @return Factory object for this runtime - */ - std::shared_ptr<Factory> createFactory(std::shared_ptr<MainLoopContext> mainLoopContext = std::shared_ptr<MainLoopContext>(NULL), - const std::string factoryName = "", - const bool nullOnInvalidName = false); - - /** - * \brief Create a factory for the loaded runtime. - * - * Create a factory for the loaded runtime - * - * @param factoryName: If additional configuration parameters for the specific middleware factory shall be provided, - * the appropriate set of parameters may be identified by this name. See accompanying documentation for - * usage of configuration files. - * - * @param nullOnInvalidName: If a factoryName is provided, this parameter determines whether the standard configuration - * for factories shall be used if the specific parameter set cannot be found, or if instead no factory - * shall be returned in this case. - * - * @return Factory object for this runtime - */ - std::shared_ptr<Factory> createFactory(const std::string factoryNamey, - const bool nullOnInvalidName = false); - - /** - * \brief Returns the ServicePublisher object for this runtime. - * - * Returns the ServicePublisher object for this runtime. Use the interface - * provided by the ServicePublisher to publish and de-publish the services that - * your application will provide to the outside world over the middleware - * represented by this runtime. A ServicePublisher exists once per middleware. - * - * @return The ServicePublisher object for this runtime - */ - virtual std::shared_ptr<ServicePublisher> getServicePublisher() = 0; - - protected: - virtual std::shared_ptr<Factory> doCreateFactory(std::shared_ptr<MainLoopContext> mainLoopContext, - const std::string& factoryName, - const bool nullOnInvalidName = false) = 0; - - private: - static const std::vector<std::string> readDirectory(const std::string& path); - - static std::shared_ptr<Runtime> checkDynamicLibraries(LoadState& loadState); - static std::shared_ptr<Runtime> checkDynamicLibraries(const std::string& middlewareName, LoadState& loadState); - - static bool tryLoadLibrary(const std::string& libraryPath, void** sharedLibraryHandle, MiddlewareInfo** foundMiddlewareInfo); - static bool checkAndLoadLibrary(const std::string& libraryPath, const std::string& requestedMiddlewareName, bool keepLibrary); - static bool checkAndLoadDefaultLibrary(std::string& foundBindingName, const std::string& libraryPath); - - static void closeHandle(void* libraryHandle); -}; - - -} // namespace CommonAPI - -#endif // COMMONAPI_RUNTIME_H_ diff --git a/src/CommonAPI/SelectiveEvent.h b/src/CommonAPI/SelectiveEvent.h deleted file mode 100644 index c430e8d..0000000 --- a/src/CommonAPI/SelectiveEvent.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_SELECTIVE_EVENT_H_ -#define COMMONAPI_SELECTIVE_EVENT_H_ - -#include "Event.h" - -namespace CommonAPI { - -template<typename ... _Arguments> -class SelectiveEvent: public Event<_Arguments...> { -public: - typedef typename Event<_Arguments...>::Listener Listener; - typedef typename Event<_Arguments...>::Subscription Subscription; - - virtual ~SelectiveEvent() { - } - - Subscription subscribe(Listener listener) { - // just delegate - bool success; - return subscribe(listener, success); - } - - /** - * \brief Subscribe a listener to this event and be notified of success - * - * Subscribe a listener to this event and be notified of success via the passed reference. - * ATTENTION: You should not build new proxies or register services in callbacks - * from events. This can cause a deadlock or assert. Instead, you should set a - * trigger for your application to do this on the next iteration of your event loop - * if needed. The preferred solution is to build all proxies you need at the - * beginning and react to events appropriatly for each. - * - * @param listener A listener to be added - * @param success Indicates whether subscription was accepted - * @return A token identifying this subscription - */ - virtual Subscription subscribe(Listener listener, bool& success) = 0; -}; - -} // namespace CommonAPI - -#endif diff --git a/src/CommonAPI/SerializableStruct.h b/src/CommonAPI/SerializableStruct.h deleted file mode 100644 index c704387..0000000 --- a/src/CommonAPI/SerializableStruct.h +++ /dev/null @@ -1,39 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_SERIALIZABLE_STRUCT_H_ -#define COMMONAPI_SERIALIZABLE_STRUCT_H_ - -#include <cstdint> -#include <memory> - - -namespace CommonAPI { - -class InputStream; -class OutputStream; -class TypeOutputStream; - -struct SerializableStruct { - virtual ~SerializableStruct() { } - - virtual void readFromInputStream(InputStream& inputStream) = 0; - virtual void writeToOutputStream(OutputStream& outputStream) const = 0; -}; - -struct SerializablePolymorphicStruct: SerializableStruct { - virtual uint32_t getSerialId() const = 0; - virtual void createTypeSignature(TypeOutputStream& typeOutputStream) const = 0; -}; - -} // namespace CommonAPI - -#endif // COMMONAPI_SERIALIZABLE_STRUCT_H_ diff --git a/src/CommonAPI/SerializableVariant.h b/src/CommonAPI/SerializableVariant.h deleted file mode 100644 index 78daee3..0000000 --- a/src/CommonAPI/SerializableVariant.h +++ /dev/null @@ -1,257 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_SERIALIZABLE_VARIANT_H_ -#define COMMONAPI_SERIALIZABLE_VARIANT_H_ - -#include <memory> -#include <cstdint> -#include <iostream> -#include <string> -#include <tuple> -#include <type_traits> -#include <cassert> - -namespace CommonAPI { - -class InputStream; -class OutputStream; - -class TypeOutputStream; - -template<typename _Type> -struct TypeWriter; - -/** - * \brief A variant class which can be serialised by bindings. - * - * A variant class which can be serialised by bindings. - */ -class SerializableVariant { -public: - virtual ~SerializableVariant() { - } - - virtual uint8_t getValueType() const = 0; - - virtual void readFromInputStream(const uint8_t typeIndex, InputStream& inputStream) = 0; - virtual void writeToOutputStream(OutputStream& outputStream) const = 0; - - virtual void writeToTypeOutputStream(TypeOutputStream& typeOutputStream) const = 0; -}; - -template<typename ... _Types> -struct MaxSize; - -template<> -struct MaxSize<> { - static const unsigned int value = 0; -}; - -template<typename _Type, typename ... _Types> -struct MaxSize<_Type, _Types...> { - static const unsigned int current_type_size = sizeof(_Type); - static const unsigned int next_type_size = MaxSize<_Types...>::value; - static const unsigned int value = - current_type_size > next_type_size ? - current_type_size : next_type_size; -}; - -template<typename _SearchType, typename ... _RestTypes> -struct VariantTypeSelector; - -template<typename _SearchType, typename ... _RestTypes> -struct VariantTypeSelector<_SearchType, _SearchType, _RestTypes...> { - typedef _SearchType type; -}; - -/** - * \brief A templated generic variant class which provides type safe access and operators - * - * A templated generic variant class which provides type safe access and operators - */ -template<typename ... _Types> -class Variant: public SerializableVariant { -private: - typedef std::tuple_size<std::tuple<_Types...>> TypesTupleSize; - -public: - - static const unsigned int maxSize = MaxSize<_Types...>::value; - - /** - * \brief Construct an empty variant - * - * Construct an empty variant - */ - Variant(); - - - /** - * \brief Copy constructor. Must have identical templates. - * - * Copy constructor. Must have identical templates. - * - * @param fromVariant Variant to copy - */ - Variant(const Variant& fromVariant); - - /** - * \brief Copy constructor. Must have identical templates. - * - * Copy constructor. Must have identical templates. - * - * @param fromVariant Variant to copy - */ - Variant(Variant&& fromVariant); - - ~Variant(); - - virtual void readFromInputStream(const uint8_t typeIndex, InputStream& inputStream); - - virtual void writeToOutputStream(OutputStream& outputStream) const; - - virtual void writeToTypeOutputStream(TypeOutputStream& typeOutputStream) const; - - /** - * \brief Assignment of another variant. Must have identical templates. - * - * Assignment of another variant. Must have identical templates. - * - * @param rhs Variant to assign - */ - Variant& operator=(const Variant& rhs); - /** - * \brief Assignment of another variant. Must have identical templates. - * - * Assignment of another variant. Must have identical templates. - * - * @param rhs Variant to assign - */ - Variant& operator=(Variant&& rhs); - - /** - * \brief Assignment of a contained type. Must be one of the valid templated types. - * - * Assignment of a contained type. Must be one of the valid templated types. - * - * @param value Value to assign - */ - template<typename _Type> - typename std::enable_if<!std::is_same<_Type, Variant<_Types...>>::value, Variant<_Types...>&>::type - operator=(const _Type& value); - - /** - * \brief Equality of another variant. Must have identical template list and content. - * - * Equality of another variant. Must have identical template list and content. - * - * @param rhs Variant to compare - */ - bool operator==(const Variant<_Types...>& rhs) const; - - /** - * \brief Not-Equality of another variant. Must have identical template list and content. - * - * Not-Equality of another variant. Must have identical template list and content. - * - * @param rhs Variant to compare - */ - bool operator!=(const Variant<_Types...>& rhs) const; - - /** - * \brief Testif the contained type is the same as the template on this method. - * - * Testif the contained type is the same as the template on this method. - * - * @return Is same type - */ - template <typename _Type> - const bool isType() const; - - /** - * \brief Construct variant with content type set to value. - * - * Construct variant with content type set to value. - * - * @param value Value to place - */ - template <typename _Type> - Variant(const _Type& value, - typename std::enable_if<!std::is_const<_Type>::value>::type* = 0, - typename std::enable_if<!std::is_reference<_Type>::value>::type* = 0, - typename std::enable_if<!std::is_same<_Type, Variant>::value>::type* = 0); - - /** - * \brief Construct variant with content type set to value. - * - * Construct variant with content type set to value. - * - * @param value Value to place - */ - template <typename _Type> - Variant(_Type && value, - typename std::enable_if<!std::is_const<_Type>::value>::type* = 0, - typename std::enable_if<!std::is_reference<_Type>::value>::type* = 0, - typename std::enable_if<!std::is_same<_Type, Variant>::value>::type* = 0); - - /** - * \brief Get value of variant, template to content type. Throws exception if type is not contained. - * - * Get value of variant, template to content type. Throws exception if type is not contained. - */ - template <typename _Type> - const _Type& get() const; - - /** - * \brief Get index in template list of type actually contained, starting at 1 at the end of the template list - * - * Get index in template list of type actually contained, starting at 1 at the end of the template list - * - * @return Index of contained type - */ - uint8_t getValueType() const { - return valueType_; - } - -private: - - template<typename _U> - void set( const _U& value, const bool clear); - - template<typename _U> - void set( _U&& value, const bool clear); - - template<typename _FriendType> - friend struct TypeWriter; - template<typename ... _FriendTypes> - friend struct AssignmentVisitor; - template<typename _FriendType> - friend struct TypeEqualsVisitor; - template<typename ... _FriendTypes> - friend struct PartialEqualsVisitor; - template<typename ... _FriendTypes> - friend struct InputStreamReadVisitor; - template<class Variant, typename ... _FTypes> - friend struct ApplyVoidIndexVisitor; - -protected: - inline bool hasValue() const { - return valueType_ < TypesTupleSize::value; - } - uint8_t valueType_; - typename std::aligned_storage<maxSize>::type valueStorage_; -}; -} // namespace CommonAPI - -#include "SerializableVariant.hpp" - -#endif // COMMONAPI_SERIALIZABLE_VARIANT_H_ diff --git a/src/CommonAPI/SerializableVariant.hpp b/src/CommonAPI/SerializableVariant.hpp deleted file mode 100644 index fe9a53d..0000000 --- a/src/CommonAPI/SerializableVariant.hpp +++ /dev/null @@ -1,522 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef COMMONAPI_SERIALIZABLE_VARIANT_IMPL_ -#define COMMONAPI_SERIALIZABLE_VARIANT_IMPL_ - -#include "OutputStream.h" -#include "InputStream.h" - -#include <exception> - - -namespace CommonAPI { - -template<class Variant, typename ... _Types> -struct ApplyVoidIndexVisitor; - -template<class Variant> -struct ApplyVoidIndexVisitor<Variant> { - static const uint8_t index = 0; - - static - void visit(Variant&, uint8_t&) { - //won't be called - assert(false); - } -}; - -template<class Variant, typename _Type, typename ... _Types> -struct ApplyVoidIndexVisitor<Variant, _Type, _Types...> { - static const uint8_t index = ApplyVoidIndexVisitor<Variant, - _Types...>::index + 1; - - static void visit(Variant& var, uint8_t& ind) { - if (ind == index) { - new (&var.valueStorage_) _Type(); - var.valueType_ = index; - } else { - ApplyVoidIndexVisitor<Variant, _Types...>::visit(var, ind); - } - } -}; - -template<class Visitor, class Variant, typename ... _Types> -struct ApplyVoidVisitor; - -template<class Visitor, class Variant> -struct ApplyVoidVisitor<Visitor, Variant> { - static const uint8_t index = 0; - - static - void visit(Visitor&, Variant&) { - //won't be called - assert(false); - } - - static - void visit(Visitor&, const Variant&) { - //won't be called - assert(false); - } -}; - -template<class Visitor, class Variant, typename _Type, typename ... _Types> -struct ApplyVoidVisitor<Visitor, Variant, _Type, _Types...> { - static const uint8_t index = ApplyVoidVisitor<Visitor, Variant, - _Types...>::index + 1; - - static void visit(Visitor& visitor, Variant& var) { - if (var.getValueType() == index) { - visitor(var.template get<_Type>()); - } else { - ApplyVoidVisitor<Visitor, Variant, _Types...>::visit(visitor, var); - } - } - - static void visit(Visitor& visitor, const Variant& var) { - if (var.getValueType() == index) { - visitor(var.template get<_Type>()); - } else { - ApplyVoidVisitor<Visitor, Variant, _Types...>::visit(visitor, var); - } - } -}; - -template<class Visitor, class Variant, typename ... _Types> -struct ApplyBoolVisitor -; - -template<class Visitor, class Variant> -struct ApplyBoolVisitor<Visitor, Variant> { - static const uint8_t index = 0; - - static bool visit(Visitor&, Variant&) { - //won't be called - assert(false); - return false; - } -}; - -template<class Visitor, class Variant, typename _Type, typename ... _Types> -struct ApplyBoolVisitor<Visitor, Variant, _Type, _Types...> { - static const uint8_t index = ApplyBoolVisitor<Visitor, Variant, - _Types...>::index + 1; - - static bool visit(Visitor& visitor, Variant& var) { - if (var.getValueType() == index) { - return visitor(var.template get<_Type>()); - } else { - return ApplyBoolVisitor<Visitor, Variant, _Types...>::visit(visitor, - var); - } - } -}; - -template<uint8_t size> -struct DeleteVisitor { -public: - DeleteVisitor(typename std::aligned_storage<size>::type& storage) : - storage_(storage) { - } - - template<typename _Type> - void operator()(const _Type&) const { - (reinterpret_cast<const _Type *>(&storage_))->~_Type(); - } - -private: - typename std::aligned_storage<size>::type& storage_; -}; - -struct TypeOutputStreamWriteVisitor { -public: - TypeOutputStreamWriteVisitor(TypeOutputStream& typeStream) : - typeStream_(typeStream) { - } - - template<typename _Type> - void operator()(const _Type&) const { - TypeWriter<_Type>::writeType(typeStream_); - } - -private: - TypeOutputStream& typeStream_; -}; - -struct OutputStreamWriteVisitor { -public: - OutputStreamWriteVisitor(OutputStream& outputStream) : - outputStream_(outputStream) { - } - - template<typename _Type> - void operator()(const _Type& value) const { - outputStream_ << value; - } - -private: - OutputStream& outputStream_; -}; - - -template<typename ... _Types> -struct InputStreamReadVisitor { -public: - InputStreamReadVisitor(Variant<_Types...>& lhs, InputStream& inputStream) : - lhs_(lhs), - inputStream_(inputStream) { - } - - template<typename _Type> - void operator()(const _Type&) { - _Type value; - inputStream_ >> value; -#ifdef WIN32 - lhs_.set<_Type>(std::move(value), false); -#else - lhs_.Variant<_Types...>::template set<_Type>(std::move(value), false); -#endif - } - -private: - Variant<_Types...>& lhs_; - InputStream& inputStream_; -}; - - -template<typename _Type> -struct TypeEqualsVisitor -{ -public: - TypeEqualsVisitor(const _Type& rhs): rhs_(rhs) { - } - - bool operator()(const _Type& lhs) const { - return lhs == rhs_; - } - - template<typename _U> - bool operator()(const _U&) const { - return false; - } - -private: - const _Type& rhs_; -}; - -template<typename ... _Types> -struct PartialEqualsVisitor -{ -public: - PartialEqualsVisitor(const Variant<_Types...>& lhs) : - lhs_(lhs) { - } - - template<typename _Type> - bool - operator()(const _Type& rhs) const - { - TypeEqualsVisitor<_Type> visitor(rhs); - return ApplyBoolVisitor<TypeEqualsVisitor<_Type>, const Variant<_Types...>, _Types...>::visit(visitor, lhs_); - } - -private: - const Variant<_Types...>& lhs_; -}; - -template<typename ... _Types> -struct AssignmentVisitor { -public: - AssignmentVisitor(Variant<_Types...>& lhs, const bool clear = true) : - lhs_(lhs), clear_(clear) { - } - - template<typename _Type> - void operator()(const _Type& value) const { -#ifdef WIN32 - lhs_.set<_Type>(value, clear_); -#else - lhs_.Variant<_Types...>::template set<_Type>(value, clear_); -#endif - } - - template<typename _Type> - void operator()(_Type& value) const { - lhs_.Variant<_Types...>::template set<_Type>(value, clear_); - } - -private: - Variant<_Types...>& lhs_; - const bool clear_; -}; - -template<typename ... _Types> -struct TypeSelector; - -template<typename _U> -struct TypeSelector<_U> { -}; - -//_U == _Type -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type, _Type, _Types...> { - typedef _Type type; -}; - -//_U& == _Type -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type, _Type&, _Types...> { - typedef _Type& type; -}; - -//_U == _Type& -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type&, _Type, _Types...> { - typedef _Type type; -}; - -//const _U& == _Type -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type, const _Type&, _Types...> { - typedef const _Type& type; -}; - -//_U == const _Type& -template<typename _Type, typename ... _Types> -struct TypeSelector<const _Type&, _Type, _Types...> { - typedef _Type type; -}; - -//_U == X* -//_Type == const X* -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type*, const _Type*, _Types...> { - typedef const _Type* type; -}; - -//_U == X& -//_Type == const X& -template<typename _Type, typename ... _Types> -struct TypeSelector<_Type&, const _Type&, _Types...> { - typedef const _Type& type; -}; - -//_U != _Type, let's try to find _U among _Types -template<typename _U, typename _Type, typename ... _Types> -struct TypeSelector<_U, _Type, _Types...> { - typedef typename TypeSelector<_U, _Types...>::type type; -}; - -template<typename ... _Types> -struct TypeIndex; - -template<> -struct TypeIndex<> { - static const uint8_t index = 0; - - template<typename _U> - static uint8_t get() { - return 0; - } -}; - -template<typename _Type, typename ... _Types> -struct TypeIndex<_Type, _Types...> { - static const uint8_t index = TypeIndex<_Types...>::index + 1; - - template<typename _U> - static uint8_t get( - typename std::enable_if<std::is_same<_Type, _U>::value>::type* = 0) { - return index; - } - - template<typename _U> - static uint8_t get(typename std::enable_if<!std::is_same<_Type, _U>::value>::type* = 0) { - return TypeIndex<_Types...>::template get<_U>(); - } -}; - -template<typename ... _Types> -Variant<_Types...>::Variant() : - valueType_(TypesTupleSize::value) { - ApplyVoidIndexVisitor<Variant<_Types...>, _Types...>::visit(*this, valueType_); -} - -template<typename ... _Types> -Variant<_Types...>::Variant(const Variant& fromVariant) { - AssignmentVisitor<_Types...> visitor(*this, false); - ApplyVoidVisitor<AssignmentVisitor<_Types...> , Variant<_Types...>, _Types...>::visit(visitor, fromVariant); -} - -template<typename ... _Types> -Variant<_Types...>::Variant(Variant&& fromVariant) -{ - AssignmentVisitor<_Types...> visitor(*this, false); - ApplyVoidVisitor<AssignmentVisitor<_Types...> , Variant<_Types...>, _Types...>::visit(visitor, fromVariant); -} - -/*template<typename ... _Types> -Variant<_Types...>::Variant(Variant&& fromVariant) : - valueType_(std::move(fromVariant.valueType_)), - valueStorage_(std::move(fromVariant.valueStorage_)) -{ -}*/ - -template<typename ... _Types> -Variant<_Types...>::~Variant() { - if (hasValue()) { - DeleteVisitor<maxSize> visitor(valueStorage_); - ApplyVoidVisitor<DeleteVisitor<maxSize>, Variant<_Types...>, _Types...>::visit(visitor, *this); - } -} - -template<typename ... _Types> -void Variant<_Types...>::readFromInputStream(const uint8_t typeIndex, InputStream& inputStream) { - if(hasValue()) { - DeleteVisitor<maxSize> visitor(valueStorage_); - ApplyVoidVisitor<DeleteVisitor<maxSize>, Variant<_Types...>, _Types...>::visit(visitor, *this); - } - valueType_ = typeIndex; - InputStreamReadVisitor<_Types...> visitor(*this, inputStream); - ApplyVoidVisitor<InputStreamReadVisitor<_Types...>, Variant<_Types...>, _Types...>::visit(visitor, *this); -} - -template<typename ... _Types> -void Variant<_Types...>::writeToOutputStream(OutputStream& outputStream) const { - OutputStreamWriteVisitor visitor(outputStream); - ApplyVoidVisitor<OutputStreamWriteVisitor, Variant<_Types...>, _Types...>::visit( - visitor, *this); -} - -template<typename ... _Types> -void Variant<_Types...>::writeToTypeOutputStream(TypeOutputStream& typeOutputStream) const { - TypeOutputStreamWriteVisitor visitor(typeOutputStream); - ApplyVoidVisitor<TypeOutputStreamWriteVisitor, Variant<_Types...>, _Types...>::visit( - visitor, *this); -} - -template<typename ... _Types> -Variant<_Types...>& Variant<_Types...>::operator=(const Variant<_Types...>& rhs) { - AssignmentVisitor<_Types...> visitor(*this, hasValue()); - ApplyVoidVisitor<AssignmentVisitor<_Types...>, Variant<_Types...>, _Types...>::visit( - visitor, rhs); - return *this; -} - -template<typename ... _Types> -Variant<_Types...>& Variant<_Types...>::operator=(Variant<_Types...>&& rhs) { - AssignmentVisitor<_Types...> visitor(*this, hasValue()); - ApplyVoidVisitor<AssignmentVisitor<_Types...>, Variant<_Types...>, _Types...>::visit(visitor, rhs); - return *this; -} - -template<typename ... _Types> -template<typename _Type> -typename std::enable_if<!std::is_same<_Type, Variant<_Types...>>::value, Variant<_Types...>&>::type -Variant<_Types...>::operator=(const _Type& value) { - set<typename TypeSelector<_Type, _Types...>::type>(value, hasValue()); - return *this; -} - -template<typename ... _Types> -template<typename _Type> -const bool Variant<_Types...>::isType() const { - typedef typename TypeSelector<_Type, _Types...>::type selected_type_t; - uint8_t cType = TypeIndex<_Types...>::template get<selected_type_t>(); - if (cType == valueType_) { - return true; - } else { - return false; - } -} - -template<typename ... _Types> -template<typename _Type> -Variant<_Types...>::Variant(const _Type& value, - typename std::enable_if<!std::is_const<_Type>::value>::type*, - typename std::enable_if<!std::is_reference<_Type>::value>::type*, - typename std::enable_if<!std::is_same<_Type, Variant<_Types...>>::value>::type*) { - set<typename TypeSelector<_Type, _Types...>::type>(value, false); -} - -template<typename ... _Types> -template<typename _Type> -Variant<_Types...>::Variant(_Type && value, -typename std::enable_if<!std::is_const<_Type>::value>::type*, -typename std::enable_if<!std::is_reference<_Type>::value>::type*, -typename std::enable_if<!std::is_same<_Type, Variant<_Types...>>::value>::type*) { - set<typename TypeSelector<_Type, _Types...>::type>(std::move(value), false); -} - - -template<typename ... _Types> -template<typename _Type> -const _Type & Variant<_Types...>::get() const { - typedef typename TypeSelector<_Type, _Types...>::type selected_type_t; - uint8_t cType = TypeIndex<_Types...>::template get<selected_type_t>(); - if (cType == valueType_) { - return *(reinterpret_cast<const _Type *>(&valueStorage_)); - } else { -#if defined(__EXCEPTIONS) || defined(WIN32) - std::bad_cast toThrow; - throw toThrow; -#else - printf("SerializableVariant.hpp:%i %s: Incorrect access to variant; attempting to get type not currently contained", __LINE__, __FUNCTION__); - abort(); -#endif - } -} - - -template<typename ... _Types> -template<typename _U> -void Variant<_Types...>::set(const _U& value, const bool clear) { - typedef typename TypeSelector<_U, _Types...>::type selected_type_t; - - if (clear) { - DeleteVisitor<maxSize> visitor(valueStorage_); - ApplyVoidVisitor<DeleteVisitor<maxSize>, Variant<_Types...>, _Types...>::visit(visitor, *this); - } - new (&valueStorage_) selected_type_t(std::move(value)); - valueType_ = TypeIndex<_Types...>::template get<selected_type_t>(); -} - -template<typename ... _Types> -template<typename _U> -void Variant<_Types...>::set(_U&& value, const bool clear) { - typedef typename TypeSelector<_U, _Types...>::type selected_type_t; - - selected_type_t&& any_container_value = std::move(value); - if(clear) - { - DeleteVisitor<maxSize> visitor(valueStorage_); - ApplyVoidVisitor<DeleteVisitor<maxSize>, Variant<_Types...>, _Types...>::visit(visitor, *this); - } else { - new (&valueStorage_) selected_type_t(std::move(any_container_value)); - } - - valueType_ = TypeIndex<_Types...>::template get<selected_type_t>(); -} - -template<typename ... _Types> -bool Variant<_Types...>::operator==(const Variant<_Types...>& rhs) const - { - PartialEqualsVisitor<_Types...> visitor(*this); - return ApplyBoolVisitor<PartialEqualsVisitor<_Types...>, const Variant<_Types...>, _Types...>::visit( - visitor, - rhs); -} - -template<typename ... _Types> -bool Variant<_Types...>::operator!=(const Variant<_Types...>& rhs) const - { - return !(*this == rhs); -} - -} - -#endif //COMMONAPI_SERIALIZABLE_VARIANT_IMPL_ diff --git a/src/CommonAPI/ServicePublisher.cpp b/src/CommonAPI/ServicePublisher.cpp deleted file mode 100644 index dc89b2b..0000000 --- a/src/CommonAPI/ServicePublisher.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#include "ServicePublisher.h" -#include "Stub.h" -#include "Factory.h" - -namespace CommonAPI { - -bool ServicePublisher::registerService(const std::shared_ptr<StubBase>& stubBase, - const char* interfaceId, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain, - const std::shared_ptr<Factory>& factory) { - return factory->registerAdapter(stubBase, interfaceId, participantId, serviceName, domain); -} - -} // namespace CommonAPI diff --git a/src/CommonAPI/ServicePublisher.h b/src/CommonAPI/ServicePublisher.h deleted file mode 100644 index 3dd6a65..0000000 --- a/src/CommonAPI/ServicePublisher.h +++ /dev/null @@ -1,140 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_SERVICE_PUBLISHER_H_ -#define COMMONAPI_SERVICE_PUBLISHER_H_ - -#include <memory> -#include <string> - -namespace CommonAPI { - -class StubBase; -class Factory; - -/** - * \brief Manages all services that shall be published by the application. - * - * Stubs for all services that shall be published will be registered here. - * This class is defined as singleton per loaded runtime (i.e. per loaded middleware). - */ -class ServicePublisher { - public: - virtual ~ServicePublisher() {} - - /** - * \brief Registers and publishes a service. - * - * Registers and publishes a service. Which service is to be published is defined - * by the stub-pointer that is given as parameter. The given factory will be used - * to construct all necessary middleware specific objects to do the publishing. - * - * \note Note that a call to this method will always result in a registration - * with the middleware the given factory was instantiated for, not the middleware - * that matches the runtime this ServicePublisher was retrieved from. Accordingly, - * unregistering the service will have to be done by using the ServicePublisher - * that is provided by the runtime matching the middleware that also provided - * the given factory. - * - * @param serviceAddress The CommonAPI address the service shall be reachable at - * @param stub The stub that provides an implementation for the service - * @param factory The factory that will be used to construct all necessary middleware specific objects - * - * @return 'true' if the service was published successfully, 'false' if not or if another service that uses - * the exact same address already is registered. - */ - template<typename _Stub> - bool registerService(std::shared_ptr<_Stub> stub, - const std::string& serviceAddress, - std::shared_ptr<Factory> factory); - - /** - * \brief Registers and publishes a service. - * - * Registers and publishes a service. Which service is to be published is defined - * by the stub-pointer that is given as parameter. The given factory will be used - * to construct all necessary middleware specific objects to do the publishing. - * - * \note Note that a call to this method will always result in a registration - * with the middleware the given factory was instantiated for, not the middleware - * that matches the runtime this ServicePublisher was retrieved from. Accordingly, - * unregistering the service will have to be done by using the ServicePublisher - * that is provided by the runtime matching the middleware that also provided - * the given factory. - * - * @param participantId The CommonAPI participant ID the service shall be identified with - * @param serviceName The CommonAPI service name the service shall provide - * @param domain The CommonAPI domain the service shall be reachable at - * @param stub The stub that provides an implementation for the service - * @param factory The factory that will be used to construct all necessary middleware specific objects - * - * @return 'true' if the service was published successfully, 'false' if not or if another service that uses - * the exact same address already is registered. - */ - template<typename _Stub> - bool registerService(std::shared_ptr<_Stub> stub, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain, - std::shared_ptr<Factory> factory); - - /** - * \brief Unregisters and depublishes the service that was published for the given address. - * - * Unregisters and depublishes the service that was published for the given CommonAPI address. - * - * @param The CommonAPI address the service was registered for - * - * @return 'true' if there was a service for the given address and depublishing - * was successful, 'false' otherwise - */ - virtual bool unregisterService(const std::string& serviceAddress) = 0; - - /** - * \brief Unregisters and depublishes the service that was published for the given address. - * - * Unregisters and depublishes the service that was published for the given CommonAPI address. - * - * @param The CommonAPI participant ID the service was identified with - * @param The CommonAPI service name the service provided - * @param The CommonAPI domain the service was registered for - * - * @return 'true' if there was a service for the given address and depublishing - * was successful, 'false' otherwise - */ - bool unregisterService(const std::string& participantId, - const std::string& serviceName, - const std::string& domain) { - std::string serviceAddress(participantId + ":" + serviceName + ":" + domain); - return unregisterService(serviceAddress); - } - - protected: - /** - * Register stubBase service within a factory. - * - * This is a new API which deprecates the old Factory::registerAdapter() method. - * For compatibility reasons a default implementation is provided. New middleware - * implementations should override this method. - */ - virtual bool registerService(const std::shared_ptr<StubBase>& stubBase, - const char* interfaceId, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain, - const std::shared_ptr<Factory>& factory); -}; - -} // namespace CommonAPI - -#include "ServicePublisher.hpp" - -#endif /* COMMONAPI_SERVICE_PUBLISHER_H_ */ diff --git a/src/CommonAPI/ServicePublisher.hpp b/src/CommonAPI/ServicePublisher.hpp deleted file mode 100644 index bab75ed..0000000 --- a/src/CommonAPI/ServicePublisher.hpp +++ /dev/null @@ -1,43 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#ifndef COMMONAPI_SERVICE_PUBLISHER_IMPL_H_ -#define COMMONAPI_SERVICE_PUBLISHER_IMPL_H_ - -#include "Factory.h" - -namespace CommonAPI { - -template<typename _Stub> -bool ServicePublisher::registerService(std::shared_ptr<_Stub> stub, - const std::string& participantId, - const std::string& serviceName, - const std::string& domain, - std::shared_ptr<Factory> factory) { - - std::shared_ptr<StubBase> stubBase = std::dynamic_pointer_cast<StubBase>(stub); - return registerService(stubBase, _Stub::StubInterface::getInterfaceId(), participantId, serviceName, domain, factory); -} - -template<typename _Stub> -bool ServicePublisher::registerService(std::shared_ptr<_Stub> stub, - const std::string& serviceAddress, - std::shared_ptr<Factory> factory) { - std::string domain; - std::string serviceName; - std::string participantId; - if(!factory->splitValidAddress(serviceAddress, domain, serviceName, participantId)) { - return false; - } - - return registerService<_Stub>(stub, participantId, serviceName, domain, factory); -} - -} // namespace CommonAPI - - -#endif /* COMMONAPI_SERVICE_PUBLISHER_IMPL_H_ */ diff --git a/src/CommonAPI/Stub.h b/src/CommonAPI/Stub.h deleted file mode 100644 index a22ae3c..0000000 --- a/src/CommonAPI/Stub.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_STUB_H_ -#define COMMONAPI_STUB_H_ - -#include <memory> -#include <string> -#include <type_traits> - -namespace CommonAPI { - -class StubAdapter { -public: - virtual ~StubAdapter() { - } - - virtual const std::string getAddress() const = 0; - virtual const std::string& getDomain() const = 0; - virtual const std::string& getServiceId() const = 0; - virtual const std::string& getInstanceId() const = 0; -}; - -class StubBase { -public: - virtual ~StubBase() { - } -}; - -template<typename _StubAdapter, typename _StubRemoteEventHandler> -class Stub: public virtual StubBase { - static_assert(std::is_base_of<StubAdapter, _StubAdapter>::value, "Invalid StubAdapter Class!"); -public: - typedef _StubAdapter StubAdapterType; - typedef _StubRemoteEventHandler RemoteEventHandlerType; - - virtual ~Stub() { - } - - virtual _StubRemoteEventHandler* initStubAdapter(const std::shared_ptr<_StubAdapter>& stubAdapter) = 0; - virtual const std::shared_ptr<_StubAdapter> getStubAdapter() { - return stubAdapter_; - } - -protected: - std::shared_ptr<_StubAdapter> stubAdapter_; -}; - -enum SelectiveBroadcastSubscriptionEvent { - SUBSCRIBED, - UNSUBSCRIBED -}; - -} // namespace CommonAPI - -#endif // COMMONAPI_STUB_H_ diff --git a/src/CommonAPI/Utils.cpp b/src/CommonAPI/Utils.cpp new file mode 100644 index 0000000..2540a86 --- /dev/null +++ b/src/CommonAPI/Utils.cpp @@ -0,0 +1,47 @@ +// Copyright (C) 2014-2015 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at http://mozilla.org/MPL/2.0/. + +#include <algorithm> +#include <sstream> +#include <functional> + +#include <CommonAPI/Utils.hpp> + +namespace CommonAPI { + +std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems) { + std::istringstream ss(s); + std::string item; + while (std::getline(ss, item, delim)) { + elems.push_back(item); + } + return elems; +} + +std::vector<std::string> split(const std::string& s, char delim) { + std::vector<std::string> elems; + return split(s, delim, elems); +} + +void trim(std::string& toTrim) { + toTrim.erase( + toTrim.begin(), + std::find_if( + toTrim.begin(), + toTrim.end(), + std::not1(std::ptr_fun(isspace)) + ) + ); + + toTrim.erase( + std::find_if( + toTrim.rbegin(), + toTrim.rend(), + std::not1(std::ptr_fun(isspace))).base(), + toTrim.end() + ); +} + +}//namespace CommonAPI diff --git a/src/CommonAPI/types.h b/src/CommonAPI/types.h deleted file mode 100644 index eb2aaf8..0000000 --- a/src/CommonAPI/types.h +++ /dev/null @@ -1,116 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#if !defined (COMMONAPI_INTERNAL_COMPILATION) -#error "Only <CommonAPI/CommonAPI.h> can be included directly, this file may disappear or change contents." -#endif - -#ifndef COMMONAPI_TYPES_H_ -#define COMMONAPI_TYPES_H_ - -#include <cstdint> -#include <functional> -#include <unordered_set> -#include <memory> -#include <tuple> -#include "ContainerUtils.h" -#include "Event.h" - -#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) -# define COMMONAPI_DEPRECATED __attribute__ ((__deprecated__)) -#elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# define COMMONAPI_DEPRECATED __declspec(deprecated) -#else -# define COMMONAPI_DEPRECATED -#endif - - -#ifdef WIN32 -#define CCALL __cdecl -#pragma section(".CRT$XCU",read) -#define INITIALIZER(f) \ - static void __cdecl f(void); \ - __declspec(allocate(".CRT$XCU")) void(__cdecl*f##_)(void) = f; \ - static void __cdecl f(void) -#else -#define CCALL -#define INITIALIZER(f) \ - static void f(void) __attribute__((constructor)); \ - static void f(void) -#endif - -#ifdef WIN32 -#define usleep(micSec) \ - std::this_thread::sleep_for(std::chrono::microseconds(micSec)) -#endif - -namespace CommonAPI { - -enum class AvailabilityStatus { - UNKNOWN, - AVAILABLE, - NOT_AVAILABLE -}; - -enum class CallStatus { - SUCCESS, - OUT_OF_MEMORY, - NOT_AVAILABLE, - CONNECTION_FAILED, - REMOTE_ERROR -}; - - -struct Version { - Version() = default; - - Version(const uint32_t& majorValue, const uint32_t& minorValue): - Major(majorValue), - Minor(minorValue) {} - - uint32_t Major; - uint32_t Minor; -}; - -/** - * \brief Identifies a client sending a call to a stub. - * - * The ClientId is used to identify the caller within a stub. - * The ClientId is supposed to be added by the middleware and can be compared using the == operator. - */ -class ClientId { -public: - virtual ~ClientId() { } - virtual bool operator==(ClientId& clientIdToCompare) = 0; - virtual std::size_t hashCode() = 0; -}; - -template <typename ... Args> -struct SelectiveBroadcastFunctorHelper { - typedef std::function<SubscriptionStatus(Args...)> SelectiveBroadcastFunctor; -}; - - -typedef std::unordered_set<std::shared_ptr<CommonAPI::ClientId>, SharedPointerClientIdContentHash, SharedPointerClientIdContentEqual> ClientIdList; -template <typename ... Args> -struct SelectiveBroadcastSubscriptionResult { - typedef std::tuple<bool, typename CommonAPI::Event<Args...>::Subscription> SubscriptionResult; - -}; - -template<typename _EnumType> -class EnumHasher { -public: - size_t operator()(const _EnumType& testEnum) const { - return static_cast<int32_t>(testEnum); - } - -}; - -} // namespace CommonAPI - -#endif // COMMONAPI_TYPES_H_ diff --git a/src/CommonAPI/utils.cpp b/src/CommonAPI/utils.cpp deleted file mode 100644 index 303c32a..0000000 --- a/src/CommonAPI/utils.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -#include "utils.h" - -namespace CommonAPI { -std::string getCurrentBinaryFileFQN() { - #ifdef WIN32 - TCHAR result[MAX_PATH]; - std::basic_string<TCHAR> resultString(result, GetModuleFileName(NULL, result, MAX_PATH)); - return std::string(resultString.begin(), resultString.end()); - #else - char fqnOfBinary[FILENAME_MAX]; - char pathToProcessImage[FILENAME_MAX]; - - sprintf(pathToProcessImage, "/proc/%d/exe", getpid()); - const ssize_t lengthOfFqn = readlink(pathToProcessImage, fqnOfBinary, sizeof(fqnOfBinary) - 1); - - if (lengthOfFqn != -1) { - fqnOfBinary[lengthOfFqn] = '\0'; - return std::string(std::move(fqnOfBinary)); - } - else { - return std::string(""); - } - #endif - } - -std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems) { - std::istringstream ss(s); - std::string item; - while (std::getline(ss, item, delim)) { - elems.push_back(item); - } - return elems; -} - -std::vector<std::string> split(const std::string& s, char delim) { - std::vector<std::string> elems; - return split(s, delim, elems); -} - -void trim(std::string& toTrim) { - toTrim.erase( - toTrim.begin(), - std::find_if(toTrim.begin(), - toTrim.end(), - std::not1(std::ptr_fun(isspace))) - ); - toTrim.erase( - std::find_if(toTrim.rbegin(), - toTrim.rend(), - std::not1(std::ptr_fun(isspace))).base(), - toTrim.end() - ); -} - -bool notIsdigit(char c) { - return !std::isdigit(c, std::locale()); -} - -bool containsOnlyDigits(const std::string& toCheck) { - auto firstNonDigitIt = std::find_if( - toCheck.begin(), - toCheck.end(), - notIsdigit); - - return firstNonDigitIt == toCheck.end(); -} - -bool notIsalnum(char c) { - return !std::isalnum(c, std::locale()); -} - -bool containsOnlyAlphanumericCharacters(const std::string& toCheck) { - auto firstNonAlphanumericCharacterIt = std::find_if( - toCheck.begin(), - toCheck.end(), - notIsalnum); - - return firstNonAlphanumericCharacterIt == toCheck.end(); -} - -bool isValidDomainName(const std::string& domainName) { - return containsOnlyAlphanumericCharacters(domainName); -} - -bool isValidServiceName(const std::string& serviceName) { - bool isValid = serviceName[0] != '.' && serviceName[serviceName.size() - 1] != '.'; - - if (isValid) { - std::vector<std::string> splittedServiceName = split(serviceName, '.'); - - for (auto serviceNameElementIt = splittedServiceName.begin(); - serviceNameElementIt != splittedServiceName.end() && isValid; - ++serviceNameElementIt) { - isValid &= containsOnlyAlphanumericCharacters(*serviceNameElementIt); - } - } - - return isValid; -} - -bool isValidInstanceId(const std::string& instanceId) { - //Validation rules for ServiceName and InstanceID are equivalent - return isValidServiceName(instanceId); -} - -bool isValidCommonApiAddress(const std::string& commonApiAddress) { - std::vector<std::string> splittedAddress = split(commonApiAddress, ':'); - if (splittedAddress.size() != 3) { - return false; - } - return isValidDomainName(splittedAddress[0]) && isValidServiceName(splittedAddress[1]) && isValidInstanceId(splittedAddress[2]); -} - -#ifndef WIN32 -bool loadGenericLibrary(const std::string& wellKnownMiddlewareName, const std::string& libraryName, const std::string& path, bool checkStandardNamePattern) { - std::string fqnOfLibrary = path + libraryName; - struct stat filestat; - if (stat(fqnOfLibrary.c_str(), &filestat)) { - return false; - } - if (S_ISDIR(filestat.st_mode)) { - return false; - } - - if (checkStandardNamePattern) { - const std::string generatedLibPrefix = "lib" + wellKnownMiddlewareName + "Gen-"; - if (strncmp(generatedLibPrefix.c_str(), libraryName.c_str(), generatedLibPrefix.length()) != 0) { - return false; - } - - const char* fileNamePtr = libraryName.c_str(); - while ((fileNamePtr = strchr(fileNamePtr + 1, '.'))) { - if (strncmp(".so\0", fileNamePtr, 4) == 0 || strncmp(".so.", fileNamePtr, 4) == 0) { - break; - } - } - - if (!fileNamePtr) { - return false; - } - } - - dlopen(fqnOfLibrary.c_str(), RTLD_NOW | RTLD_GLOBAL); - return true; -} - -bool loadGenericLibrary(const std::string& wellKnownMiddlewareName, - const std::string& fqnOfLibrary, - bool checkStandardNamePattern) { - uint32_t position = fqnOfLibrary.find_last_of("/\\"); - std::string path = fqnOfLibrary.substr(0, position + 1); - std::string file = fqnOfLibrary.substr(position + 1); - return loadGenericLibrary(wellKnownMiddlewareName, file, path, checkStandardNamePattern); -} - -void findAndLoadGenericLibraries(const std::string& requestedMiddlewareName, const std::string& singleSearchPath) { - DIR *directory = opendir(singleSearchPath.c_str()); - - if (directory != NULL) { - struct dirent* entry; - - while ((entry = readdir(directory))) { - loadGenericLibrary(requestedMiddlewareName, entry->d_name, singleSearchPath, true); - } - } -} - -void findAndLoadGenericLibraries(const std::string& requestedMiddlewareName, const std::vector<std::string>& searchPaths) { - for (const std::string& singleSearchPath : searchPaths) { - findAndLoadGenericLibraries(requestedMiddlewareName, singleSearchPath.c_str()); - } -} -#endif -}//namespace CommonAPI diff --git a/src/CommonAPI/utils.h b/src/CommonAPI/utils.h deleted file mode 100644 index c0e78eb..0000000 --- a/src/CommonAPI/utils.h +++ /dev/null @@ -1,230 +0,0 @@ -/* Copyright (C) 2013 BMW Group - * Author: Manfred Bathelt (manfred.bathelt@bmw.de) - * Author: Juergen Gehring (juergen.gehring@bmw.de) - * This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -#ifndef COMMONAPI_UTILS_H_ -#define COMMONAPI_UTILS_H_ - -#ifndef WIN32 -#include <dirent.h> -#include <dlfcn.h> -#endif -#include <sys/stat.h> - -#include <cstring> -#include <string> -#include <sstream> -#include <vector> -#include <algorithm> -#include <iostream> - -#include <locale> -#include <functional> - -#ifdef WIN32 -#include <xfunctional> -#define WIN32_LEAN_AND_MEAN // this prevents windows.h from including winsock.h, which causes duplicate definitions with winsock2.h -#include <windows.h> -#else -#include <unistd.h> -#endif - -namespace CommonAPI { - - -#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1) -# define COMMONAPI_DEPRECATED __attribute__ ((__deprecated__)) -#elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# define COMMONAPI_DEPRECATED __declspec(deprecated) -#else -# define COMMONAPI_DEPRECATED -#endif - - -/** - * \brief Returns the fully qualified name of the binary. - * - * @return The name of the currently executing binary. - */ -std::string getCurrentBinaryFileFQN(); - -/** - * \brief Splits a std::string according to the given delim-char. - * - * The string will be splitted at each position the delim char is encountered. The delim itself - * will be removed from the result. - * - * @param s: The string that is to be splitted - * @param delim: The character that separates the resulting string tokens in the original string - * @param elems: Reference to the vector that shall be filled with the splitted string elements. - * - * @return A reference to the vector you passed in (elems) - */ -std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems); - -/** - * \brief Splits a std::string according to the given delim-char. - * - * The string will be splitted at each position the delim char is encountered. The delim itself - * will be removed from the result. - * - * @param s: The string that is to be splitted - * @param delim: The character that separates the resulting string tokens in the original string - * - * @return A vector containing the splitted string elements. - */ -std::vector<std::string> split(const std::string& s, char delim); - -inline bool isspace(char c) { - return std::isspace(c, std::locale()); -} - -/** - * \brief Trims whitespaces from beginning and end of a std::string. - * - * @param toTrim: The string that is to be trimmed. - */ -void trim(std::string& toTrim); - -bool notIsdigit(char c); - -/** - * \brief Checks whether the given string contains nothing but digits. - * - * @param toCheck: The string that is to be checked on the presence of anything but digits. - * - * @return true if toCheck contains nothing but digits, false otherwise. - */ -bool containsOnlyDigits(const std::string& toCheck); - -bool notIsalnum(char c); - -/** - * \brief Checks whether the given string contains nothing but alphanumeric characters. - * - * @param toCheck: The string that is to be checked on the presence of anything but alphanumeric characters. - * - * @return true if toCheck contains nothing but alphanumeric characters, false otherwise. - */ -bool containsOnlyAlphanumericCharacters(const std::string& toCheck); - -/** - * \brief Checks whether the given std::string is a valid CommonAPI domain name. - * - * @param domainName: The std::string that is to be checked. - * - * @return true if domainName is a valid CommonAPI domainName, false otherwise. - */ -bool isValidDomainName(const std::string& domainName); - -/** - * \brief Checks whether the given std::string is a valid CommonAPI service name. - * - * @param serviceName: The std::string that is to be checked. - * - * @return true if serviceName is a valid CommonAPI serviceName, false otherwise. - */ -bool isValidServiceName(const std::string& serviceName); - -/** - * \brief Checks whether the given std::string is a valid CommonAPI instance ID. - * - * @param instanceId: The std::string that is to be checked. - * - * @return true if instanceId is a valid CommonAPI instance ID, false otherwise. - */ -bool isValidInstanceId(const std::string& instanceId); - -/** - * \brief Checks whether the given std::string is a valid CommonAPI address. - * - * @param commonApiAddressName: The std::string that is to be checked. - * - * @return true if commonApiAddress is a valid CommonAPI address, false otherwise. - */ -bool isValidCommonApiAddress(const std::string& commonApiAddress); - -#ifndef WIN32 -/** - * \brief Loads a specific generic library at runtime. - * - * The library will be loaded using dlopen(3) with the flags (RTLD_NOW | RTLD_GLOBAL), if all pre-checks are - * successful. Pre-checks include the verification that the given parameters actually point to a library and - * optionally if the library matches the standard name pattern for CommonAPI generic libraries. The standard - * name pattern is "lib<wellKnownMiddlewareName>Gen-<arbitraryName>.so[.major[.minor.revision]]". - * - * @param wellKnownMiddlewareName: The name of the middleware that requests the loading of the library. - * @param libraryName: The name of the library that shall be loaded. - * @param path: The path at which the library is to be found. path + library name together make up the fully - * qualified name of the library. - * @param checkStandardNamePattern: If set to true, it will be ensured the library matches the CommonAPI - * standard name pattern for generic libraries. This is meant as a safety measure - * to prevent the loading of unnecessary or the wrong libraries. Set to false if - * you are sure about what you are doing. - * @return true if the library could be loaded successfully, false otherwise. - * - * @note The well known middleware name is included as a parameter because the additional libraries normally are needed - * only by specific middlewares. This name however will only be taken into consideration during name checking - * if the checkStandardNamePattern flag is set to true. - */ -bool loadGenericLibrary(const std::string& wellKnownMiddlewareName, const std::string& libraryName, const std::string& path, bool checkStandardNamePattern = true); - -/** - * \brief Loads a specific generic library at runtime. - * - * The library will be loaded using dlopen(3) with the flags (RTLD_NOW | RTLD_GLOBAL), if all pre-checks are - * successful. Pre-checks include the verification that the given parameters actually point to a library and - * optionally if the library matches the standard name pattern for CommonAPI generic libraries. The standard - * name pattern is "lib<wellKnownMiddlewareName>Gen-<arbitraryName>.so[.major[.minor.revision]]". - * - * @param wellKnownMiddlewareName: The name of the middleware that requests the loading of the library. - * @param fqnOfLibrary: The fully qualified name of the library. - * @param checkStandardNamePattern: If set to true, it will be ensured the library matches the CommonAPI - * standard name pattern for generic libraries. This is meant as a safety measure - * to prevent the loading of unnecessary or the wrong libraries. Set to false if - * you are sure about what you are doing. - * @return true if the library could be loaded successfully, false otherwise. - * - * @note The well known middleware name is included as a parameter because the additional libraries normally are needed - * only by specific middlewares. This name however will only be taken into consideration during name checking - * if the checkStandardNamePattern flag is set to true. - */ -bool loadGenericLibrary(const std::string& wellKnownMiddlewareName, - const std::string& fqnOfLibrary, - bool checkStandardNamePattern = true); - -/** - * \brief Searches the given path for additional generic CommonAPI libraries and loads them. - * - * All libraries for which the pre-checks are successful will be loaded using dlopen(3) with the flags - * (RTLD_NOW | RTLD_GLOBAL). Pre-checks include the verification that the given parameters actually point - * to a library and if the library matches the standard name pattern for CommonAPI generic libraries. - * The standard name pattern is "lib<wellKnownMiddlewareName>Gen-<arbitraryName>.so[.major[.minor.revision]]". - * - * @param wellKnownMiddlewareName: The name of the middleware that requests the loading of the library. Will - * be used to perform the name check. - * @param singleSearchPath: The directory that is to be searched for libraries. - */ -void findAndLoadGenericLibraries(const std::string& requestedMiddlewareName, const std::string& singleSearchPath); - -/** - * \brief Searches the given paths for additional generic CommonAPI libraries and loads them. - * - * All libraries for which the pre-checks are successful will be loaded using dlopen(3) with the flags - * (RTLD_NOW | RTLD_GLOBAL). Pre-checks include the verification that the given parameters actually point - * to a library and if the library matches the standard name pattern for CommonAPI generic libraries. - * The standard name pattern is "lib<wellKnownMiddlewareName>Gen-<arbitraryName>.so[.major[.minor.revision]]". - * - * @param wellKnownMiddlewareName: The name of the middleware that requests the loading of the library. Will - * be used to perform the name check. - * @param searchPaths: The directories that are to be searched for libraries. - */ -void findAndLoadGenericLibraries(const std::string& requestedMiddlewareName, const std::vector<std::string>& searchPaths); -#endif - -} //namespace CommonAPI - - -#endif /* COMMONAPI_UTILS_H_ */ |