cppmicroservices-framework - Man Page

CppMicroServices Framework API

Main

These classes are the main API to the C++ Micro Services Framework:

Bundle

std::ostream &operator<<(std::ostream &os, Bundle const &bundle)

Streams a textual representation of bundle into the stream os.

std::ostream &operator<<(std::ostream &os, Bundle const *bundle)

This is the same as calling os << *bundle.

std::ostream &operator<<(std::ostream &os, Bundle::State state)

Streams a textual representation of the bundle state enumeration.

class Bundle

#include <cppmicroservices/Bundle.h>

An installed bundle in the Framework.

A Bundle object is the access point to define the lifecycle of an installed bundle. Each bundle installed in the CppMicroServices environment has an associated Bundle object.

A bundle has a unique identity, a long, chosen by the Framework. This identity does not change during the lifecycle of a bundle. Uninstalling and then reinstalling the bundle creates a new unique identity.

A bundle can be in one of six states:.INDENT 7.0

·

STATE_UNINSTALLED

·

STATE_INSTALLED

·

STATE_RESOLVED

·

STATE_STARTING

·

STATE_STOPPING

·

STATE_ACTIVE

Values assigned to these states have no specified ordering; they represent bit values that may be ORed together to determine if a bundle is in one of the valid states.

A bundle should only have active threads of execution when its state is one of STATE_STARTING,STATE_ACTIVE, or STATE_STOPPING. A STATE_UNINSTALLED bundle can not be set to another state; it is a zombie and can only be reached because references are kept somewhere.

The framework is the only entity that is allowed to create Bundle objects, and these objects are only valid within the Framework that created them.

Bundles have a natural ordering such that if two Bundles have the same bundle id they are equal. A Bundle is less than another Bundle if it has a lower bundle id and is greater if it has a higher bundle id.

Remark

This class is thread safe.

Subclassed by cppmicroservices::Framework

Public Types

enum State

The bundle state.

Values:

enumerator STATE_UNINSTALLED

The bundle is uninstalled and may not be used.

The STATE_UNINSTALLED state is only visible after a bundle is uninstalled; the bundle is in an unusable state but references to the Bundle object may still be available and used for introspection.

The value of STATE_UNINSTALLED is 0x00000001.

enumerator STATE_INSTALLED

The bundle is installed but not yet resolved.

A bundle is in the STATE_INSTALLED state when it has been installed in the Framework but is not or cannot be resolved.

This state is visible if the bundle's code dependencies are not resolved. The Framework may attempt to resolve a STATE_INSTALLED bundle's code dependencies and move the bundle to the STATE_RESOLVED state.

The value of STATE_INSTALLED is 0x00000002.

enumerator STATE_RESOLVED

The bundle is resolved and is able to be started.

A bundle is in the STATE_RESOLVED state when the Framework has successfully resolved the bundle's code dependencies. These dependencies include:.INDENT 7.0

·

None (this may change in future versions)

Note that the bundle is not active yet. A bundle is put in the STATE_RESOLVED state before it can be started. The Framework may attempt to resolve a bundle at any time.

The value of STATE_RESOLVED is 0x00000004.

enumerator STATE_STARTING

The bundle is in the process of starting.

A bundle is in the STATE_STARTING state when its Start method is active. A bundle must be in this state when the bundle's BundleActivator::Start(BundleContext) is called. If the BundleActivator::Start method completes without exception, then the bundle has successfully started and moves to the STATE_ACTIVE state.

If the bundle has a lazy activation policy, then the bundle may remain in this state for some time until the activation is triggered.

The value of STATE_STARTING is 0x00000008.

enumerator STATE_STOPPING

The bundle is in the process of stopping.

A bundle is in the STATE_STOPPING state when its Stop method is active. A bundle is in this state when the bundle's BundleActivator#Stop(BundleContext) method is called. When the BundleActivator::Stop method completes the bundle is stopped and moves to the STATE_RESOLVED state.

The value of STATE_STOPPING is 0x00000010.

enumerator STATE_ACTIVE

The bundle is now running.

A bundle is in the STATE_ACTIVE state when it has been successfully started and activated.

The value of STATE_ACTIVE is 0x00000020.

enum StartOptions

Values:

enumerator START_TRANSIENT

The bundle start operation is transient and the persistent autostart setting of the bundle is not modified.

This bit may be set when calling Start(uint32_t) to notify the framework that the autostart setting of the bundle must not be modified. If this bit is not set, then the autostart setting of the bundle is modified.

SEE ALSO:

Start(uint32_t)

NOTE:

This option is reserved for future use and not supported yet.

enumerator START_ACTIVATION_POLICY

The bundle start operation must activate the bundle according to the bundle's declared activation policy.

This bit may be set when calling Start(uint32_t) to notify the framework that the bundle must be activated using the bundle's declared activation policy.

SEE ALSO:

Constants::BUNDLE_ACTIVATIONPOLICY

SEE ALSO:

Start(uint32_t)

NOTE:

This option is reserved for future use and not supported yet.

enum StopOptions

Values:

enumerator STOP_TRANSIENT

The bundle stop is transient and the persistent autostart setting of the bundle is not modified.

This bit may be set when calling Stop(uint32_t) to notify the framework that the autostart setting of the bundle must not be modified. If this bit is not set, then the autostart setting of the bundle is modified.

SEE ALSO:

Stop(uint32_t)

NOTE:

This option is reserved for future use and not supported yet.

using TimeStamp = std::chrono::steady_clock::time_point

Public Functions

Bundle(Bundle const&)

Bundle(Bundle&&) noexcept

Bundle &operator=(Bundle const&)

Bundle &operator=(Bundle&&) noexcept

Bundle()

Constructs an invalid Bundle object.

Valid bundle objects can only be created by the framework in response to certain calls to a BundleContext object. A BundleContext object is supplied to a bundle via its BundleActivator or as a return value of the GetBundleContext() method.

SEE ALSO:

operator bool() const

virtual ~Bundle()

bool operator==(Bundle const &rhs) const

Compares this Bundle object with the specified bundle.

Valid Bundle objects compare equal if and only if they are installed in the same framework instance and their bundle id is equal. Invalid Bundle objects are always considered to be equal.

Parameters

rhs -- The Bundle object to compare this object with.

Returns

true if this Bundle object is equal to rhs, false otherwise.

bool operator!=(Bundle const &rhs) const

Compares this Bundle object with the specified bundle for inequality.

Parameters

rhs -- The Bundle object to compare this object with.

Returns

Returns the result of !(*this == rhs).

bool operator<(Bundle const &rhs) const

Compares this Bundle with the specified bundle for order.

Bundle objects are ordered first by their framework id and then according to their bundle id. Invalid Bundle objects will always compare greater then valid Bundle objects.

Parameters

rhs -- The Bundle object to compare this object with.

Returns

explicit operator bool() const

Tests this Bundle object for validity.

Invalid Bundle objects are created by the default constructor or can be returned by certain framework methods if the bundle has been uninstalled.

Returns

true if this Bundle object is valid and can safely be used, false otherwise.

Bundle &operator=(std::nullptr_t)

Releases any resources held or locked by this Bundle and renders it invalid.

State GetState() const

Returns this bundle's current state.

A bundle can be in only one state at any time.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

An element of STATE_UNINSTALLED,STATE_INSTALLED, STATE_RESOLVED, STATE_STARTING, STATE_STOPPING, STATE_ACTIVE.

BundleContext GetBundleContext() const

Returns this bundle's BundleContext.

The returned BundleContext can be used by the caller to act on behalf of this bundle.

If this bundle is not in the STATE_STARTING, STATE_ACTIVE, or STATE_STOPPING states, then this bundle has no valid BundleContext and this method will return an invalid BundleContext object.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

A valid or invalid BundleContext for this bundle.

long GetBundleId() const

Returns this bundle's unique identifier.

This bundle is assigned a unique identifier by the framework when it was installed.

A bundle's unique identifier has the following attributes:.INDENT 7.0

·

Is unique.

·

Is a long.

·

Its value is not reused for another bundle, even after a bundle is uninstalled.

·

Does not change while a bundle remains installed.

·

Does not change when a bundle is re-started.

This method continues to return this bundle's unique identifier while this bundle is in the STATE_UNINSTALLED state.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The unique identifier of this bundle.

std::string GetLocation() const

Returns this bundle's location.

The location is the full path to the bundle's shared library. This method continues to return this bundle's location while this bundle is in the STATE_UNINSTALLED state.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The string representation of this bundle's location.

void *GetSymbol(void *handle, std::string const &symname) const

Retrieves the resolved symbol from bundle shared library and returns a function pointer associated with it.

Parameters
  • handle -- Handle to the Bundle's shared library
  • symname -- Name of the symbol
Throws
  • std::runtime_error -- if the bundle is not started or active
  • std::invalid_argument -- if handle or symname is empty
  • std::invalid_argument -- if this bundle is not initialized
Returns

A function pointer to the desired symbol or nullptr if the library is not loaded

Pre

Bundle is already started and active

Post

The symbol(s) associated with the bundle gets fetched if the library is loaded

Post

If the symbol does not exist, the API returns nullptr

std::string GetSymbolicName() const

Returns the symbolic name of this bundle as specified by the US_BUNDLE_NAME preprocessor definition.

The bundle symbolic name together with a version must identify a unique bundle.

This method continues to return this bundle's symbolic name while this bundle is in the STATE_UNINSTALLED state.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The symbolic name of this bundle.

BundleVersion GetVersion() const

Returns the version of this bundle as specified in its manifest.json file.

If this bundle does not have a specified version then BundleVersion::EmptyVersion is returned.

This method continues to return this bundle's version while this bundle is in the STATE_UNINSTALLED state.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The version of this bundle.

std::map<std::string, Any> GetProperties() const

Returns this bundle's Manifest properties as key/value pairs.

Deprecated since version 3.0: Use GetHeaders() instead.

SEE ALSO:

Bundle Properties

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

A map containing this bundle's Manifest properties as key/value pairs.

AnyMap const &GetHeaders() const

Returns this bundle's Manifest headers and values.

Manifest header names are case-insensitive. The methods of the returned AnyMap object operate on header names in a case-insensitive manner.

If a Manifest header value starts with "%", it is localized according to the default locale. If no localization is found for a header value, the header value without the leading "%" is returned.

This method continues to return Manifest header information while this bundle is in the UNINSTALLED state.

SEE ALSO:

Constants::BUNDLE_LOCALIZATION

NOTE:

Localization is not yet supported, hence the leading "%" is always removed.

NOTE:

The lifetime of the returned reference is bound to the lifetime of this Bundle object.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

A map containing this bundle's Manifest headers and values.

Any GetProperty(std::string const &key) const

Returns the value of the specified property for this bundle.

If not found, the framework's properties are searched. The method returns an empty Any if the property is not found.

Deprecated since version 3.0: Use GetHeaders() or :any:

`

BundleContext::GetProperty(const

std::string&) <cppmicroservices::BundleContext::GetProperty>` instead.

SEE ALSO:

Bundle Properties
Parameters

key -- The name of the requested property.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The value of the requested property, or an empty string if the property is undefined.

std::vector<std::string> GetPropertyKeys() const

Returns a list of top-level property keys for this bundle.

Deprecated since version 3.0: Use GetHeaders() instead.

SEE ALSO:

Bundle Properties

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

A list of available property keys.

std::vector<ServiceReferenceU> GetRegisteredServices() const

Returns this bundle's ServiceReference list for all services it has registered or an empty list if this bundle has no registered services.

The list is valid at the time of the call to this method, however, as the framework is a very dynamic environment, services can be modified or unregistered at anytime.

Throws
  • std::logic_error -- If this bundle has been uninstalled, if the ServiceRegistrationBase object is invalid, or if the service is unregistered.
  • std::invalid_argument -- if this bundle is not initialized.
Returns

A list of ServiceReference objects for services this bundle has registered.

std::vector<ServiceReferenceU> GetServicesInUse() const

Returns this bundle's ServiceReference list for all services it is using or returns an empty list if this bundle is not using any services.

A bundle is considered to be using a service if its use count for that service is greater than zero.

The list is valid at the time of the call to this method, however, as the framework is a very dynamic environment, services can be modified or unregistered at anytime.

Throws
  • std::logic_error -- If this bundle has been uninstalled, if the ServiceRegistrationBase object is invalid, or if the service is unregistered.
  • std::invalid_argument -- if this bundle is not initialized.
Returns

A list of ServiceReference objects for all services this bundle is using.

BundleResource GetResource(std::string const &path) const

Returns the resource at the specified path in this bundle.

The specified path is always relative to the root of this bundle and may begin with '/'. A path value of "/" indicates the root of this bundle.

Parameters

path -- The path name of the resource.

Throws
  • std::logic_error -- If this bundle has been uninstalled.
  • std::invalid_argument -- if this bundle is not initialized.
Returns

A BundleResource object for the given path. If the path cannot be found in this bundle an invalid BundleResource object is returned.

std::vector<BundleResource> FindResources(std::string const &path, std::string const &filePattern, bool recurse) const

Returns resources in this bundle.

This method is intended to be used to obtain configuration, setup, localization and other information from this bundle.

This method can either return only resources in the specified path or recurse into subdirectories returning resources in the directory tree beginning at the specified path.

Examples: .INDENT 7.0

    auto bundleContext = GetBundleContext();
    auto bundle = bundleContext.GetBundle();

    // List all XML files in the config directory
    std::vector<BundleResource> xmlFiles = bundle.FindResources("config", "*.xml", false);

    // Find the resource named vertex_shader.txt starting at the root directory
    std::vector<BundleResource> shaders = bundle.FindResources("", "vertex_shader.txt", true);
Parameters
  • path -- The path name in which to look. The path is always relative to the root of this bundle and may begin with '/'. A path value of "/" indicates the root of this bundle.
  • filePattern -- The resource name pattern for selecting entries in the specified path. The pattern is only matched against the last element of the resource path. Substring matching is supported using the wildcard charachter ('*'). If filePattern is empty, this is equivalent to "*" and matches all resources.
  • recurse -- If true, recurse into subdirectories. Otherwise only return resources from the specified path.
Throws
  • std::logic_error -- If this bundle has been uninstalled.
  • std::invalid_argument -- if this bundle is not initialized.
Returns

A vector of BundleResource objects for each matching entry.

TimeStamp GetLastModified() const

Returns the time when this bundle was last modified.

A bundle is considered to be modified when it is installed, updated or uninstalled.

Throws

std::invalid_argument -- if this bundle is not initialized.

Returns

The time when this bundle was last modified.

void Start(uint32_t options)

Starts this bundle.

If this bundle's state is STATE_UNINSTALLED then a std::logic_error is thrown.

The Framework sets this bundle's persistent autostart setting to Started with declared activation if the START_ACTIVATION_POLICY option is set or Started with eager activation if not set.

The following steps are executed to start this bundle:.INDENT 7.0

i.

If this bundle is in the process of being activated or deactivated, then this method waits for activation or deactivation to complete before continuing. If this does not occur in a reasonable time, a std::runtime_error is thrown to indicate this bundle was unable to be started.

ii.

If this bundle's state is STATE_ACTIVE, then this method returns immediately.

iii.

If the START_TRANSIENT option is not set, then set this bundle's autostart setting to Started with declared activation if the START_ACTIVATION_POLICY option is set or Started with eager activation if not set. When the Framework is restarted and this bundle's autostart setting is not Stopped, this bundle must be automatically started.

iv.

If this bundle's state is not STATE_RESOLVED, an attempt is made to resolve this bundle. If the Framework cannot resolve this bundle, a std::runtime_error is thrown.

v.

If the START_ACTIVATION_POLICY option is set and this bundle's declared activation policy is lazy then:.INDENT 5.0

·

If this bundle's state is STATE_STARTING, then this method returns immediately.

·

This bundle's state is set to STATE_STARTING.

·

A bundle event of type BundleEvent#BUNDLE_LAZY_ACTIVATION is fired.

·

This method returns immediately and the remaining steps will be followed when this bundle's activation is later triggered.

vi.

This bundle's state is set to STATE_STARTING.

vii.

A bundle event of type BundleEvent#BUNDLE_STARTING is fired.

viii.

If the bundle is contained in a shared library, the library is loaded and the BundleActivator#Start(BundleContext) method of this bundle's BundleActivator (if one is specified) is called. If the shared library could not be loaded, or the BundleActivator is invalid or throws an exception then:.INDENT 5.0

·

This bundle's state is set to STATE_STOPPING.

·

A bundle event of type BundleEvent#BUNDLE_STOPPING is fired.

·

Any services registered by this bundle are unregistered.

·

Any services used by this bundle are released.

·

Any listeners registered by this bundle are removed.

·

This bundle's state is set to STATE_RESOLVED.

·

A bundle event of type BundleEvent#BUNDLE_STOPPED is fired.

·

A std::runtime_error exception is then thrown.

ix.

If this bundle's state is STATE_UNINSTALLED, because this bundle was uninstalled while the BundleActivator::Start method was running, a std::logic_error is thrown.

x.

This bundle's state is set to STATE_ACTIVE.

xi.

A bundle event of type BundleEvent#BUNDLE_STARTED is fired.

Preconditions.INDENT 7.0

i.

GetState() in { STATE_INSTALLED, STATE_RESOLVED } or { STATE_INSTALLED, STATE_RESOLVED, STATE_STARTING } if this bundle has a lazy activation policy.

Postconditions, no exceptions thrown .INDENT 7.0

i.

Bundle autostart setting is modified unless the START_TRANSIENT option was set.

ii.

GetState() in { STATE_ACTIVE } unless the lazy activation policy was used.

iii.

BundleActivator::Start() has been called and did not throw an exception unless the lazy activation policy was used.

Postconditions, when an exception is thrown .INDENT 7.0

i.

Depending on when the exception occurred, the bundle autostart setting is modified unless the START_TRANSIENT option was set.

ii.

GetState() not in { STATE_STARTING, STATE_ACTIVE }.

Parameters

options -- The options for starting this bundle. See START_TRANSIENT and START_ACTIVATION_POLICY. The Framework ignores unrecognized options.

Throws
  • std::runtime_error -- If this bundle could not be started.
  • std::logic_error -- If this bundle has been uninstalled or this bundle tries to change its own state.
  • std::invalid_argument -- if this bundle is not initialized.
  • cppmicroservices::SecurityException -- if the bundle's shared library to be loaded failed a security check.
void Start()

Starts this bundle with no options.

This method performs the same function as calling Start(0).

SEE ALSO:

Start(uint32_t)

Throws
  • std::runtime_error -- If this bundle could not be started.
  • std::logic_error -- If this bundle has been uninstalled or this bundle tries to change its own state.
  • std::invalid_argument -- if this bundle is not initialized.
  • cppmicroservices::SecurityException -- if the bundle's shared library to be loaded failed a security check.
void Stop(uint32_t options)

Stops this bundle.

The following steps are executed when stopping a bundle:.INDENT 7.0

i.

If this bundle's state is STATE_UNINSTALLED then a std::logic_error is thrown.

ii.

If this bundle is in the process of being activated or deactivated then this method waits for activation or deactivation to complete before continuing. If this does not occur in a reasonable time, a std::runtime_error is thrown to indicate this bundle was unable to be stopped.

iii.

If the STOP_TRANSIENT option is not set then set this bundle's persistent autostart setting to Stopped. When the Framework is restarted and this bundle's autostart setting is Stopped, this bundle will not be automatically started.

iv.

If this bundle's state is not STATE_STARTING or STATE_ACTIVE then this method returns immediately.

v.

This bundle's state is set to STATE_STOPPING.

vi.

A bundle event of type BundleEvent#BUNDLE_STOPPING is fired.

vii.

If this bundle's state was STATE_ACTIVE prior to setting the state to STATE_STOPPING, the BundleActivator#Stop(BundleContext) method of this bundle's BundleActivator, if one is specified, is called. If that method throws an exception, this method continues to stop this bundle and a std::runtime_error is thrown after completion of the remaining steps.

viii.

Any services registered by this bundle are unregistered.

ix.

Any services used by this bundle are released.

x.

Any listeners registered by this bundle are removed.

xi.

If this bundle's state is STATE_UNINSTALLED, because this bundle was uninstalled while the BundleActivator::Stop method was running, a std::runtime_error is thrown.

xii.

This bundle's state is set to STATE_RESOLVED.

xiii.

A bundle event of type BundleEvent#BUNDLE_STOPPED is fired.

Preconditions .INDENT 7.0

i.

GetState() in { STATE_ACTIVE }.

Postconditions, no exceptions thrown .INDENT 7.0

i.

Bundle autostart setting is modified unless the STOP_TRANSIENT option was set.

ii.

GetState() not in { STATE_ACTIVE, STATE_STOPPING }.

iii.

BundleActivator::Stop has been called and did not throw an exception.

Postconditions, when an exception is thrown .INDENT 7.0

i.

Bundle autostart setting is modified unless the STOP_TRANSIENT option was set.

Parameters

options -- The options for stopping this bundle. See STOP_TRANSIENT. The Framework ignores unrecognized options.

Throws
  • std::runtime_error -- If the bundle failed to stop.
  • std::logic_error -- If this bundle has been uninstalled or this bundle tries to change its own state.
  • std::invalid_argument -- if this bundle is not initialized.
void Stop()

Stops this bundle with no options.

This method performs the same function as calling Stop(0).

SEE ALSO:

Stop(uint32_t)

Throws
  • std::runtime_error -- If the bundle failed to stop.
  • std::logic_error -- If this bundle has been uninstalled or this bundle tries to change its own state.
void Uninstall()

Uninstalls this bundle.

This method causes the Framework to notify other bundles that this bundle is being uninstalled, and then puts this bundle into the STATE_UNINSTALLED state. The Framework removes any resources related to this bundle that it is able to remove.

The following steps are executed to uninstall a bundle:.INDENT 7.0

i.

If this bundle's state is STATE_UNINSTALLED, then a std::logic_error is thrown.

ii.

If this bundle's state is STATE_ACTIVE, STATE_STARTING or STATE_STOPPING, this bundle is stopped as described in the Bundle::Stop method. If Bundle::Stop throws an exception, a Framework event of type FrameworkEvent#FRAMEWORK_ERROR is fired containing the exception.

iii.

This bundle's state is set to STATE_UNINSTALLED.

iv.

A bundle event of type BundleEvent#BUNDLE_UNINSTALLED is fired.

v.

This bundle and any persistent storage area provided for this bundle by the Framework are removed.

Preconditions .INDENT 7.0

  • GetState() not in { STATE_UNINSTALLED }.

Postconditions, no exceptions thrown .INDENT 7.0

  • GetState() in { STATE_UNINSTALLED }.
  • This bundle has been uninstalled.

Postconditions, when an exception is thrown .INDENT 7.0

  • GetState() not in { STATE_UNINSTALLED }.
  • This Bundle has not been uninstalled.
SEE ALSO:

Stop()

Throws
  • std::runtime_error -- If the uninstall failed. This can occur if another thread is attempting to change this bundle's state and does not complete in a timely manner.
  • std::logic_error -- If this bundle has been uninstalled or this bundle tries to change its own state.
  • std::invalid_argument -- if this bundle is not initialized.
Protected Functions

Bundle(std::shared_ptr<BundlePrivate> const &d)

Protected Attributes

std::shared_ptr<BundlePrivate> d

std::shared_ptr<CoreBundleContext> c

Friends

friend class BundleRegistry

friend Bundle MakeBundle(std::shared_ptr<BundlePrivate> const&)

BundleActivator

struct BundleActivator

Customizes the starting and stopping of a CppMicroServices bundle.

BundleActivator is an interface that can be implemented by CppMicroServices bundles. The CppMicroServices library can create instances of a bundle's BundleActivator as required. If an instance's BundleActivator::Start method executes successfully, it is guaranteed that the same instance's BundleActivator::Stop method will be called when the bundle is to be stopped. The CppMicroServices library does not concurrently call a BundleActivator object.

BundleActivator is an abstract class interface whose implementations must be exported via a special macro. Implementations are usually declared and defined directly in .cpp files.

class MyActivator : public BundleActivator
{

  public:
    void
    Start(BundleContext /*context*/)
    { /* register stuff */
    }

    void
    Stop(BundleContext /*context*/)
    { /* cleanup */
    }
};

CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR(MyActivator)

The class implementing the BundleActivator interface must have a public default constructor so that a BundleActivator object can be created by the CppMicroServices library.

NOTE:

A bundle activator needs to be exported by using the Cppmicroservices_export_bundle_activator macro. The bundle manifest.json resource also needs to contain a

"bundle.activator" : true

element.

Public Functions

virtual ~BundleActivator() = default

virtual void Start(BundleContext context) = 0

Called when this bundle is started.

This method can be used to register services or to allocate any resources that this bundle may need globally (during the whole bundle lifetime).

This method must complete and return to its caller in a timely manner.

Parameters

context -- The execution context of the bundle being started.

Throws

std::exception -- If this method throws an exception, this bundle is marked as stopped and the framework will remove this bundle's listeners, unregister all services registered by this bundle, and release all services used by this bundle.

virtual void Stop(BundleContext context) = 0

Called when this bundle is stopped.

In general, this method should undo the work that the BundleActivator::Start method started. There should be no active threads that were started by this bundle when this method returns.

This method must complete and return to its caller in a timely manner.

Parameters

context -- The execution context of the bundle being stopped.

Throws

std::exception -- If this method throws an exception, the bundle is still marked as stopped, and the framework will remove the bundle's listeners, unregister all services registered by the bundle, and release all services used by the bundle.

BundleContext

class BundleContext

A bundle's execution context within the framework.

The context is used to grant access to other methods so that this bundle can interact with the framework.

BundleContext methods allow a bundle to: .INDENT 7.0

·

Install other bundles.

·

Subscribe to events published by the framework.

·

Register service objects with the framework service registry.

·

Retrieve ServiceReferences from the framework service registry.

·

Get and release service objects for a referenced service.

·

Get the list of bundles installed in the framework.

·

Get the Bundle object for a bundle.

A BundleContext object will be created and provided to the bundle associated with this context when it is started using the BundleActivator::Start method. The same BundleContext object will be passed to the bundle associated with this context when it is stopped using the BundleActivator::Stop method. A BundleContext object is generally for the private use of its associated bundle and is not meant to be shared with other bundles in the bundle environment.

The Bundle object associated with a BundleContext object is called the context bundle.

The BundleContext object is only valid during the execution of its context bundle; that is, during the period when the context bundle is started. If the BundleContext object is used subsequently, a std::runtime_error is thrown. The BundleContext object is never reused after its context bundle is stopped.

The framework is the only entity that can create BundleContext objects.

Remark

This class is thread safe.

Public Functions

BundleContext()

Constructs an invalid BundleContext object.

Valid bundle context objects can only be created by the framework and are supplied to a bundle via its BundleActivator or as a return value of the GetBundleContext() method.

SEE ALSO:

operator bool() const

bool operator==(BundleContext const &rhs) const

Compares this BundleContext object with the specified bundle context.

Valid BundleContext objects are equal if and only if they represent the same context. Invalid BundleContext objects are always considered to be equal.

Parameters

rhs -- The BundleContext object to compare this object with.

Returns

true if this BundleContext object is equal to rhs, false otherwise.

bool operator!=(BundleContext const &rhs) const

Compares this BundleContext object with the specified bundle context for inequality.

Parameters

rhs -- The BundleContext object to compare this object with.

Returns

Returns the result of !(*this == rhs).

bool operator<(BundleContext const &rhs) const

Compares this BundleContext with the specified bundle context for order.

How valid BundleContext objects are ordered is an implementation detail and must not be relied on. Invalid BundleContext objects will always compare greater then valid BundleContext objects.

Parameters

rhs -- The BundleContext object to compare this object with.

Returns

true if this object is orderded before rhs, false otherwise.

explicit operator bool() const

Tests this BundleContext object for validity.

Invalid BundleContext objects are created by the default constructor or can be returned by certain framework methods if the context bundle has been uninstalled.

A BundleContext object can become invalid by assigning a nullptr to it or if the context bundle is stopped.

Returns

true if this BundleContext object is valid and can safely be used, false otherwise.

BundleContext &operator=(std::nullptr_t)

Releases any resources held or locked by this BundleContext and renders it invalid.

Any GetProperty(std::string const &key) const

Returns the value of the specified property.

If the key is not found in the Framework properties, the method returns an empty Any.

Parameters

key -- The name of the requested property.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

The value of the requested property, or an empty Any if the property is undefined.

AnyMap GetProperties() const

Returns all known properties.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

A map of all framework properties.

Bundle GetBundle() const

Returns the Bundle object associated with this BundleContext.

This bundle is called the context bundle.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

The Bundle object associated with this BundleContext.

Bundle GetBundle(long id) const

Returns the bundle with the specified identifier.

Parameters

id -- The identifier of the bundle to retrieve.

Throws
  • std::logic_error -- If the framework instance is not active.
  • std::runtime_error -- If this BundleContext is no longer valid.
Returns

A Bundle object or nullptr if the identifier does not match any previously installed bundle.

std::vector<Bundle> GetBundles(std::string const &location) const

Get the bundles with the specified bundle location.

Parameters

location -- The location of the bundles to get.

Throws
  • std::logic_error -- If the framework instance is not active.
  • std::runtime_error -- If the BundleContext is no longer valid.
Returns

The requested {Bundle}s or an empty list.

std::vector<Bundle> GetBundles() const

Returns a list of all known bundles.

This method returns a list of all bundles installed in the bundle environment at the time of the call to this method. This list will also contain bundles which might already have been stopped.

Throws

std::runtime_error -- If the BundleContext is no longer valid.

Returns

A std::vector of Bundle objects which will hold one object per known bundle.

ServiceRegistrationU RegisterService(InterfaceMapConstPtr const &service, ServiceProperties const &properties = ServiceProperties())

Registers the specified service object with the specified properties under the specified class names into the framework.

A ServiceRegistration object is returned. The ServiceRegistration object is for the private use of the bundle registering the service and should not be shared with other bundles. The registering bundle is defined to be the context bundle. Other bundles can locate the service by using either the GetServiceReferences or GetServiceReference method.

A bundle can register a service object that implements the ServiceFactory or PrototypeServiceFactory interface to have more flexibility in providing service objects to other bundles.

The following steps are taken when registering a service: .INDENT 7.0

i.

The framework adds the following service properties to the service properties from the specified ServiceProperties

(which may be omitted):

A property named Constants::SERVICE_ID

identifying the registration number of the service

A property named Constants::OBJECTCLASS

containing all the specified classes.

A property named Constants::SERVICE_SCOPE

identifying the scope of the service.

Properties with these names in the specified ServiceProperties will be ignored.

ii.

The service is added to the framework service registry and may now be used by other bundles.

iii.

A service event of type ServiceEvent::SERVICE_REGISTERED is fired.

iv.

A ServiceRegistration object for this registration is returned.

SEE ALSO:

ServiceRegistration

SEE ALSO:

ServiceFactory

SEE ALSO:

PrototypeServiceFactory

NOTE:

This is a low-level method and should normally not be used directly. Use one of the templated RegisterService methods instead.

Parameters
  • service -- A shared_ptr to a map of interface identifiers to service objects.
  • properties -- The properties for this service. The keys in the properties object must all be std::string objects. See Constants for a list of standard service property keys. Changes should not be made to this object after calling this method. To update the service's properties the ServiceRegistration::SetProperties method must be called. The set of properties may be omitted if the service has no properties.
Throws
  • std::runtime_error -- If this BundleContext is no longer valid, or if there are case variants of the same key in the supplied properties map.
  • std::invalid_argument -- If the InterfaceMap is empty, or if a service is registered as a null class.
Returns

A ServiceRegistration object for use by the bundle registering the service to update the service's properties or to unregister the service. This object cannot be called from a discard-value expression as the intent is for the ServiceRegistration object is intended to be stored by the caller

template<class I1, class ...Interfaces, class Impl> inline ServiceRegistration<I1, Interfaces...> RegisterService(std::shared_ptr<Impl> const &impl, ServiceProperties const &properties = ServiceProperties())

Registers the specified service object with the specified properties using the specified interfaces types with the framework.

This method is provided as a convenience when registering a service under two interface classes whose type is available to the caller. It is otherwise identical to RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred since it avoids errors in the string literal identifying the class name or interface identifier.

Example usage: .INDENT 7.0

class MyService2
    : public InterfaceA
    , public InterfaceB
{
};

.INDENT 7.0

        std::shared_ptr<MyService2> myService = std::make_shared<MyService2>();
        context.RegisterService<InterfaceA, InterfaceB>(myService);
SEE ALSO:

RegisterService(const InterfaceMap&, const ServiceProperties&)

Template Parameters
  • I1 -- The first interface type under which the service can be located.
  • Interfaces -- Additional interface types under which the service can be located.
Parameters
  • impl -- A shared_ptr to the service object
  • properties -- The properties for this service.
Throws
  • std::logic_error -- If this BundleContext is no longer valid.
  • ServiceException -- If the service type S is invalid or the service object is nullptr.
Returns

A ServiceRegistration object for use by the bundle registering the service to update the service's properties or to unregister the service.

template<class I1, class ...Interfaces> inline ServiceRegistration<I1, Interfaces...> RegisterService(std::shared_ptr<ServiceFactory> const &factory, ServiceProperties const &properties = ServiceProperties())

Registers the specified service factory as a service with the specified properties using the specified template argument as service interface type with the framework.

This method is provided as a convenience when factory will only be registered under a single class name whose type is available to the caller. It is otherwise identical to RegisterService(const InterfaceMap&, const ServiceProperties&) but should be preferred since it avoids errors in the string literal identifying the class name or interface identifier.

Example usage: .INDENT 7.0

class MyService2
    : public InterfaceA
    , public InterfaceB
{
};

.INDENT 7.0

        class MyServiceFactory : public ServiceFactory
        {
            virtual InterfaceMapConstPtr
            GetService(Bundle const& /*bundle*/, ServiceRegistrationBase const& /*registration*/)
            {
                return MakeInterfaceMap<InterfaceA, InterfaceB>(std::make_shared<MyService2>());
            }

            virtual void
            UngetService(Bundle const& /*bundle*/,
                         ServiceRegistrationBase const& /*registration*/,
                         InterfaceMapConstPtr const& /*service*/)
            {
            }
        };

        std::shared_ptr<MyServiceFactory> myServiceFactory = std::make_shared<MyServiceFactory>();
        context.RegisterService<InterfaceA, InterfaceB>(ToFactory(myServiceFactory));
SEE ALSO:

RegisterService(const InterfaceMap&, const ServiceProperties&)

Template Parameters
  • I1 -- The first interface type under which the service can be located.
  • Interfaces -- Additional interface types under which the service can be located.
Parameters
  • factory -- A shared_ptr to the ServiceFactory object.
  • properties -- The properties for this service.
Throws
  • std::logic_error -- If this BundleContext is no longer valid.
  • ServiceException -- If the service type S is invalid or the service factory object is nullptr.
Returns

A ServiceRegistration object for use by the bundle registering the service to update the service's properties or to unregister the service.

std::vector<ServiceReferenceU> GetServiceReferences(std::string const &clazz, std::string const &filter = std::string())

Returns a list of ServiceReference objects ordered by rank.

The returned list contains services that were registered under the specified class and match the specified filter expression.

The list is valid at the time of the call to this method. However, since the framework is a very dynamic environment, services can be modified or unregistered at any time.

The specified filter expression is used to select the registered services whose service properties contain keys and values that satisfy the filter expression. See LDAPFilter for a description of the filter syntax. If the specified filter is empty, all registered services are considered to match the filter. If the specified filter expression cannot be parsed, an std::invalid_argument will be thrown with a human-readable message where the filter became unparsable.

The result is a list of ServiceReference objects for all services that meet all of the following conditions: .INDENT 7.0

·

If the specified class name, clazz, is not empty, the service must have been registered with the specified class name. The complete list of class names with which a service was registered is available from the service's objectClass property.

·

If the specified filter is not empty, the filter expression must match the service.

Parameters
  • clazz -- The class name with which the service was registered or an empty string for all services.
  • filter -- The filter expression or empty for all services.
Throws
  • std::invalid_argument -- If the specified filter contains an invalid filter expression that cannot be parsed.
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::logic_error -- If the ServiceRegistrationBase object is invalid, or if the service is unregistered.
Returns

A list of ServiceReference objects or an empty list if no services are registered that satisfy the search. These objects will be in decreasing order of their rank.

template<class S> inline std::vector<ServiceReference<S>> GetServiceReferences(std::string const &filter = std::string())

Returns a list of ServiceReference objects ordered by rank.

The returned list contains services that were registered under the interface id of the template argument S and match the specified filter expression.

This method is identical to GetServiceReferences(const std::string&, const std::string&) except that the class name for the service object is automatically deduced from the template argument.

SEE ALSO:

GetServiceReferences(const std::string&, const std::string&)

Template Parameters

S -- The type under which the requested service objects must have been registered.

Parameters

filter -- The filter expression or empty for all services.

Throws
  • std::invalid_argument -- If the specified filter contains an invalid filter expression that cannot be parsed.
  • std::runtime_error -- If this BundleContext is no longer valid.
  • ServiceException -- If the service interface id of S is empty, see Service Interface.
Returns

A list of ServiceReference objects or an empty list if no services are registered which satisfy the search. These objects will be in decreasing order of their rank.

ServiceReferenceU GetServiceReference(std::string const &clazz)

Returns a ServiceReference object for a service that implements and was registered under the specified class.

The returned ServiceReference object is valid at the time of the call to this method. However as the Micro Services framework is a very dynamic environment, services can be modified or unregistered at any time.

This method is the same as calling BundleContext::GetServiceReferences(const std::string&, const std::string&) with an empty filter expression. It is provided as a convenience for when the caller is interested in any service that implements the specified class.

If multiple such services exist, the service with the highest ranking (as specified in its Constants::SERVICE_RANKING property) is returned.

If there is a tie in ranking, the service with the lowest service ID (as specified in its Constants::SERVICE_ID property); that is, the service that was registered first is returned.

SEE ALSO:

GetServiceReferences(const std::string&, const std::string&)

Parameters

clazz -- The class name with which the service was registered.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

A ServiceReference object, or an invalid ServiceReference if no services are registered which implement the named class.

template<class S> inline ServiceReference<S> GetServiceReference()

Returns a ServiceReference object for a service that implements and was registered under the specified template class argument.

This method is identical to GetServiceReference(const std::string&) except that the class name for the service object is automatically deduced from the template argument.

SEE ALSO:

GetServiceReference(const std::string&)

SEE ALSO:

GetServiceReferences(const std::string&)

Template Parameters

S -- The type under which the requested service must have been registered.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • ServiceException -- If the service interface id of S is empty, see Service Interface.
Returns

A ServiceReference object, or an invalid ServiceReference if no services are registered which implement the type S.

std::shared_ptr<void> GetService(ServiceReferenceBase const &reference)

Returns the service object referenced by the specified ServiceReferenceBase object.

A bundle's use of a service is tracked by the bundle's use count of that service. Each call to GetService(const ServiceReference<S>&) increments the context bundle's use count by one. The deleter function of the returned shared_ptr object is responsible for decrementing the context bundle's use count.

When a bundle's use count for a service drops to zero, the bundle should no longer use that service.

This method will always return an empty object when the service associated with this reference has been unregistered.

The ServiceObjects object must be used to obtain multiple service objects for services with prototype scope. For services with singleton or bundle scope, the ServiceObjects::GetService() method behaves the same as the GetService(const ServiceReference<S>&) method. That is, only one, use-counted service object is available from the ServiceObjects object.

The following steps are taken to get the service object: .INDENT 7.0

i.

If the service has been unregistered, an empty object is returned.

ii.

The context bundle's use count for this service is incremented by one.

iii.

If the context bundle's use count for the service is currently one and the service was registered with an object implementing the ServiceFactory interface, the ServiceFactory::GetService

method is called to create a service object for the context bundle. This service object is cached by the framework. While the context bundle's use count for the service is greater than zero, subsequent calls to get the services's service object for the context bundle will return the cached service object.

If the ServiceFactory object throws an exception, empty object is returned and a warning is logged.

iv.

A shared_ptr to the service object is returned.

SEE ALSO:

ServiceFactory

SEE ALSO:

ServiceObjects

Parameters

reference -- A reference to the service.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::invalid_argument -- If the specified ServiceReferenceBase is invalid (default constructed).
  • cppmicroservices::SecurityException -- if retrieving a service caused a bundle's shared library to be loaded and the bundle failed a security check.
Returns

A shared_ptr to the service object associated with reference. An empty shared_ptr is returned if the service is not registered or the ServiceFactory threw an exception

InterfaceMapConstPtr GetService(ServiceReferenceU const &reference)

template<class S> inline std::shared_ptr<S> GetService(ServiceReference<S> const &reference)

Returns the service object referenced by the specified ServiceReference object.

This is a convenience method which is identical to void* GetService(const ServiceReferenceBase&) except that it casts the service object to the supplied template argument type

SEE ALSO:

GetService(const ServiceReferenceBase&)

SEE ALSO:

ServiceFactory

Template Parameters

S -- The type the service object will be cast to.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::invalid_argument -- If the specified ServiceReference is invalid (default constructed).
  • cppmicroservices::SecurityException -- if retrieving a service caused a bundle's shared library to be loaded and the bundle failed a security check.
Returns

A shared_ptr to the service object associated with reference. An empty object is returned if the service is not registered, the ServiceFactory threw an exception or the service could not be cast to the desired type.

template<class S> inline ServiceObjects<S> GetServiceObjects(ServiceReference<S> const &reference)

Returns the ServiceObjects object for the service referenced by the specified ServiceReference object.

The ServiceObjects object can be used to obtain multiple service objects for services with prototype scope. For services with singleton or bundle scope, the ServiceObjects::GetService() method behaves the same as the GetService(const ServiceReference<S>&) method. That is, only one, use-counted service object is available from the ServiceObjects object.

SEE ALSO:

PrototypeServiceFactory

Template Parameters

S -- Type of Service.

Parameters

reference -- A reference to the service.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::invalid_argument -- If the specified ServiceReference is invalid (default constructed or the service has been unregistered)
  • cppmicroservices::SecurityException -- if retrieving a service caused a bundle's shared library to be loaded and the bundle failed a security check.
Returns

A ServiceObjects object for the service associated with the specified reference or an invalid instance if the service is not registered.

ListenerToken AddServiceListener(ServiceListener const &listener, std::string const &filter = std::string())

Adds the specified listener with the specified filter to the context bundles's list of listeners.

See LDAPFilter for a description of the filter syntax. Listeners are notified when a service has a lifecycle state change.

The framework takes care of removing all listeners registered by this context bundle's classes after the bundle is stopped.

The listener is called if the filter criteria is met. To filter based upon the class of the service, the filter should reference the Constants::OBJECTCLASS property. If filter is empty, all services are considered to match the filter.

When using a filter, it is possible that the ServiceEvents for the complete lifecycle of a service will not be delivered to the listener. For example, if the filter only matches when the property example_property has the value 1, the listener will not be called if the service is registered with the property example_property not set to the value 1. Subsequently, when the service is modified setting property example_property to the value 1, the filter will match and the listener will be called with a ServiceEvent of type SERVICE_MODIFIED. Thus, the listener will not be called with a ServiceEvent of type SERVICE_REGISTERED.

SEE ALSO:

ServiceEvent

SEE ALSO:

ServiceListener

SEE ALSO:

RemoveServiceListener()

Parameters
  • listener -- Any callable object.
  • filter -- The filter criteria.
Throws
  • std::invalid_argument -- If filter contains an invalid filter string that cannot be parsed.
  • std::runtime_error -- If this BundleContext is no longer valid.
Returns

a ListenerToken object which can be used to remove the listener from the list of registered listeners.

void RemoveServiceListener(ServiceListener const &listener)

Removes the specified listener from the context bundle's list of listeners.

If the listener is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddServiceListener()

Parameters

listener -- The callable object to remove.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

ListenerToken AddBundleListener(BundleListener const &listener)

Adds the specified listener to the context bundles's list of listeners.

Listeners are notified when a bundle has a lifecycle state change.

SEE ALSO:

BundleEvent

SEE ALSO:

BundleListener

Parameters

listener -- Any callable object.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

a ListenerToken object which can be used to remove the listener from the list of registered listeners.

void RemoveBundleListener(BundleListener const &listener)

Removes the specified listener from the context bundle's list of listeners.

If the listener is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddBundleListener()

SEE ALSO:

BundleListener

Parameters

listener -- The callable object to remove.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

ListenerToken AddFrameworkListener(FrameworkListener const &listener)

Adds the specified listener to the context bundles's list of framework listeners.

Listeners are notified of framework events.

SEE ALSO:

FrameworkEvent

SEE ALSO:

FrameworkListener

Parameters

listener -- Any callable object.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

a ListenerToken object which can be used to remove the listener from the list of registered listeners.

void RemoveFrameworkListener(FrameworkListener const &listener)

Removes the specified listener from the context bundle's list of framework listeners.

If the listener is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddFrameworkListener()

SEE ALSO:

FrameworkListener

Parameters

listener -- The callable object to remove.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

void RemoveListener(ListenerToken token)

Removes the registered listener associated with the token

If the listener associated with the token is not contained in this context bundle's list of listeners or if token is an invalid token, this method does nothing.

The token can correspond to one of Service, Bundle or Framework listeners. Using this function to remove the registered listeners is the recommended approach over using any of the other deprecated functions - Remove{Bundle,Framework,Service}Listener.

SEE ALSO:

AddServiceListener()

SEE ALSO:

AddBundleListener()

SEE ALSO:

AddFrameworkListener()

Parameters

token -- is an object of type ListenerToken.

Throws

std::runtime_error -- If this BundleContext is no longer valid.

template<class R> inline ListenerToken AddServiceListener(R *receiver, void (R::* callback)(ServiceEvent const&), std::string const &filter = std::string())

Adds the specified callback with the specified filter to the context bundles's list of listeners.

See LDAPFilter for a description of the filter syntax. Listeners are notified when a service has a lifecycle state change.

You must take care to remove registered listeners before the receiver object is destroyed. However, the Micro Services framework takes care of removing all listeners registered by this context bundle's classes after the bundle is stopped.

If the context bundle's list of listeners already contains a pair (r,c) of receiver and callback such that (r == receiver && c == callback), then this method replaces that callback's filter (which may be empty) with the specified one (which may be empty).

The callback is called if the filter criteria is met. To filter based upon the class of the service, the filter should reference the Constants::OBJECTCLASS property. If filter is empty, all services are considered to match the filter.

When using a filter, it is possible that the ServiceEvents for the complete lifecycle of a service will not be delivered to the callback. For example, if the filter only matches when the property example_property has the value 1, the callback will not be called if the service is registered with the property example_property not set to the value 1. Subsequently, when the service is modified setting property example_property to the value 1, the filter will match and the callback will be called with a ServiceEvent of type SERVICE_MODIFIED. Thus, the callback will not be called with a ServiceEvent of type SERVICE_REGISTERED.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use std::bind to bind the member function and then pass the result to AddServiceListener(const ServiceListener&)

instead.

SEE ALSO:

ServiceEvent

SEE ALSO:

RemoveServiceListener()

Template Parameters

R -- The type of the receiver (containing the member function to be called)

Parameters
  • receiver -- The object to connect to.
  • callback -- The member function pointer to call.
  • filter -- The filter criteria.
Throws
  • std::invalid_argument -- If filter contains an invalid filter string that cannot be parsed.
  • std::runtime_error -- If this BundleContext is no longer valid.
Returns

a ListenerToken object which can be used to remove the callable from the registered listeners.

template<class R> inline void RemoveServiceListener(R *receiver, void (R::* callback)(ServiceEvent const&))

Removes the specified callback from the context bundle's list of listeners.

If the (receiver,callback) pair is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddServiceListener()

Template Parameters

R -- The type of the receiver (containing the member function to be removed)

Parameters
  • receiver -- The object from which to disconnect.
  • callback -- The member function pointer to remove.
Throws

std::runtime_error -- If this BundleContext is no longer valid.

template<class R> inline ListenerToken AddBundleListener(R *receiver, void (R::* callback)(BundleEvent const&))

Adds the specified callback to the context bundles's list of listeners.

Listeners are notified when a bundle has a lifecycle state change.

If the context bundle's list of listeners already contains a pair (r,c) of receiver and callback such that (r == receiver && c == callback), then this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use std::bind to bind the member function and then pass the result to AddBundleListener(const BundleListener&)

instead.

SEE ALSO:

BundleEvent

Template Parameters

R -- The type of the receiver (containing the member function to be called)

Parameters
  • receiver -- The object to connect to.
  • callback -- The member function pointer to call.
Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

a ListenerToken object which can be used to remove the callable from the registered listeners.

template<class R> inline void RemoveBundleListener(R *receiver, void (R::* callback)(BundleEvent const&))

Removes the specified callback from the context bundle's list of listeners.

If the (receiver,callback) pair is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddBundleListener()

Template Parameters

R -- The type of the receiver (containing the member function to be removed)

Parameters
  • receiver -- The object from which to disconnect.
  • callback -- The member function pointer to remove.
Throws

std::runtime_error -- If this BundleContext is no longer valid.

template<class R> inline ListenerToken AddFrameworkListener(R *receiver, void (R::* callback)(FrameworkEvent const&))

Adds the specified callback to the context bundles's list of framework listeners.

Listeners are notified of framework events.

If the context bundle's list of listeners already contains a pair (r,c) of receiver and callback such that (r == receiver && c == callback), then this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use std::bind to bind the member function and then pass the result to :any:

`

AddFrameworkListener(const FrameworkListener&)

<cppmicroservices::BundleContext::AddFrameworkListener>` instead.

SEE ALSO:

FrameworkEvent

Template Parameters

R -- The type of the receiver (containing the member function to be called)

Parameters
  • receiver -- The object to connect to.
  • callback -- The member function pointer to call.
Throws

std::runtime_error -- If this BundleContext is no longer valid.

Returns

a ListenerToken object which can be used to remove the callable from the registered listeners.

template<class R> inline void RemoveFrameworkListener(R *receiver, void (R::* callback)(FrameworkEvent const&))

Removes the specified callback from the context bundle's list of framework listeners.

If the (receiver,callback) pair is not contained in this context bundle's list of listeners, this method does nothing.

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use RemoveListener() instead.

SEE ALSO:

AddFrameworkListener()

Template Parameters

R -- The type of the receiver (containing the member function to be removed)

Parameters
  • receiver -- The object from which to disconnect.
  • callback -- The member function pointer to remove.
Throws

std::runtime_error -- If this BundleContext is no longer valid.

std::string GetDataFile(std::string const &filename) const

Get the absolute path for a file or directory in the persistent storage area provided for the bundle.

The absolute path for the base directory of the persistent storage area provided for the context bundle by the Framework can be obtained by calling this method with an empty string as filename.

Parameters

filename -- A relative name to the file or directory to be accessed.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::invalid_argument -- If the input param filename is not a valid UTF-8 string.
Returns

The absolute path to the persistent storage area for the given file name.

std::vector<Bundle> InstallBundles(std::string const &location, cppmicroservices::AnyMap const &bundleManifest = cppmicroservices::AnyMap(cppmicroservices::any_map::UNORDERED_MAP_CASEINSENSITIVE_KEYS))

Installs all bundles from the bundle library at the specified location.

The following steps are required to install a bundle:.INDENT 7.0

i.

If a bundle containing the same install location is already installed, the Bundle object for that bundle is returned.

ii.

The bundle's associated resources are allocated. The associated resources minimally consist of a unique identifier and a persistent storage area if the platform has file system support. If this step fails, a std::runtime_error is thrown.

iii.

A bundle event of type BundleEvent::BUNDLE_INSTALLED is fired.

iv.

The Bundle object for the newly or previously installed bundle is returned.

Remark

An install location is an absolute path to a shared library or executable file which may contain several bundles, i. e. acts as a bundle library.

Remark

If the bundleManifest is passed in, it is installed. In the event that the injected bundle manifest does NOT match the manifest in the bundle's file, the behavior of the system is undefined.

Remark

If the provided bundleManifest does not match the manifest embedded in the bundle's file the behavior of that bundle in CppMicroServices is undefined.

Remark

Example JSON representation of manifest AnyMap:

Parameters
  • location -- The location of the bundle library to install.
  • bundleManifest -- OPTIONAL - the manifest of the bundle at "location". If non-empty this will be used without opening the bundle at "location". Otherwise, the bundle will be opened and the manifest read from there.
Throws
  • std::runtime_error -- If the BundleContext is no longer valid, or if the installation failed.
  • std::logic_error -- If the framework instance is no longer active
  • std::invalid_argument -- If the location is not a valid UTF8 string
Returns

The Bundle objects of the installed bundle library.

BundleEvent

std::ostream &operator<<(std::ostream &os, BundleEvent::Type eventType)

Writes a string representation of eventType to the stream os.

std::ostream &operator<<(std::ostream &os, BundleEvent const &event)

Writes a string representation of event to the stream os.

class BundleEvent

#include <cppmicroservices/BundleEvent.h>

An event from the Micro Services framework describing a bundle lifecycle change.

BundleEvent objects are delivered to listeners connected via BundleContext::AddBundleListener() when a change occurs in a bundles's lifecycle. A type code is used to identify the event type for future extendability.

SEE ALSO:

BundleContext::AddBundleListener

Public Types

enum Type

The bundle event type.

Values:

enumerator BUNDLE_INSTALLED

The bundle has been installed.

The bundle has been installed by the Framework.

SEE ALSO:

BundleContext::InstallBundles(const std::string&)

enumerator BUNDLE_STARTED

The bundle has been started.

The bundle's BundleActivator Start method has been executed if the bundle has a bundle activator class.

SEE ALSO:

Bundle::Start()

enumerator BUNDLE_STOPPED

The bundle has been stopped.

The bundle's BundleActivator Stop method has been executed if the bundle has a bundle activator class.

SEE ALSO:

Bundle::Stop()

enumerator BUNDLE_UPDATED

The bundle has been updated.

NOTE:

This identifier is reserved for future use and not supported yet.

enumerator BUNDLE_UNINSTALLED

The bundle has been uninstalled.

SEE ALSO:

Bundle::Uninstall()

enumerator BUNDLE_RESOLVED

The bundle has been resolved.

SEE ALSO:

Bundle::STATE_RESOLVED

enumerator BUNDLE_UNRESOLVED

The bundle has been unresolved.

SEE ALSO:

Bundle#BUNDLE_INSTALLED

enumerator BUNDLE_STARTING

The bundle is about to be activated.

The bundle's BundleActivator start method is about to be called if the bundle has a bundle activator class.

SEE ALSO:

Bundle::Start()

enumerator BUNDLE_STOPPING

The bundle is about to deactivated.

The bundle's BundleActivator stop method is about to be called if the bundle has a bundle activator class.

SEE ALSO:

Bundle::Stop()

enumerator BUNDLE_LAZY_ACTIVATION

The bundle will be lazily activated.

The bundle has a lazy activation policy and is waiting to be activated. It is now in the BUNDLE_STARTING state and has a valid BundleContext.

NOTE:

This identifier is reserved for future use and not supported yet.

Public Functions

BundleEvent()

Creates an invalid instance.

explicit operator bool() const

Can be used to check if this BundleEvent instance is valid, or if it has been constructed using the default constructor.

Returns

true if this event object is valid, false otherwise.

BundleEvent(Type type, Bundle const &bundle)

Creates a bundle event of the specified type.

Parameters
  • type -- The event type.
  • bundle -- The bundle which had a lifecycle change. This bundle is used as the origin of the event.
BundleEvent(Type type, Bundle const &bundle, Bundle const &origin)

Creates a bundle event of the specified type.

Parameters
  • type -- The event type.
  • bundle -- The bundle which had a lifecycle change.
  • origin -- The bundle which is the origin of the event. For the event type BUNDLE_INSTALLED, this is the bundle whose context was used to install the bundle. Otherwise it is the bundle itself.
Bundle GetBundle() const

Returns the bundle which had a lifecycle change.

Returns

The bundle that had a change occur in its lifecycle.

Type GetType() const

Returns the type of lifecyle event.

The type values are: .INDENT 7.0

·

BUNDLE_INSTALLED

·

BUNDLE_RESOLVED

·

BUNDLE_LAZY_ACTIVATION

·

BUNDLE_STARTING

·

BUNDLE_STARTED

·

BUNDLE_STOPPING

·

BUNDLE_STOPPED

·

BUNDLE_UNRESOLVED

·

BUNDLE_UNINSTALLED

Returns

The type of lifecycle event.

Bundle GetOrigin() const

Returns the bundle that was the origin of the event.

For the event type BUNDLE_INSTALLED, this is the bundle whose context was used to install the bundle. Otherwise it is the bundle itself.

Returns

The bundle that was the origin of the event.

bool operator==(BundleEvent const &evt) const

Compares two bundle events for equality.

Parameters

evt -- The bundle event to compare this event with.

Returns

true if both events originate from the same bundle, describe a life-cycle change for the same bundle, and are of the same type. false otherwise. Two invalid bundle events are considered to be equal.

BundleEventHook

struct BundleEventHook

Bundle Event Hook Service.

Bundles registering this service will be called during bundle lifecycle (installed, starting, started, stopping, stopped, uninstalled) operations.

Remark

Implementations of this interface are required to be thread-safe.

Public Functions

virtual ~BundleEventHook()

virtual void Event(BundleEvent const &event, ShrinkableVector<BundleContext> &contexts) = 0

Bundle event hook method.

This method is called prior to bundle event delivery when a bundle is installed, starting, started, stopping, stopped, and uninstalled. This method can filter the bundles which receive the event.

This method is called one and only one time for each bundle event generated, this includes bundle events which are generated when there are no bundle listeners registered.

Parameters
  • event -- The bundle event to be delivered.
  • contexts -- A list of Bundle Contexts for bundles which have listeners to which the specified event will be delivered. The implementation of this method may remove bundle contexts from the list to prevent the event from being delivered to the associated bundles.

BundleFindHook

struct BundleFindHook

Bundle Context Hook Service.

Bundles registering this service will be called during bundle find (get bundles) operations.

Remark

Implementations of this interface are required to be thread-safe.

Public Functions

virtual ~BundleFindHook()

virtual void Find(BundleContext const &context, ShrinkableVector<Bundle> &bundles) = 0

Find hook method.

This method is called for bundle find operations using BundleContext::GetBundle(long) and BundleContext::GetBundles() methods. The find method can filter the result of the find operation.

NOTE:

A find operation using the BundleContext::GetBundle(const std::string&) method does not cause the find method to be called, neither does any call to the static methods of the BundleRegistry class.

Parameters
  • context -- The bundle context of the bundle performing the find operation.
  • bundles -- A list of Bundles to be returned as a result of the find operation. The implementation of this method may remove bundles from the list to prevent the bundles from being returned to the bundle performing the find operation.

BundleResource

std::ostream &operator<<(std::ostream &os, BundleResource const &resource)

Streams the resource path into the stream os.

class BundleResource

#include <cppmicroservices/BundleResource.h>

Represents a resource (text file, image, etc.) embedded in a CppMicroServices bundle.

A BundleResource object provides information about a resource (external file) which was embedded into this bundle's shared library. BundleResource objects can be obtained be calling Bundle::GetResource or Bundle::FindResources.

Example code for retreiving a resource object and reading its contents: .INDENT 7.0

    // Get this bundle's Bundle object
    auto bundle = GetBundleContext().GetBundle();

    BundleResource resource = bundle.GetResource("config.properties");
    if (resource.IsValid())
    {
        // Create a BundleResourceStream object
        BundleResourceStream resourceStream(resource);

        // Read the contents line by line
        std::string line;
        while (std::getline(resourceStream, line))
        {
            // Process the content
            std::cout << line << std::endl;
        }
    }
    else
    {
        // Error handling
    }

BundleResource objects have value semantics and copies are very inexpensive.

SEE ALSO:

BundleResourceStream
The Resource System

Public Functions

BundleResource()

Creates in invalid BundleResource object.

SEE ALSO:

IsValid()

BundleResource(BundleResource const &resource)

Copy constructor.

Parameters

resource -- The object to be copied.

~BundleResource() = default

BundleResource &operator=(BundleResource const &resource) = default

Assignment operator.

Parameters

resource -- The BundleResource object which is assigned to this instance.

Returns

A reference to this BundleResource instance.

bool operator<(BundleResource const &resource) const

A less then operator using the full resource path as returned by GetResourcePath() to define the ordering.

Parameters

resource -- The object to which this BundleResource object is compared to.

Returns

true if this BundleResource object is less then resource, false otherwise.

bool operator==(BundleResource const &resource) const

Equality operator for BundleResource objects.

Parameters

resource -- The object for testing equality.

Returns

true if this BundleResource object is equal to resource, i.e. they are coming from the same bundle (shared or static) and have an equal resource path, false otherwise.

bool operator!=(BundleResource const &resource) const

Inequality operator for BundleResource objects.

Parameters

resource -- The object for testing inequality.

Returns

The result of !(*this == resource).

bool IsValid() const

Tests this BundleResource object for validity.

Invalid BundleResource objects are created by the default constructor or can be returned by the Bundle class if the resource path is not found.

Returns

true if this BundleReource object is valid and can safely be used, false otherwise.

explicit operator bool() const

Boolean conversion operator using IsValid().

std::string GetName() const

Returns the name of the resource, excluding the path.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string name = resource.GetName(); // name = "archive.tar.gz"
SEE ALSO:

GetPath(), GetResourcePath()

Returns

The resource name.

std::string GetPath() const

Returns the resource's path, without the file name.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string path = resource.GetPath(); // path = "/data/"

The path with always begin and end with a forward slash.

SEE ALSO:

GetResourcePath(), GetName() and IsDir()

Returns

The resource path without the name.

std::string GetResourcePath() const

Returns the resource path including the file name.

SEE ALSO:

GetPath(), GetName() and IsDir()

Returns

The resource path including the file name.

std::string GetBaseName() const

Returns the base name of the resource without the path.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string base = resource.GetBaseName(); // base = "archive"
SEE ALSO:

GetName(), GetSuffix(), GetCompleteSuffix() and GetCompleteBaseName()

Returns

The resource base name.

std::string GetCompleteBaseName() const

Returns the complete base name of the resource without the path.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string base = resource.GetCompleteBaseName(); // base = "archive.tar"
SEE ALSO:

GetName(), GetSuffix(), GetCompleteSuffix(), and GetBaseName()

Returns

The resource's complete base name.

std::string GetSuffix() const

Returns the suffix of the resource.

The suffix consists of all characters in the resource name after (but not including) the last '.'.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string suffix = resource.GetSuffix(); // suffix = "gz"
SEE ALSO:

GetName(), GetCompleteSuffix(), GetBaseName() and GetCompleteBaseName()

Returns

The resource name suffix.

std::string GetCompleteSuffix() const

Returns the complete suffix of the resource.

The suffix consists of all characters in the resource name after (but not including) the first '.'.

Example: .INDENT 7.0

BundleResource resource = bundle->GetResource("/data/archive.tar.gz");
std::string suffix = resource.GetCompleteSuffix(); // suffix = "tar.gz"
SEE ALSO:

GetName(), GetSuffix(), GetBaseName(), and GetCompleteBaseName()

Returns

The resource name suffix.

bool IsDir() const

Returns true if this BundleResource object points to a directory and thus may have child resources.

Returns

true if this object points to a directory, false otherwise.

bool IsFile() const

Returns true if this BundleResource object points to a file resource.

Returns

true if this object points to an embedded file, false otherwise.

std::vector<std::string> GetChildren() const

Returns a list of resource names which are children of this object.

The returned names are relative to the path of this BundleResource object and may contain file as well as directory entries.

Returns

A list of child resource names.

std::vector<BundleResource> GetChildResources() const

Returns a list of resource objects which are children of this object.

The returned BundleResource objects may contain files as well as directory resources.

Returns

A list of child resource objects.

int GetSize() const

Returns the (uncompressed) size of the resource data for this BundleResource object.

Returns

The uncompressed resource data size.

int GetCompressedSize() const

Returns the compressed size of the resource data for this BundleResource object.

Returns

The compressed resource data size.

time_t GetLastModified() const

Returns the last modified time of this resource in seconds from the epoch.

Returns

Last modified time of this resource.

uint32_t GetCrc32() const

Returns the CRC-32 checksum of this resource.

Returns

CRC-32 checksum of this resource.

Friends

friend struct ::std::hash< BundleResource >

template<> struct hash<cppmicroservices::BundleResource>

#include <cppmicroservices/BundleResource.h>

Hash functor specialization for BundleResource objects.

BundleResourceStream

class BundleResourceStream : private cppmicroservices::detail::BundleResourceBuffer, public std::istream

An input stream class for BundleResource objects.

This class provides access to the resource data embedded in a bundle's shared library via a STL input stream interface.

SEE ALSO:

BundleResource for an example how to use this class.

Public Functions

BundleResourceStream(BundleResourceStream const&) = delete

BundleResourceStream &operator=(BundleResourceStream const&) = delete

BundleResourceStream(BundleResource const &resource, std::ios_base::openmode mode = std::ios_base::in)

Construct a BundleResourceStream object.

Parameters
  • resource -- The BundleResource object for which an input stream should be constructed.
  • mode -- The open mode of the stream. If std::ios_base::binary is used, the resource data will be treated as binary data, otherwise the data is interpreted as text data and the usual platform specific end-of-line translations take place.

Framework

class Framework : public cppmicroservices::Bundle

A Framework instance.

A Framework is itself a bundle and is known as the "System Bundle". The System Bundle differs from other bundles in the following ways:.INDENT 7.0

·

The system bundle is always assigned a bundle identifier of zero (0).

·

The system bundle GetLocation method returns the string: "System Bundle".

·

The system bundle's life cycle cannot be managed like normal bundles. Its life cycle methods behave as follows:.INDENT 2.0

·

Start - Initialize the framework and start installed bundles.

·

Stop - Stops all installed bundles.

·

Uninstall - The Framework throws a std::runtime_error exception indicating that the system bundle cannot be uninstalled.

Framework instances are created using a FrameworkFactory. The methods of this class can be used to manage and control the created framework instance.

Remark

This class is thread-safe.

SEE ALSO:

FrameworkFactory::NewFramework(const std::map<std::string, Any>& configuration)

Public Functions

explicit Framework(Bundle b)

Convert a Bundle representing the system bundle to a Framework instance.

Parameters

b -- The system bundle

Throws

std::logic_error -- If the bundle is not the system bundle.

Framework(Framework const &fw)

Framework(Framework &&fw) noexcept

Framework &operator=(Framework const &fw)

Framework &operator=(Framework &&fw) noexcept

void Init()

Initialize this Framework.

After calling this method, this Framework has:.INDENT 7.0

·

Generated a new framework UUID.

·

Moved to the STATE_STARTING state.

·

A valid Bundle Context.

·

Event handling enabled.

·

Reified Bundle objects for all installed bundles.

·

Registered any framework services.

This Framework will not actually be started until Start is called.

This method does nothing if called when this Framework is in the STATE_STARTING, STATE_ACTIVE or STATE_STOPPING states.

Throws

std::runtime_error -- If this Framework could not be initialized.

FrameworkEvent WaitForStop(std::chrono::milliseconds const &timeout)

Wait until this Framework has completely stopped.

The Stop method on a Framework performs an asynchronous stop of the Framework if it was built with threading support.

This method can be used to wait until the asynchronous stop of this Framework has completed. This method will only wait if called when this Framework is in the STATE_STARTING, STATE_ACTIVE, or STATE_STOPPING states. Otherwise it will return immediately.

A Framework Event is returned to indicate why this Framework has stopped.

Parameters

timeout -- Maximum time duration to wait until this Framework has completely stopped. A value of zero will wait indefinitely.

Returns

A Framework Event indicating the reason this method returned. The following FrameworkEvent types may be returned by this method. .INDENT 7.0

·

FRAMEWORK_STOPPED - This Framework has been stopped.

·

FRAMEWORK_ERROR - The Framework encountered an error while shutting down or an error has occurred which forced the framework to shutdown.

·

FRAMEWORK_WAIT_TIMEDOUT - This method has timed out and returned before this Framework has stopped.

FrameworkEvent

std::ostream &operator<<(std::ostream &os, FrameworkEvent::Type eventType)

Writes a string representation of eventType to the stream os.

std::ostream &operator<<(std::ostream &os, FrameworkEvent const &evt)

Writes a string representation of evt to the stream os.

bool operator==(FrameworkEvent const &rhs, FrameworkEvent const &lhs)

Compares two framework events for equality.

class FrameworkEvent

#include <cppmicroservices/FrameworkEvent.h>

An event from the Micro Services framework describing a Framework event.

FrameworkEvent objects are delivered to listeners connected via BundleContext::AddFrameworkListener() when an event occurs within the Framework which a user would be interested in. A Type code is used to identify the event type for future extendability.

SEE ALSO:

BundleContext::AddFrameworkListener

Public Types

enum Type

A type code used to identify the event type for future extendability.

Values:

enumerator FRAMEWORK_STARTED

The Framework has started.

This event is fired when the Framework has started after all installed bundles that are marked to be started have been started. The source of this event is the System Bundle.

enumerator FRAMEWORK_ERROR

An error has occurred.

There was an error associated with a bundle.

enumerator FRAMEWORK_WARNING

A warning has occurred.

There was a warning associated with a bundle.

enumerator FRAMEWORK_INFO

An informational event has occurred.

There was an informational event associated with a bundle.

enumerator FRAMEWORK_STOPPED

The Framework has been stopped.

This event is fired when the Framework has been stopped because of a stop operation on the system bundle. The source of this event is the System Bundle.

enumerator FRAMEWORK_STOPPED_UPDATE

The Framework is about to be stopped.

This event is fired when the Framework has been stopped because of an update operation on the system bundle. The Framework will be restarted after this event is fired. The source of this event is the System Bundle.

enumerator FRAMEWORK_WAIT_TIMEDOUT

The Framework did not stop before the wait timeout expired.

This event is fired when the Framework did not stop before the wait timeout expired. The source of this event is the System Bundle.

Public Functions

FrameworkEvent()

Creates an invalid instance.

explicit operator bool() const

Returns false if the FrameworkEvent is empty (i.e invalid) and true if the FrameworkEvent is not null and contains valid data.

Returns

true if this event object is valid, false otherwise.

FrameworkEvent(Type type, Bundle const &bundle, std::string const &message, const std::exception_ptr exception = nullptr)

Creates a Framework event of the specified type.

Parameters
  • type -- The event type.
  • bundle -- The bundle associated with the event. This bundle is also the source of the event.
  • message -- The message associated with the event.
  • exception -- The exception associated with this event. Should be nullptr if there is no exception.
Bundle GetBundle() const

Returns the bundle associated with the event.

Returns

The bundle associated with the event.

std::string GetMessage() const

Returns the message associated with the event.

Returns

the message associated with the event.

std::exception_ptr GetThrowable() const

Returns the exception associated with this event.

Remark

Use std::rethrow_exception to throw the exception returned.

Returns

The exception. May be nullptr if there is no related exception.

Type GetType() const

Returns the type of framework event.

The type values are: .INDENT 7.0

·

FRAMEWORK_STARTED

·

FRAMEWORK_ERROR

·

FRAMEWORK_WARNING

·

FRAMEWORK_INFO

·

FRAMEWORK_STOPPED

·

FRAMEWORK_STOPPED_UPDATE

·

FRAMEWORK_WAIT_TIMEDOUT

Returns

The type of Framework event.

PrototypeServiceFactory

struct PrototypeServiceFactory : public cppmicroservices::ServiceFactory

A factory for prototype scope services.

The factory can provide multiple, unique service objects.

When registering a service, a PrototypeServiceFactory object can be used instead of a service object, so that the bundle developer can create a unique service object for each caller that is using the service. When a caller uses a ServiceObjects to request a service instance, the framework calls the GetService method to return a service object specifically for the requesting caller. The caller can release the returned service object and the framework will call the UngetService method with the service object. When a bundle uses the BundleContext::GetService(const ServiceReferenceBase&) method to obtain a service object, the framework acts as if the service has bundle scope. That is, the framework will call the GetService method to obtain a bundle-scoped instance which will be cached and have a use count. See ServiceFactory.

A bundle can use both ServiceObjects and BundleContext::GetService(const ServiceReferenceBase&) to obtain a service object for a service. ServiceObjects::GetService() will always return an instance provided by a call to GetService(const Bundle&, const ServiceRegistrationBase&) and BundleContext::GetService(const ServiceReferenceBase&) will always return the bundle-scoped instance. PrototypeServiceFactory objects are only used by the framework and are not made available to other bundles. The framework may concurrently call a PrototypeServiceFactory.

SEE ALSO:

BundleContext::GetServiceObjects()

SEE ALSO:

ServiceObjects

Public Functions

virtual InterfaceMapConstPtr GetService(Bundle const &bundle, ServiceRegistrationBase const &registration) override = 0

Returns a service object for a caller.

The framework invokes this method for each caller requesting a service object using ServiceObjects::GetService(). The factory can then return a specific service object for the caller. The framework checks that the returned service object is valid. If the returned service object is empty or does not contain entries for all the interfaces named when the service was registered, a warning is issued and nullptr is returned to the caller. If this method throws an exception, a warning is issued and nullptr is returned to the caller.

SEE ALSO:

ServiceObjects::GetService()

SEE ALSO:

InterfaceMapConstPtr

Parameters
  • bundle -- The bundle requesting the service.
  • registration -- The ServiceRegistrationBase object for the requested service.
Returns

A service object that must contain entries for all the interfaces named when the service was registered.

virtual void UngetService(Bundle const &bundle, ServiceRegistrationBase const &registration, InterfaceMapConstPtr const &service) override = 0

Releases a service object created for a caller.

The framework invokes this method when a service has been released by a bundles such as by calling ServiceObjects::UngetService(). The service object may then be destroyed. If this method throws an exception, a warning is issued.

SEE ALSO:

ServiceObjects::UngetService()

Parameters
  • bundle -- The bundle releasing the service.
  • registration -- The ServiceRegistrationBase object for the service being released.
  • service -- The service object returned by a previous call to the GetService method.

ServiceEvent

std::ostream &operator<<(std::ostream &os, ServiceEvent::Type const &type)

Writes a string representation of type to the stream os.

std::ostream &operator<<(std::ostream &os, ServiceEvent const &event)

Writes a string representation of event to the stream os.

class ServiceEvent

#include <cppmicroservices/ServiceEvent.h>

An event from the Micro Services framework describing a service lifecycle change.

ServiceEvent objects are delivered to listeners connected via BundleContext::AddServiceListener() when a change occurs in this service's lifecycle. A type code is used to identify the event type for future extendability.

Public Types

enum Type

The service event type.

Values:

enumerator SERVICE_REGISTERED

This service has been registered.

This event is delivered after the service has been registered with the framework.

SEE ALSO:

BundleContext::RegisterService

enumerator SERVICE_MODIFIED

The properties of a registered service have been modified.

This event is delivered after the service properties have been modified.

SEE ALSO:

ServiceRegistration::SetProperties

enumerator SERVICE_UNREGISTERING

This service is in the process of being unregistered.

This event is delivered before the service has completed unregistering.

If a bundle is using a service that is SERVICE_UNREGISTERING, the bundle should release its use of the service when it receives this event. If the bundle does not release its use of the service when it receives this event, the framework will automatically release the bundle's use of the service while completing the service unregistration operation.

SEE ALSO:

ServiceRegistration::Unregister

enumerator SERVICE_MODIFIED_ENDMATCH

The properties of a registered service have been modified and the new properties no longer match the listener's filter.

This event is delivered after the service properties have been modified. This event is only delivered to listeners which were added with a non-empty filter where the filter matched the service properties prior to the modification but the filter does not match the modified service properties.

SEE ALSO:

ServiceRegistration::SetProperties

Public Functions

ServiceEvent()

Creates an invalid instance.

explicit operator bool() const

Can be used to check if this ServiceEvent instance is valid, or if it has been constructed using the default constructor.

Returns

true if this event object is valid, false otherwise.

ServiceEvent(Type type, ServiceReferenceBase const &reference)

Creates a new service event object.

Parameters
  • type -- The event type.
  • reference -- A ServiceReference object to the service that had a lifecycle change.

ServiceEvent(ServiceEvent const &other)

ServiceEvent &operator=(ServiceEvent const &other)

ServiceReferenceU GetServiceReference() const

Returns a reference to the service that had a change occur in its lifecycle.

This reference is the source of the event.

Returns

Reference to the service that had a lifecycle change.

template<class S> inline ServiceReference<S> GetServiceReference() const

Type GetType() const

Returns the type of event.

The event type values are: .INDENT 7.0

·

SERVICE_REGISTERED

·

SERVICE_MODIFIED

·

SERVICE_MODIFIED_ENDMATCH

·

SERVICE_UNREGISTERING

Returns

Type of service lifecycle change.

ServiceEventListenerHook

struct ServiceEventListenerHook

Service Event Listener Hook Service.

Bundles registering this service will be called during service (register, modify, and unregister service) operations.

Remark

Implementations of this interface are required to be thread-safe.

Public Types

using ShrinkableMapType = ShrinkableMap<BundleContext, ShrinkableVector<ServiceListenerHook::ListenerInfo>>

ShrinkableMap type for filtering event listeners.

Public Functions

virtual ~ServiceEventListenerHook()

virtual void Event(ServiceEvent const &event, ShrinkableMapType &listeners) = 0

Event listener hook method.

This method is called prior to service event delivery when a publishing bundle registers, modifies or unregisters a service. This method can filter the listeners which receive the event.

Parameters
  • event -- The service event to be delivered.
  • listeners -- A map of Bundle Contexts to a list of Listener Infos for the bundle's listeners to which the specified event will be delivered. The implementation of this method may remove bundle contexts from the map and listener infos from the list values to prevent the event from being delivered to the associated listeners.

ServiceException

std::ostream &operator<<(std::ostream &os, cppmicroservices::ServiceException const &exc)

Writes a string representation of exc to the stream os.

class ServiceException : public std::runtime_error

#include <cppmicroservices/ServiceException.h>

A service exception used to indicate that a service problem occurred.

A ServiceException object is created by the framework or to denote an exception condition in the service. An enum type is used to identify the exception type for future extendability.

This exception conforms to the general purpose exception chaining mechanism.

Public Types

enum Type

Values:

enumerator UNSPECIFIED

No exception type is unspecified.

enumerator UNREGISTERED

The service has been unregistered.

enumerator FACTORY_ERROR

The service factory produced an invalid service object.

enumerator FACTORY_EXCEPTION

The service factory threw an exception.

enumerator REMOTE

An error occurred invoking a remote service.

enumerator FACTORY_RECURSION

The service factory resulted in a recursive call to itself for the requesting bundle.

Public Functions

ServiceException(std::string const &msg, Type const &type = UNSPECIFIED)

Creates a ServiceException with the specified message, type and exception cause.

Parameters
  • msg -- The associated message.
  • type -- The type for this exception.

ServiceException(ServiceException const &o)

ServiceException &operator=(ServiceException const &o)

~ServiceException() override

Type GetType() const

Returns the type for this exception or UNSPECIFIED if the type was unspecified or unknown.

Returns

The type of this exception.

ServiceFactory

class ServiceFactory

A factory for bundle scope services.

The factory can provide service objects unique to each bundle.

When registering a service, a ServiceFactory object can be used instead of a service object, so that the bundle developer can create a customized service object for each bundle that is using the service.

When a bundle requests the service object, the framework calls the ServiceFactory::GetService method to return a service object customized for the requesting bundle. The returned service object is cached by the framework for subsequent calls to BundleContext::GetService(const ServiceReference&) until the bundle releases its use of the service.

When the bundle's use count for the service is decremented to zero (including the bundle stopping or the service being unregistered), the framework will call the ServiceFactory::UngetService method.

ServiceFactory objects are only used by the framework and are not made available to other bundles in the bundle environment. The framework may concurrently call a ServiceFactory.

SEE ALSO:

BundleContext::GetService

SEE ALSO:

PrototypeServiceFactory

Remark

This class is thread safe.

Subclassed by cppmicroservices::PrototypeServiceFactory

Public Functions

virtual ~ServiceFactory() = default

virtual InterfaceMapConstPtr GetService(Bundle const &bundle, ServiceRegistrationBase const &registration) = 0

Returns a service object for a bundle.

The framework invokes this method the first time the specified bundle requests a service object using the BundleContext::GetService(const ServiceReferenceBase&) method. The factory can then return a customized service object for each bundle.

The framework checks that the returned service object is valid. If the returned service object is null or does not contain entries for all the classes named when the service was registered, a framework event of type FrameworkEvent::FRAMEWORK_ERROR is fired containing a service exception of type ServiceException::FACTORY_ERROR and null is returned to the bundle. If this method throws an exception, a framework event of type FrameworkEvent::FRAMEWORK_ERROR is fired containing a service exception of type ServiceException::FACTORY_EXCEPTION with the thrown exception as a nested exception and null is returned to the bundle. If this method is recursively called for the specified bundle, a framework event of type FrameworkEvent::FRAMEWORK_ERROR is fired containing a service exception of type ServiceException::FACTORY_RECURSION and null is returned to the bundle.

The framework caches the valid service object, and will return the same service object on any future call to BundleContext::GetService for the specified bundle. This means the framework does not allow this method to be concurrently called for the specified bundle.

SEE ALSO:

BundleContext::GetService

SEE ALSO:

InterfaceMapConstPtr

Parameters
  • bundle -- The bundle requesting the service.
  • registration -- The ServiceRegistrationBase object for the requested service.
Returns

A service object that must contain entries for all the interfaces named when the service was registered.

virtual void UngetService(Bundle const &bundle, ServiceRegistrationBase const &registration, InterfaceMapConstPtr const &service) = 0

Releases a service object customized for a bundle.

The Framework invokes this method when a service has been released by a bundle. If this method throws an exception, a framework event of type FrameworkEvent::FRAMEWORK_ERROR is fired containing a service exception of type ServiceException::FACTORY_EXCEPTION with the thrown exception as a nested exception.

SEE ALSO:

InterfaceMapConstPtr

Parameters
  • bundle -- The Bundle releasing the service.
  • registration -- The ServiceRegistration object for the service being released.
  • service -- The service object returned by a previous call to the ServiceFactory::GetService method.

ServiceFindHook

struct ServiceFindHook

Service Find Hook Service.

Bundles registering this service will be called during service find (get service references) operations.

Remark

Implementations of this interface are required to be thread-safe.

Public Functions

virtual ~ServiceFindHook()

virtual void Find(BundleContext const &context, std::string const &name, std::string const &filter, ShrinkableVector<ServiceReferenceBase> &references) = 0

Find hook method.

This method is called during the service find operation (for example, BundleContext::GetServiceReferences<S>()). This method can filter the result of the find operation.

Parameters
  • context -- The bundle context of the bundle performing the find operation.
  • name -- The class name of the services to find or an empty string to find all services.
  • filter -- The filter criteria of the services to find or an empty string for no filter criteria.
  • references -- A list of Service References to be returned as a result of the find operation. The implementation of this method may remove service references from the list to prevent the references from being returned to the bundle performing the find operation.

ServiceInterface

template<class T> std::shared_ptr<ServiceFactory> ToFactory(std::shared_ptr<T> const &factory)

Cast the argument to a shared pointer of type ServiceFactory.

Useful when calling BundleContext::RegisterService with a service factory, for example:

std::shared_ptr<MyServiceFactory> factory = std::make_shared<MyServiceFactory>();
context->RegisterService<ISomeInterface>(ToFactory(factory));
SEE ALSO:

BundleContext::RegisterService(ServiceFactory* factory, const ServiceProperties& properties)

Parameters

factory -- The service factory shared_ptr object

Returns

A shared_ptr object of type ServiceFactory

using InterfaceMap = std::unordered_map<std::string, std::shared_ptr<void>>

A map containing interfaces ids and their corresponding service object smart pointers.

InterfaceMap instances represent a complete service object which implements one or more service interfaces. For each implemented service interface, there is an entry in the map with the key being the service interface id and the value a smart pointer to the service interface implementation.

To create InterfaceMap instances, use the MakeInterfaceMap helper class.

SEE ALSO:

MakeInterfaceMap

NOTE:

This is a low-level type and should only rarely be used.

template<class T> std::string const &us_service_interface_iid()

Returns a unique id for a given type.

By default, the demangled name of T is returned.

This template method may be specialized directly or by using the macro Cppmicroservices_declare_service_interface to return a custom id for each service interface.

Template Parameters

T -- The service interface type.

Returns

A unique id for the service interface type T.

template<class Interface> std::shared_ptr<Interface> ExtractInterface(InterfaceMapConstPtr const &map)

Extract a service interface pointer from a given InterfaceMap instance.

SEE ALSO:

MakeInterfaceMap

Parameters

map -- a InterfaceMap instance.

Returns

A shared pointer object of type Interface. The returned object is empty if the map does not contain an entry for the given type

inline std::shared_ptr<void> ExtractInterface(InterfaceMapConstPtr const &map, std::string const &interfaceId)

Extract a service interface pointer from a given InterfaceMap instance.

SEE ALSO:

ExtractInterface(const InterfaceMapConstPtr&)

Parameters
  • map -- a InterfaceMap instance.
  • interfaceId -- The interface id string.
Returns

The service interface pointer for the service interface id or nullptr if map does not contain an entry for the given type.

template<class ...Interfaces> class MakeInterfaceMap

#include <cppmicroservices/ServiceInterface.h>

Helper class for constructing InterfaceMap instances based on service implementations or service factories.

Example usage: .INDENT 7.0

std::shared_ptr<MyService> service; // implementes I1 and I2
InterfaceMap im = MakeInterfaceMap<I1,I2>(service);
SEE ALSO:

InterfaceMap

Public Functions

template<class Impl> inline MakeInterfaceMap(std::shared_ptr<Impl> const &impl)

Constructor taking a service implementation pointer.

Parameters

impl -- A service implementation pointer, which must be castable to a all specified service interfaces.

inline MakeInterfaceMap(std::shared_ptr<ServiceFactory> factory)

Constructor taking a service factory.

Parameters

factory -- A service factory.

inline operator InterfaceMapPtr()

inline operator InterfaceMapConstPtr()

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id)

Declare a service interface id.

This macro associates the given identifier _service_interface_id (a string literal) to the interface class called _service_interface_type. The Identifier must be unique. For example:

#include "cppmicroservices/ServiceInterface.h"

struct ISomeInterace { ... };

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0")

The usage of this macro is optional and the service interface id which is automatically associated with any type is usually good enough (the demangled type name). However, care must be taken if the default id is compared with a string literal hard-coding a service interface id. E.g. the default id for templated types in the STL may differ between platforms. For user-defined types and templates the ids are typically consistent, but platform specific default template arguments will lead to different ids.

This macro is normally used right after the class definition for _service_interface_type, in a header file.

If you want to use Cppmicroservices_declare_service_interface with interface classes declared in a namespace then you have to make sure the Cppmicroservices_declare_service_interface macro call is not inside a namespace though. For example:

#include "cppmicroservices/ServiceInterface.h"

namespace Foo
{
  struct ISomeInterface { ... };
}

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0")
Parameters
  • _service_interface_type -- The service interface type.
  • _service_interface_id -- A string literal representing a globally unique identifier.

ServiceListenerHook

struct ServiceListenerHook

#include <cppmicroservices/ServiceListenerHook.h>

Service Listener Hook Service.

Bundles registering this service will be called during service listener addition and removal.

Remark

Implementations of this interface are required to be thread-safe.

Public Functions

virtual ~ServiceListenerHook()

virtual void Added(std::vector<ListenerInfo> const &listeners) = 0

Added listeners hook method.

This method is called to provide the hook implementation with information on newly added service listeners. This method will be called as service listeners are added while this hook is registered. Also, immediately after registration of this hook, this method will be called to provide the current collection of service listeners which had been added prior to the hook being registered.

Parameters

listeners -- A collection of ListenerInfo objects for newly added service listeners which are now listening to service events.

virtual void Removed(std::vector<ListenerInfo> const &listeners) = 0

Removed listeners hook method.

This method is called to provide the hook implementation with information on newly removed service listeners. This method will be called as service listeners are removed while this hook is registered.

Parameters

listeners -- A collection of ListenerInfo objects for newly removed service listeners which are no longer listening to service events.

struct ListenerInfo

#include <cppmicroservices/ServiceListenerHook.h>

Information about a Service Listener.

This class describes the bundle which added the Service Listener and the filter with which it was added.

Remark

This class is not intended to be implemented by clients.

Public Functions

ListenerInfo()

ListenerInfo(ListenerInfo const &other)

~ListenerInfo()

ListenerInfo &operator=(ListenerInfo const &other)

bool IsNull() const

Can be used to check if this ListenerInfo instance is valid, or if it has been constructed using the default constructor.

Returns

true if this listener object is valid, false otherwise.

BundleContext GetBundleContext() const

Return the context of the bundle which added the listener.

Returns

The context of the bundle which added the listener.

std::string GetFilter() const

Return the filter string with which the listener was added.

Returns

The filter string with which the listener was added. This may be empty if the listener was added without a filter.

bool IsRemoved() const

Return the state of the listener for this addition and removal life cycle.

Initially this method will return false indicating the listener has been added but has not been removed. After the listener has been removed, this method must always returns true.

There is an extremely rare case in which removed notification to ServiceListenerHooks can be made before added notification if two threads are racing to add and remove the same service listener. Because ServiceListenerHooks are called synchronously during service listener addition and removal, the CppMicroServices library cannot guarantee in-order delivery of added and removed notification for a given service listener. This method can be used to detect this rare occurrence.

Returns

false if the listener has not been been removed, true otherwise.

bool operator==(ListenerInfo const &other) const

Compares this ListenerInfo to another ListenerInfo.

Two ListenerInfos are equal if they refer to the same listener for a given addition and removal life cycle. If the same listener is added again, it will have a different ListenerInfo which is not equal to this ListenerInfo.

Parameters

other -- The object to compare against this ListenerInfo.

Returns

true if the other object is a ListenerInfo object and both objects refer to the same listener for a given addition and removal life cycle.

Friends

friend struct ::std::hash< ServiceListenerHook::ListenerInfo >

template<> struct hash<cppmicroservices::ServiceListenerHook::ListenerInfo>

#include <ServiceListenerHook.h>

<cppmicroservices/ServiceListenerHook.h>

Hash functor specialization for ServiceListenerHook::ListenerInfo objects.

ServiceObjects

template<class S> class ServiceObjects : private cppmicroservices::ServiceObjectsBase

#include <cppmicroservices/ServiceObjects.h>

Allows multiple service objects for a service to be obtained.

For services with prototype scope, multiple service objects for the service can be obtained. For services with singleton or bundle scope, only one, use-counted service object is available. Any unreleased service objects obtained from this ServiceObjects object are automatically released by the framework when the bundles associated with the BundleContext used to create this ServiceObjects object is stopped.

Template Parameters

S -- Type of Service.

Public Functions

ServiceObjects(ServiceObjects const &other) = delete

ServiceObjects &operator=(ServiceObjects const &other) = delete

inline ServiceObjects(ServiceObjects &&other)

inline ServiceObjects &operator=(ServiceObjects &&other)

inline std::shared_ptr<S> GetService() const

Returns a service object for the referenced service.

This ServiceObjects object can be used to obtain multiple service objects for the referenced service if the service has prototype scope. If the referenced service has singleton or bundle scope, this method behaves the same as calling the BundleContext::GetService(const ServiceReferenceBase&) method for the referenced service. That is, only one, use-counted service object is available from this ServiceObjects object.

This method will always return nullptr when the referenced service has been unregistered.

For a prototype scope service, the following steps are taken to get the service object:

i.

If the referenced service has been unregistered, nullptr is returned.

ii.

The PrototypeServiceFactory::GetService(const Bundle&, const ServiceRegistrationBase&) method is called to create a service object for the caller.

iii.

If the service object (an instance of InterfaceMap) returned by the PrototypeServiceFactory object is empty, does not contain all the interfaces named when the service was registered or the PrototypeServiceFactory object throws an exception, nullptr is returned and a warning message is issued.

iv.

The service object is returned.

Throws

std::logic_error -- If the BundleContext used to create this ServiceObjects object is no longer valid.

Returns

A shared_ptr to the service object. The returned shared_ptr is empty if the service is not registered, the service object returned by a ServiceFactory does not contain all the classes under which it was registered or the ServiceFactory threw an exception.

inline ServiceReference<S> GetServiceReference() const

Returns the ServiceReference for this ServiceObjects object.

Returns

The ServiceReference for this ServiceObjects object.

template<> class ServiceObjects<void> : private cppmicroservices::ServiceObjectsBase, private cppmicroservices::ServiceObjectsBase

#include <cppmicroservices/ServiceObjects.h>

Allows multiple service objects for a service to be obtained.

This is a specialization of the ServiceObjects class template for void, which maps to all service interface types.

SEE ALSO:

ServiceObjects

Public Functions

ServiceObjects(ServiceObjects const &other) = delete

ServiceObjects &operator=(ServiceObjects const &other) = delete

ServiceObjects(ServiceObjects &&other) noexcept

ServiceObjects &operator=(ServiceObjects &&other) noexcept

InterfaceMapConstPtr GetService() const

Returns a service object as a InterfaceMap instance for the referenced service.

This method is the same as ServiceObjects<S>::GetService() except for the return type. Further, this method will always return an empty InterfaceMap object when the referenced service has been unregistered.

SEE ALSO:

ServiceObjects<S>::GetService()

Throws

std::logic_error -- If the BundleContext used to create this ServiceObjects object is no longer valid.

Returns

A InterfaceMapConstPtr object for the referenced service, which is empty if the service is not registered, the InterfaceMap returned by a ServiceFactory does not contain all the classes under which the service object was registered or the ServiceFactory threw an exception.

ServiceReferenceU GetServiceReference() const

Returns the ServiceReference for this ServiceObjects object.

Returns

The ServiceReference for this ServiceObjects object.

ServiceObjects(ServiceObjects const &other) = delete

inline ServiceObjects(ServiceObjects &&other)

ServiceObjects &operator=(ServiceObjects const &other) = delete

inline ServiceObjects &operator=(ServiceObjects &&other)

inline std::shared_ptr<void> GetService() const

Returns a service object for the referenced service.

This ServiceObjects object can be used to obtain multiple service objects for the referenced service if the service has prototype scope. If the referenced service has singleton or bundle scope, this method behaves the same as calling the BundleContext::GetService(const ServiceReferenceBase&) method for the referenced service. That is, only one, use-counted service object is available from this ServiceObjects object.

This method will always return nullptr when the referenced service has been unregistered.

For a prototype scope service, the following steps are taken to get the service object:

i.

If the referenced service has been unregistered, nullptr is returned.

ii.

The PrototypeServiceFactory::GetService(const Bundle&, const ServiceRegistrationBase&) method is called to create a service object for the caller.

iii.

If the service object (an instance of InterfaceMap) returned by the PrototypeServiceFactory object is empty, does not contain all the interfaces named when the service was registered or the PrototypeServiceFactory object throws an exception, nullptr is returned and a warning message is issued.

iv.

The service object is returned.

Throws

std::logic_error -- If the BundleContext used to create this ServiceObjects object is no longer valid.

Returns

A shared_ptr to the service object. The returned shared_ptr is empty if the service is not registered, the service object returned by a ServiceFactory does not contain all the classes under which it was registered or the ServiceFactory threw an exception.

inline ServiceReference<void> GetServiceReference() const

Returns the ServiceReference for this ServiceObjects object.

Returns

The ServiceReference for this ServiceObjects object.

ServiceReference

typedef ServiceReference<void> ServiceReferenceU

A service reference of unknown type, which is not bound to any interface identifier.

US_Framework_EXPORT ServiceReferenceU ServiceReferenceFromService (std::shared_ptr< void > const &s)

A method to retrieve a ServiceObject's original ServiceReference<void>

template<typename T, typename U = T> ServiceReference<U> ServiceReferenceFromService(std::shared_ptr<T> const &s)

A method to retrieve a ServiceObject<T>'s original ServiceReference

Template Parameters
  • T -- The class type of the ServiceObject
  • U -- The class type of the ServiceReference. Defaults to T if not specified.
std::ostream &operator<<(std::ostream &os, ServiceReferenceBase const &serviceRef)

Writes a string representation of serviceRef to the stream os.

template<class S> class ServiceReference : public cppmicroservices::ServiceReferenceBase

#include <cppmicroservices/ServiceReference.h>

A reference to a service.

The framework returns ServiceReference objects from the BundleContext::GetServiceReference and BundleContext::GetServiceReferences methods.

A ServiceReference object may be shared between bundles and can be used to examine the properties of the service and to get the service object.

Every service registered in the framework has a unique ServiceRegistration object and may have multiple, distinct ServiceReference objects referring to it. ServiceReference objects associated with a ServiceRegistration are considered equal (more specifically, their operator==() method will return true when compared).

If the same service object is registered multiple times, ServiceReference objects associated with different ServiceRegistration objects are not equal.

SEE ALSO:

BundleContext::GetServiceReference

SEE ALSO:

BundleContext::GetServiceReferences

SEE ALSO:

BundleContext::GetService

Template Parameters

S -- The class type of the service interface

Public Types

using ServiceType = S

Public Functions

inline ServiceReference()

Creates an invalid ServiceReference object.

You can use this object in boolean expressions and it will evaluate to false.

ServiceReference(ServiceReference const&) = default

ServiceReference &operator=(ServiceReference const&) = default

inline ServiceReference(ServiceReferenceBase const &base)

ServiceReferenceBase &operator=(std::nullptr_t)

Releases any resources held or locked by this ServiceReferenceBase and renders it invalid.

ServiceReferenceBase &operator=(ServiceReferenceBase const &reference)

bool operator==(ServiceReferenceBase const &reference) const

class ServiceReferenceBase

#include <cppmicroservices/ServiceReferenceBase.h>

A reference to a service.

NOTE:

This class is provided as public API for low-level service queries only. In almost all cases you should use the template ServiceReference instead.

Subclassed by cppmicroservices::ServiceReference< void >, cppmicroservices::ServiceReference< cppmicroservices::service::cm::ConfigurationAdmin >, cppmicroservices::ServiceReference< S >

Public Functions

ServiceReferenceBase(ServiceReferenceBase const &ref)

explicit operator bool() const

Converts this ServiceReferenceBase instance into a boolean expression.

If this instance was default constructed or the service it references has been unregistered, the conversion returns false, otherwise it returns true.

ServiceReferenceBase &operator=(std::nullptr_t)

Releases any resources held or locked by this ServiceReferenceBase and renders it invalid.

~ServiceReferenceBase()

Any GetProperty(std::string const &key) const

Returns the property value to which the specified property key is mapped in the properties ServiceProperties object of the service referenced by this ServiceReferenceBase object.

Property keys are case-insensitive.

This method continues to return property values after the service has been unregistered. This is so references to unregistered services can still be interrogated.

Parameters

key -- The property key.

Returns

The property value to which the key is mapped; an invalid Any if there is no property named after the key.

void GetPropertyKeys(std::vector<std::string> &keys) const

Returns a list of the keys in the ServiceProperties object of the service referenced by this ServiceReferenceBase object.

This method will continue to return the keys after the service has been unregistered. This is so references to unregistered services can still be interrogated.

Deprecated:

Since 3.0, use GetPropertyKeys() instead.

Parameters

keys -- A vector being filled with the property keys.

std::vector<std::string> GetPropertyKeys() const

Returns a list of the keys in the ServiceProperties object of the service referenced by this ServiceReferenceBase object.

This method will continue to return the keys after the service has been unregistered. This is so references to unregistered services can still be interrogated.

Returns

A vector being filled with the property keys.

Bundle GetBundle() const

Returns the bundle that registered the service referenced by this ServiceReferenceBase object.

This method must return an invalid bundle when the service has been unregistered. This can be used to determine if the service has been unregistered.

SEE ALSO:

BundleContext::RegisterService(const InterfaceMap&, const ServiceProperties&)

SEE ALSO:

Bundle::operator bool() const

Returns

The bundle that registered the service referenced by this ServiceReferenceBase object; an invalid bundle if that service has already been unregistered.

std::vector<Bundle> GetUsingBundles() const

Returns the bundles that are using the service referenced by this ServiceReferenceBase object.

Specifically, this method returns the bundles whose usage count for that service is greater than zero.

Returns

A list of bundles whose usage count for the service referenced by this ServiceReferenceBase object is greater than zero.

std::string GetInterfaceId() const

Returns the interface identifier this ServiceReferenceBase object is bound to.

A default constructed ServiceReferenceBase object is not bound to any interface identifier and calling this method will return an empty string.

Returns

The interface identifier for this ServiceReferenceBase object.

bool IsConvertibleTo(std::string const &interfaceid) const

Checks whether this ServiceReferenceBase object can be converted to another ServiceReferenceBase object, which will be bound to the given interface identifier.

ServiceReferenceBase objects can be converted if the underlying service implementation was registered under multiple service interfaces.

Parameters

interfaceid --

Returns

true if this ServiceReferenceBase object can be converted, false otherwise.

bool operator<(ServiceReferenceBase const &reference) const

Compares this ServiceReferenceBase with the specified ServiceReferenceBase for order.

If this ServiceReferenceBase and the specified ServiceReferenceBase have the same service id they are equal. This ServiceReferenceBase is less than the specified ServiceReferenceBase if it has a lower service ranking and greater if it has a higher service ranking. Otherwise, if this ServiceReferenceBase and the specified ServiceReferenceBase have the same service ranking, this ServiceReferenceBase is less than the specified ServiceReferenceBase if it has a higher service id and greater if it has a lower service id.

Parameters

reference -- The ServiceReferenceBase to be compared.

Returns

Returns a false or true if this ServiceReferenceBase is less than or greater than the specified ServiceReferenceBase.

bool operator==(ServiceReferenceBase const &reference) const

ServiceReferenceBase &operator=(ServiceReferenceBase const &reference)

Friends

friend struct ::std::hash< ServiceReferenceBase >

template<> struct hash<cppmicroservices::ServiceReferenceBase>

#include <ServiceReferenceBase.h>

<cppmicroservices/ServiceReferenceBase.h>

Hash functor specialization for ServiceReferenceBase objects.

ServiceRegistration

template<class I1, class ...Interfaces> class ServiceRegistration : public cppmicroservices::ServiceRegistrationBase

#include <cppmicroservices/ServiceRegistration.h>

A registered service.

The framework returns a ServiceRegistration object when a BundleContext::RegisterService() method invocation is successful. The ServiceRegistration object is for the private use of the registering bundle and should not be shared with other bundles.

The ServiceRegistration object may be used to update the properties of the service or to unregister the service.

SEE ALSO:

BundleContext::RegisterService()

Template Parameters
  • I1 -- Class type of the first service interface
  • Interfaces -- Template parameter pack containing zero or more service interfaces

Public Functions

inline ServiceRegistration()

Creates an invalid ServiceRegistration object.

You can use this object in boolean expressions and it will evaluate to false.

template<class Interface> inline ServiceReference<Interface> GetReference() const

Returns a ServiceReference object for a service being registered.

The ServiceReference object may be shared with other bundles.

Throws

std::logic_error -- If this ServiceRegistration object has already been unregistered or if it is invalid.

Returns

ServiceReference object.

inline ServiceReference<I1> GetReference() const

Returns a ServiceReference object for a service being registered.

The ServiceReference object refers to the first interface type and may be shared with other bundles.

Throws

std::logic_error -- If this ServiceRegistration object has already been unregistered or if it is invalid.

Returns

ServiceReference object.

ServiceRegistrationBase &operator=(std::nullptr_t)

Releases any resources held or locked by this ServiceRegistrationBase and renders it invalid.

Returns

This ServiceRegistrationBase object.

ServiceRegistrationBase &operator=(ServiceRegistrationBase const &registration)

ServiceRegistrationBase &operator=(ServiceRegistrationBase &&registration) noexcept

class ServiceRegistrationBase

#include <cppmicroservices/ServiceRegistrationBase.h>

A registered service.

The framework returns a ServiceRegistrationBase object when a BundleContext::RegisterService() method invocation is successful. The ServiceRegistrationBase object is for the private use of the registering bundle and should not be shared with other bundles.

The ServiceRegistrationBase object may be used to update the properties of the service or to unregister the service.

SEE ALSO:

BundleContext::RegisterService()

NOTE:

This class is provided as public API for low-level service management only. In almost all cases you should use the template ServiceRegistration instead.

Subclassed by cppmicroservices::ServiceRegistration< void >, cppmicroservices::ServiceRegistration< cppmicroservices::HttpServlet >, cppmicroservices::ServiceRegistration< I1, Interfaces >

Public Functions

ServiceRegistrationBase(ServiceRegistrationBase const &reg)

ServiceRegistrationBase(ServiceRegistrationBase &&reg) noexcept

explicit operator bool() const

A boolean conversion operator converting this ServiceRegistrationBase object to true if it is valid and to false otherwise.

A ServiceRegistrationBase object is invalid if it was default-constructed or was invalidated by assigning 0 to it.

SEE ALSO:

operator=(std::nullptr_t)

Returns

true if this ServiceRegistrationBase object is valid, false otherwise.

ServiceRegistrationBase &operator=(std::nullptr_t)

Releases any resources held or locked by this ServiceRegistrationBase and renders it invalid.

Returns

This ServiceRegistrationBase object.

~ServiceRegistrationBase()

ServiceReferenceBase GetReference(std::string const &interfaceId = std::string()) const

Returns a ServiceReferenceBase object for a service being registered.

The ServiceReferenceBase object may be shared with other bundles.

Throws

std::logic_error -- If this ServiceRegistrationBase object has already been unregistered or if it is invalid.

Returns

ServiceReference object.

void SetProperties(ServiceProperties const &properties)

Updates the properties associated with a service.

The Constants::OBJECTCLASS and Constants::SERVICE_ID keys cannot be modified by this method. These values are set by the framework when the service is registered in the environment.

The following steps are taken to modify service properties: .INDENT 7.0

i.

The service's properties are replaced with the provided properties.

ii.

A service event of type ServiceEvent::SERVICE_MODIFIED is fired.

Parameters

properties -- The properties for this service. See ServiceProperties for a list of standard service property keys. Changes should not be made to this object after calling this method. To update the service's properties this method should be called again.

Throws
  • std::logic_error -- If this ServiceRegistrationBase object has already been unregistered or if it is invalid.
  • std::invalid_argument -- If properties contains case variants of the same key name or if the number of the keys of properties exceeds the value returned by std::numeric_limits<int>::max().

void SetProperties(ServiceProperties &&properties)

void Unregister()

Unregisters a service.

Remove a ServiceRegistrationBase object from the framework service registry. All ServiceRegistrationBase objects associated with this ServiceRegistrationBase object can no longer be used to interact with the service once unregistration is complete.

The following steps are taken to unregister a service: .INDENT 7.0

i.

The service is removed from the framework service registry so that it can no longer be obtained.

ii.

A service event of type ServiceEvent::SERVICE_UNREGISTERING is fired so that bundles using this service can release their use of the service. Once delivery of the service event is complete, the ServiceRegistrationBase objects for the service may no longer be used to get a service object for the service.

iii.

For each bundle whose use count for this service is greater than zero:

The bundle's use count for this service is set to zero.

If the service was registered with a ServiceFactory object, the ServiceFactory::UngetService method is called to release the service object for the bundle.

Throws

std::logic_error -- If this ServiceRegistrationBase object has already been unregistered or if it is invalid.

bool operator<(ServiceRegistrationBase const &o) const

Compare two ServiceRegistrationBase objects.

If both ServiceRegistrationBase objects are valid, the comparison is done using the underlying ServiceReference object. Otherwise, this ServiceRegistrationBase object is less than the other object if and only if this object is invalid and the other object is valid.

Parameters

o -- The ServiceRegistrationBase object to compare with.

Returns

true if this ServiceRegistrationBase object is less than the other object.

bool operator==(ServiceRegistrationBase const &registration) const

ServiceRegistrationBase &operator=(ServiceRegistrationBase const &registration)

ServiceRegistrationBase &operator=(ServiceRegistrationBase &&registration) noexcept

Friends

friend struct ::std::hash< ServiceRegistrationBase >

template<> struct hash<cppmicroservices::ServiceRegistrationBase>

#include <ServiceRegistrationBase.h>

<cppmicroservices/ServiceRegistrationBase.h>

Hash functor specialization for ServiceRegistrationBase objects.

ServiceTracker

template<class S, class T = S> class ServiceTracker : protected cppmicroservices::ServiceTrackerCustomizer<S, S>

#include <cppmicroservices/ServiceTracker.h>

The ServiceTracker class simplifies using services from the framework's service registry.

A ServiceTracker object is constructed with search criteria and a ServiceTrackerCustomizer object. A ServiceTracker can use a ServiceTrackerCustomizer to customize the service objects to be tracked. The ServiceTracker can then be opened to begin tracking all services in the framework's service registry that match the specified search criteria. The ServiceTracker correctly handles all of the details of listening to ServiceEvents and getting and ungetting services.

The GetServiceReferences method can be called to get references to the services being tracked. The GetService and GetServices methods can be called to get the service objects for the tracked service.

Customization of the services to be tracked requires the tracked type to be default constructible and convertible to bool. To customize a tracked service using a custom type with value-semantics like .INDENT 7.0

struct MyTrackedClass
{
    explicit operator bool() const { return true; }
    /* ... */
};

a custom ServiceTrackerCustomizer is required. It provides code to associate the tracked service with the custom tracked type: .INDENT 7.0

struct MyTrackingCustomizer : public ServiceTrackerCustomizer<IFooService, MyTrackedClass>
{
    virtual std::shared_ptr<MyTrackedClass>
    AddingService(ServiceReference<IFooService> const&)
    {
        return std::shared_ptr<MyTrackedClass>();
    }

    virtual void
    ModifiedService(ServiceReference<IFooService> const&, std::shared_ptr<MyTrackedClass> const&)
    {
    }

    virtual void
    RemovedService(ServiceReference<IFooService> const&, std::shared_ptr<MyTrackedClass> const&)
    {
    }
};

Instantiation of a ServiceTracker with the custom customizer looks like this: .INDENT 7.0

        MyTrackingCustomizer myCustomizer;
        ServiceTracker<IFooService, MyTrackedClass> tracker(GetBundleContext(), &myCustomizer);
Remark

This class is thread safe.

NOTE:

The ServiceTracker class is thread-safe. It does not call a ServiceTrackerCustomizer while holding any locks. ServiceTrackerCustomizer implementations must also be thread-safe.

Template Parameters
  • S -- The type of the service being tracked. The type S* must be an assignable datatype.
  • T -- The tracked object.

Public Types

using TrackedParamType = typename ServiceTrackerCustomizer<S, T>::TrackedParamType

The type of the tracked object.

using TrackingMap = std::unordered_map<ServiceReference<S>, std::shared_ptr<TrackedParamType>>

Public Functions

~ServiceTracker() override

Automatically closes the ServiceTracker

ServiceTracker(BundleContext const &context, ServiceReference<S> const &reference, ServiceTrackerCustomizer<S, T> *customizer = nullptr)

Create a ServiceTracker on the specified ServiceReference.

The service referenced by the specified ServiceReference will be tracked by this ServiceTracker.

Parameters
  • context -- The BundleContext against which the tracking is done.
  • reference -- The ServiceReference for the service to be tracked.
  • customizer -- The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
ServiceTracker(BundleContext const &context, std::string const &clazz, ServiceTrackerCustomizer<S, T> *customizer = nullptr)

Create a ServiceTracker on the specified class name.

Services registered under the specified class name will be tracked by this ServiceTracker.

Parameters
  • context -- The BundleContext against which the tracking is done.
  • clazz -- The class name of the services to be tracked.
  • customizer -- The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
ServiceTracker(BundleContext const &context, LDAPFilter const &filter, ServiceTrackerCustomizer<S, T> *customizer = nullptr)

Create a ServiceTracker on the specified LDAPFilter object.

Services which match the specified LDAPFilter object will be tracked by this ServiceTracker.

Parameters
  • context -- The BundleContext against which the tracking is done.
  • filter -- The LDAPFilter to select the services to be tracked.
  • customizer -- The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
ServiceTracker(BundleContext const &context, ServiceTrackerCustomizer<S, T> *customizer = nullptr)

Create a ServiceTracker on the class template argument S.

Services registered under the interface name of the class template argument S will be tracked by this ServiceTracker.

Parameters
  • context -- The BundleContext against which the tracking is done.
  • customizer -- The customizer object to call when services are added, modified, or removed in this ServiceTracker. If customizer is null, then this ServiceTracker will be used as the ServiceTrackerCustomizer and this ServiceTracker will call the ServiceTrackerCustomizer methods on itself.
Throws

ServiceException -- If the service interface name is empty.

virtual void Open()

Open this ServiceTracker and begin tracking services.

Services which match the search criteria specified when this ServiceTracker was created are now tracked by this ServiceTracker.

Throws
  • std::runtime_error -- If the BundleContext with which this ServiceTracker was created is no longer valid.
  • std::runtime_error -- If the LDAP filter used to construct the ServiceTracker contains an invalid filter expression that cannot be parsed.
virtual void Close()

Close this ServiceTracker.

This method should be called when this ServiceTracker should end the tracking of services.

This implementation calls GetServiceReferences() to get the list of tracked services to remove.

Throws

std::runtime_error -- If the BundleContext with which this ServiceTracker was created is no longer valid.

std::shared_ptr<TrackedParamType> WaitForService()

Wait for at least one service to be tracked by this ServiceTracker.

This method will also return when this ServiceTracker is closed.

It is strongly recommended that WaitForService is not used during the calling of the BundleActivator methods. BundleActivator methods are expected to complete in a short period of time.

This implementation calls GetService() to determine if a service is being tracked.

Throws

std::logic_error -- If the BundleContext with which this ServiceTracker was created is no longer valid or became invalid while waiting on Service.

Returns

The result of GetService().

template<class Rep, class Period> std::shared_ptr<TrackedParamType> WaitForService(std::chrono::duration<Rep, Period> const &rel_time)

Wait for at least one service to be tracked by this ServiceTracker.

This method will also return when this ServiceTracker is closed.

It is strongly recommended that WaitForService is not used during the calling of the BundleActivator methods. BundleActivator methods are expected to complete in a short period of time.

This implementation calls GetService() to determine if a service is being tracked.

Parameters

rel_time -- The relative time duration to wait for a service. If zero, the method will wait indefinitely.

Throws
  • std::invalid_argument -- exception if rel_time is negative.
  • std::logic_error -- If the BundleContext with which this ServiceTracker was created is no longer valid or became invalid while waiting on Service.
Returns

The result of GetService().

virtual std::vector<ServiceReference<S>> GetServiceReferences() const

Return a list of ServiceReferences for all services being tracked by this ServiceTracker.

Returns

A list of ServiceReference objects.

virtual ServiceReference<S> GetServiceReference() const

Returns a ServiceReference for one of the services being tracked by this ServiceTracker.

If multiple services are being tracked, the service with the highest ranking (as specified in its service.ranking property) is returned. If there is a tie in ranking, the service with the lowest service ID (as specified in its service.id property); that is, the service that was registered first is returned. This is the same algorithm used by BundleContext::GetServiceReference().

This implementation calls GetServiceReferences() to get the list of references for the tracked services.

Throws

ServiceException -- if no services are being tracked.

Returns

A ServiceReference for a tracked service.

virtual std::shared_ptr<TrackedParamType> GetService(ServiceReference<S> const &reference) const

Returns the service object for the specified ServiceReference if the specified referenced service is being tracked by this ServiceTracker.

Parameters

reference -- The reference to the desired service.

Returns

A service object or nullptr if the service referenced by the specified ServiceReference is not being tracked.

virtual std::vector<std::shared_ptr<TrackedParamType>> GetServices() const

Return a list of service objects for all services being tracked by this ServiceTracker.

This implementation calls GetServiceReferences() to get the list of references for the tracked services and then calls GetService(const ServiceReference&) for each reference to get the tracked service object.

Returns

A list of service objects or an empty list if no services are being tracked.

virtual std::shared_ptr<TrackedParamType> GetService() const

Returns a service object for one of the services being tracked by this ServiceTracker.

If any services are being tracked, this implementation returns the result of calling GetService(GetServiceReference()).

Returns

A service object or null if no services are being tracked.

virtual void Remove(ServiceReference<S> const &reference)

Remove a service from this ServiceTracker.

The specified service will be removed from this ServiceTracker. If the specified service was being tracked then the ServiceTrackerCustomizer::RemovedService method will be called for that service.

Parameters

reference -- The reference to the service to be removed.

virtual int Size() const

Return the number of services being tracked by this ServiceTracker.

Returns

The number of services being tracked.

virtual int GetTrackingCount() const

Returns the tracking count for this ServiceTracker.

The tracking count is initialized to 0 when this ServiceTracker is opened. Every time a service is added, modified or removed from this ServiceTracker, the tracking count is incremented.

The tracking count can be used to determine if this ServiceTracker has added, modified or removed a service by comparing a tracking count value previously collected with the current tracking count value. If the value has not changed, then no service has been added, modified or removed from this ServiceTracker since the previous tracking count was collected.

Returns

The tracking count for this ServiceTracker or -1 if this ServiceTracker is not open.

virtual void GetTracked(TrackingMap &tracked) const

Return a sorted map of the ServiceReferences and service objects for all services being tracked by this ServiceTracker.

The map is sorted in natural order of ServiceReference. That is, the last entry is the service with the highest ranking and the lowest service id.

Parameters

tracked -- A TrackingMap with the ServiceReferences and service objects for all services being tracked by this ServiceTracker. If no services are being tracked, then the returned map is empty.

virtual bool IsEmpty() const

Return if this ServiceTracker is empty.

Returns

true if this ServiceTracker is not tracking any services.

template<class Rep, class Period> std::shared_ptr<typename ServiceTracker<S, T>::TrackedParamType> WaitForService(std::chrono::duration<Rep, Period> const &rel_time)

Protected Functions

virtual std::shared_ptr<TrackedParamType> AddingService(ServiceReference<S> const &reference) override

Default implementation of the ServiceTrackerCustomizer::AddingService method.

This method is only called when this ServiceTracker has been constructed with a nullptr ServiceTrackerCustomizer argument.

This implementation returns the result of calling GetService on the BundleContext with which this ServiceTracker was created passing the specified ServiceReference.

This method can be overridden in a subclass to customize the service object to be tracked for the service being added. In that case, take care not to rely on the default implementation of RemovedService to unget the service.

SEE ALSO:

ServiceTrackerCustomizer::AddingService(const ServiceReference&)

Parameters

reference -- The reference to the service being added to this ServiceTracker.

Throws
  • std::runtime_error -- If this BundleContext is no longer valid.
  • std::invalid_argument -- If the specified ServiceReference is invalid (default constructed).
Returns

The service object to be tracked for the service added to this ServiceTracker.

void ModifiedService(ServiceReference<S> const &reference, std::shared_ptr<TrackedParamType> const &service) override

Default implementation of the ServiceTrackerCustomizer::ModifiedService method.

This method is only called when this ServiceTracker has been constructed with a nullptr ServiceTrackerCustomizer argument.

This implementation does nothing.

SEE ALSO:

ServiceTrackerCustomizer::ModifiedService(const ServiceReference&, TrackedArgType)

Parameters
  • reference -- The reference to modified service.
  • service -- The service object for the modified service.
void RemovedService(ServiceReference<S> const &reference, std::shared_ptr<TrackedParamType> const &service) override

Default implementation of the ServiceTrackerCustomizer::RemovedService method.

This method is only called when this ServiceTracker has been constructed with a nullptr ServiceTrackerCustomizer argument.

This method can be overridden in a subclass. If the default implementation of the AddingService method was used, this method must unget the service.

SEE ALSO:

ServiceTrackerCustomizer::RemovedService(const ServiceReferenceType&, TrackedArgType)

Parameters
  • reference -- The reference to removed service.
  • service -- The service object for the removed service.
template<class S, class T = S> struct ServiceTrackerCustomizer

#include <cppmicroservices/ServiceTrackerCustomizer.h>

The ServiceTrackerCustomizer interface allows a ServiceTracker to customize the service objects that are tracked.

A ServiceTrackerCustomizer is called when a service is being added to a ServiceTracker. The ServiceTrackerCustomizer can then return an object for the tracked service. A ServiceTrackerCustomizer is also called when a tracked service is modified or has been removed from a ServiceTracker.

The methods in this interface may be called as the result of a ServiceEvent being received by a ServiceTracker. Since ServiceEvents are synchronously delivered, it is highly recommended that implementations of these methods do not register (BundleContext::RegisterService), modify ( ServiceRegistration::SetProperties) or unregister ( ServiceRegistration::Unregister) a service while being synchronized on any object.

Remark

ServiceTrackerCustomizer implementations must also be thread-safe.

NOTE:

The ServiceTracker class implementation of ServiceTrackerCustomizer is thread-safe. It does not call a ServiceTrackerCustomizer while holding any locks. ServiceTrackerCustomizer implementations must also be thread-safe.

Template Parameters
  • S -- The type of the service being tracked
  • T -- The type of the tracked object. The default is S.

Public Types

using TrackedParamType = typename TypeTraits::TrackedParamType

Public Functions

virtual ~ServiceTrackerCustomizer() = default

virtual std::shared_ptr<TrackedParamType> AddingService(ServiceReference<S> const &reference) = 0

A service is being added to the ServiceTracker.

This method is called before a service which matched the search parameters of the ServiceTracker is added to the ServiceTracker. This method should return the service object to be tracked for the specified ServiceReference. The returned service object is stored in the ServiceTracker and is available from the GetService and GetServices methods.

Parameters

reference -- The reference to the service being added to the ServiceTracker.

Returns

The service object to be tracked for the specified referenced service or 0 if the specified referenced service should not be tracked.

virtual void ModifiedService(ServiceReference<S> const &reference, std::shared_ptr<TrackedParamType> const &service) = 0

A service tracked by the ServiceTracker has been modified.

This method is called when a service being tracked by the ServiceTracker has had it properties modified.

Parameters
  • reference -- The reference to the service that has been modified.
  • service -- The service object for the specified referenced service.
virtual void RemovedService(ServiceReference<S> const &reference, std::shared_ptr<TrackedParamType> const &service) = 0

A service tracked by the ServiceTracker has been removed.

This method is called after a service is no longer being tracked by the ServiceTracker.

Parameters
  • reference -- The reference to the service that has been removed.
  • service -- The service object for the specified referenced service.
struct TypeTraits

#include <cppmicroservices/ServiceTrackerCustomizer.h>

Public Types

using ServiceType = S

using TrackedType = T

using TrackedParamType = T

Public Static Functions

static inline std::shared_ptr<TrackedType> ConvertToTrackedType(std::shared_ptr<S> const&)

Utilities

These classes support the main CppMicroServices API:

Any

template<typename ValueType> ValueType *any_cast(Any *operand)

any_cast operator used to extract the ValueType from an Any*.

Will return a pointer to the stored value.

Example Usage: .INDENT 7.0

MyType* pTmp = any_cast<MyType*>(pAny)

Will return nullptr if the cast fails, i.e. types don't match.

template<typename ValueType> ValueType const *any_cast(Any const *operand)

any_cast operator used to extract a const ValueType pointer from an const Any*.

Will return a const pointer to the stored value.

Example Usage: .INDENT 7.0

const MyType* pTmp = any_cast<MyType*>(pAny)

Will return nullptr if the cast fails, i.e. types don't match.

template<typename ValueType> ValueType any_cast(Any const &operand)

any_cast operator used to extract a copy of the ValueType from an const Any&.

Example Usage: .INDENT 7.0

MyType tmp = any_cast<MyType>(anAny)

Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& = ... Some compilers will accept this code although a copy is returned. Use the ref_any_cast in these cases.

Throws

BadAnyCastException -- if the cast fails.

template<typename ValueType> ValueType any_cast(Any &operand)

any_cast operator used to extract a copy of the ValueType from an Any&.

Example Usage: .INDENT 7.0

MyType tmp = any_cast<MyType>(anAny)

Dont use an any_cast in combination with references, i.e. MyType& tmp = ... or const MyType& tmp = ... Some compilers will accept this code although a copy is returned. Use the ref_any_cast in these cases.

Throws

BadAnyCastException -- if the cast fails.

template<typename ValueType> ValueType const &ref_any_cast(Any const &operand)

ref_any_cast operator used to return a const reference to the internal data.

Example Usage: .INDENT 7.0

const MyType& tmp = ref_any_cast<MyType>(anAny);
Throws

BadAnyCastException -- if the cast fails.

template<typename ValueType> ValueType &ref_any_cast(Any &operand)

ref_any_cast operator used to return a reference to the internal data.

Example Usage: .INDENT 7.0

MyType& tmp = ref_any_cast<MyType>(anAny);
Throws

BadAnyCastException -- if the cast fails.

class Any

#include <cppmicroservices/Any.h>

An Any class represents a general type and is capable of storing any type, supporting type-safe extraction of the internally stored data.

Code taken from the Boost 1.46.1 library. Original copyright by Kevlin Henney. Modified for CppMicroServices.

Public Functions

Any()

Creates an empty any type.

template<typename ValueType> inline Any(ValueType const &value)

Creates an Any which stores the init parameter inside.

Example: .INDENT 7.0

Any a(13);
Any a(string("12345"));
Parameters

value -- The content of the Any

inline Any(Any const &other)

Copy constructor, works with empty Anys and initialized Any values.

Parameters

other -- The Any to copy

inline Any(Any &&other) noexcept

Move constructor.

Parameters

other -- The Any to move

inline Any &Swap(Any &rhs)

Swaps the content of the two Anys.

Parameters

rhs -- The Any to swap this Any with.

template<typename ValueType> inline bool operator==(ValueType const &val) const

Compares this Any with another value.

If the internal type of this any and of val do not match, the comparison always returns false.

Parameters

val -- The value to compare to.

Returns

true if this Any contains value val, false otherwise.

inline bool operator==(Any const &rhs) const

Compares this Any with another Any.

We accomplish this by forwarding the call to a virtual compare function on the Holder of the value in the _content field. The Placeholder subclass of Holder provides an implementation that invokes the above operator== with the underlying value of ValueType.

Parameters

rhs -- an Any to compare against

Returns

bool return true if rhs compares equal to *this AND the underlying ValueType has an operator==, and return false otherwise.

template<typename ValueType> inline bool operator!=(ValueType const &val) const

Compares this Any with another value for inequality.

This is the same as .INDENT 7.0

!this->operator==(val)
Parameters

val -- The value to compare to.

Returns

true if this Any does not contain value val, false otherwise.

template<typename ValueType> inline Any &operator=(ValueType const &rhs)

Assignment operator for all types != Any.

Example: .INDENT 7.0

Any a = 13;
Any a = string("12345");
Parameters

rhs -- The value which should be assigned to this Any.

inline Any &operator=(Any const &rhs)

Assignment operator for Any.

Parameters

rhs -- The Any which should be assigned to this Any.

inline Any &operator=(Any &&rhs) noexcept

Move assignment operator for Any.

Parameters

rhs -- The Any which should be moved into this Any.

Returns

A reference to this Any.

inline bool Empty() const

returns true if the Any is empty

std::string ToString() const

Returns a string representation for the content if it is not empty.

Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType&

ct) function or specialize the any_value_to_string template function for meaningful output.

Throws

std::logic_error -- if the Any is empty.

std::string ToStringNoExcept() const

Returns a string representation for the content.

If the Any is empty, an empty string is returned.

Custom types should either provide a std::ostream& operator<<(std::ostream& os, const CustomType&

ct) function or specialize the any_value_to_string template function for meaningful output.

inline std::string ToJSON(uint8_t const increment, int32_t const indent) const

Returns a JSON representation for the content.

Custom types should specialize the any_value_to_json template function for meaningful output. The values of increment and indent are passed around to be able to be used for nicer formatting. The code that makes use of this is in the any_value_to_json specializations for the various containers.

To get pretty output, simply pass a value greater than zero in as the first argument of ToJSON and the rest of the code will take care of things.

Parameters
  • increment -- The amount of extra indentation to add for each level of JSON. An increment of zero indicates no special formatting
  • indent -- The current amount of indent to apply to the current line.

inline std::string ToJSON(bool prettyPrint = false) const

inline std::string ToCPP(uint8_t const increment, int32_t const indent) const

inline std::string ToCPP(bool prettyPrint = false) const

inline std::type_info const &Type() const

Returns the type information of the stored content.

If the Any is empty typeid(void) is returned. It is suggested to always query an Any for its type info before trying to extract data via an any_cast/ref_any_cast.

class BadAnyCastException : public std::bad_cast

#include <cppmicroservices/Any.h>

The BadAnyCastException class is thrown in case of casting an Any instance.

Public Functions

inline BadAnyCastException(std::string msg = "")

~BadAnyCastException() override = default

inline char const *what() const noexcept override

AnyMap

class AnyMap : public cppmicroservices::any_map

A map data structure with support for compound keys.

This class adds convenience functions on top of the any_map class. The any_map is a recursive data structure, and its values can be retrieved via standard map functions or by using a dotted key notation specifying a compound key.

SEE ALSO:

any_map

Public Functions

AnyMap(std::initializer_list<any_map::value_type> l = {})

initializer_list constructor

Construct an AnyMap of type UNORDERED_MAP_CASEINSENSITIVE_KEYS with the content of the the initializer list. Allows for inline initialization akin to: .INDENT 7.0

AnyMap cache_bundle1 {
    {"a", std::string("A")},
    {"b", std::string("B")},
    {"c", std::string("C")}
};
Parameters

l -- a std::initializer_list<value_type> used to initialize the content of the AnyMap.

AnyMap(map_type type, std::initializer_list<any_map::value_type> l = {})

initializer_list constructor

Construct an AnyMap of type "type" with the content of the the initializer list. Allows for inline initialization akin to: .INDENT 7.0

AnyMap cache_bundle1 {
    AnyMap::ORDERED_MAP, {
        {"a", std::string("A")},
        {"b", std::string("B")},
        {"c", std::string("C")}
    }
};
Parameters
  • type -- the map_type of the AnyMap
  • l -- a std::initializer_list<value_type> used to initialize the content of the AnyMap.

AnyMap(ordered_any_map const &m)

AnyMap(ordered_any_map &&m)

AnyMap(unordered_any_map const &m)

AnyMap(unordered_any_map &&m)

AnyMap(unordered_any_cimap const &m)

AnyMap(unordered_any_cimap &&m)

map_type GetType() const

Get the underlying STL container type.

Returns

The STL container type holding the map data.

mapped_type const &AtCompoundKey(key_type const &key) const

Get a key's value, using a compound key notation.

A compound key consists of one or more key names, concatenated with the '.' (dot) character. Each key except the last requires the referenced Any object to be of type AnyMap or std::vector<Any>. Containers of type std::vector<Any> are indexed using 0-based numerical key names.

For example, a AnyMap object holding data of the following layout .INDENT 7.0

{
  one: 1,
  two: "two",
  three: {
    a: "anton",
    b: [ 3, 8 ]
  }
}

can be queried using the following notation: .INDENT 7.0

map.AtCompoundKey("one");       // returns Any(1)
map.AtCompoundKey("three.a");   // returns Any(std::string("anton"))
map.AtCompoundKey("three.b.1"); // returns Any(8)
Parameters

key -- The key hierachy to query.

Throws
  • std::invalid_argument -- if the Any value for a given key is not of type AnyMap or std::vector<Any>.
  • std::out_of_range -- if the key is not found or a numerical index would fall out of the range of an int type.
Returns

A reference to the key's value.

mapped_type AtCompoundKey(key_type const &key, mapped_type defaultValue) const noexcept

Return a key's value, using a compound key notation if the key is found in the map or return the provided default value if the key is not found.

A compound key consists of one or more key names, concatenated with the '.' (dot) character. Each key except the last requires the referenced Any object to be of type AnyMap or std::vector<Any>. Containers of type std::vector<Any> are indexed using 0-based numerical key names.

For example, a AnyMap object holding data of the following layout .INDENT 7.0

{
  one: 1,
  two: "two",
  three: {
    a: "anton",
    b: [ 3, 8 ]
  }
}

can be queried using the following notation: .INDENT 7.0

map.AtCompoundKey("one", Any());       // returns Any(1)
map.AtCompoundKey("four", Any());       // returns Any()
map.AtCompoundKey("three.a", Any());          // returns Any(std::string("anton"))
map.AtCompoundKey("three.c", Any());          // returns Any()
map.AtCompoundKey("three.b.1", Any());        // returns Any(8)
map.AtCompoundKey("three.b.4", Any());        // returns Any()
Parameters
  • key -- The key hierachy to query.
  • defaultValue -- is the value to be returned if the key is not found
Returns

A copy of the key's value.

class any_map

A map data structure which wraps different STL map types.

This is a convenience class providing a STL associative container interface for different underlying container types. Supported underlying types are.INDENT 7.0

·

any_map::ordered_any_map (a STL map)

·

any_map::unordered_any_map (a STL unordered map)

·

any_map::unordered_any_cimap (a STL unordered map with case insensitive key comparison)

This class provides most of the STL functions for associated containers, including forward iterators. It is typically not instantiated by clients directly, but obtained via framework API calls, returning an AnyMap sub-class instance.

SEE ALSO:

AnyMap

Subclassed by cppmicroservices::AnyMap

Public Types

enum map_type

Values:

enumerator ORDERED_MAP

enumerator UNORDERED_MAP

enumerator UNORDERED_MAP_CASEINSENSITIVE_KEYS

using key_type = std::string

using mapped_type = Any

using value_type = std::pair<key_type const, mapped_type>

using size_type = std::size_t

using difference_type = std::ptrdiff_t

using reference = value_type&

using const_reference = value_type const&

using pointer = value_type*

using const_pointer = value_type const*

using ordered_any_map = std::map<std::string, Any>

using unordered_any_map = std::unordered_map<std::string, Any>

using unordered_any_cimap = std::unordered_map<std::string, Any, detail::any_map_cihash, detail::any_map_ciequal>

using iterator = iter

using const_iterator = const_iter

Public Functions

any_map(map_type type, std::initializer_list<value_type> l = {})

initializer_list constructor

Construct an AnyMap of type "type" with the content of the initialized with the content of the the initializer list. Allows for inline initialization akin to: .INDENT 7.0

any_map cache_bundle1 {
    any_map::ORDERED_MAP, {
        {"a", std::string("A")},
        {"b", std::string("B")},
        {"c", std::string("C")}
    }
};

The primary purpose of this constructor in any_map is in support of the initializer_list constructors in the AnyMap subclass.

Parameters
  • type -- the map_type of the AnyMap
  • l -- a std::initializer_list<value_type> used to initialize the content of the AnyMap.

any_map(ordered_any_map const &m)

any_map(ordered_any_map &&m)

any_map(unordered_any_map const &m)

any_map(unordered_any_map &&m)

any_map(unordered_any_cimap const &m)

any_map(unordered_any_cimap &&m)

any_map(any_map const &m)

any_map &operator=(any_map const &m)

any_map(any_map &&m) noexcept

any_map &operator=(any_map &&m) noexcept

~any_map()

iter begin()

const_iter begin() const

const_iter cbegin() const

iter end()

const_iter end() const

const_iter cend() const

bool empty() const

size_type size() const

size_type count(key_type const &key) const

void clear()

mapped_type &at(key_type const &key)

mapped_type const &at(key_type const &key) const

mapped_type &operator[](key_type const &key)

mapped_type &operator[](key_type &&key)

std::pair<iterator, bool> insert(value_type const &value)

template<class ...Args> inline std::pair<iterator, bool> emplace(Args&&... args)

const_iterator find(key_type const &key) const

return the iterator to the value referenced by key

size_type erase(key_type const &key)

Erase entry for value for 'key'.

Parameters

key -- the key for the entry to Erase

Returns

the number of elements erased.

bool operator==(any_map const &rhs) const

Compare the content of this map with those of rhs.

Parameters

rhs -- an any_map to compare

Returns

bool true rhs contains the same content as this

inline bool operator!=(any_map const &rhs) const

Public Members

ordered_any_map *o

unordered_any_map *uo

unordered_any_cimap *uoci

Protected Attributes

map_type type

class const_iter : public cppmicroservices::any_map::iterator_base

Public Types

using reference = any_map::const_reference

using pointer = any_map::const_pointer

using iterator = const_iter

Public Functions

const_iter()

const_iter(iterator const &it)

const_iter(iter const &it)

~const_iter()

const_iter(ociter &&it)

const_iter(uociter &&it, iter_type type)

reference operator*() const

pointer operator->() const

iterator &operator++()

iterator operator++(int)

bool operator==(iterator const &x) const

bool operator!=(iterator const &x) const

Public Members

ociter *o

uociter *uo

uocciiter *uoci

class iter : public cppmicroservices::any_map::iterator_base

Public Types

using reference = any_map::reference

using pointer = any_map::pointer

using iterator = iter

Public Functions

iter()

iter(iter const &it)

~iter()

iter(oiter &&it)

iter(uoiter &&it, iter_type type)

reference operator*() const

pointer operator->() const

iterator &operator++()

iterator operator++(int)

bool operator==(iterator const &x) const

bool operator!=(iterator const &x) const

Public Members

oiter *o

uoiter *uo

uociiter *uoci

BundleVersion

std::ostream &operator<<(std::ostream &os, BundleVersion const &v)

Streams the string representation of v into the stream os, using BundleVersion::ToString.

class BundleVersion

#include <cppmicroservices/BundleVersion.h>

Version identifier for CppMicroServices bundles.

Version identifiers have four components. .INDENT 7.0

a.

Major version. A non-negative integer.

b.

Minor version. A non-negative integer.

c.

Micro version. A non-negative integer.

d.

Qualifier. A text string. See BundleVersion(const std::string&) for the format of the qualifier string.

BundleVersion objects are immutable.

Public Functions

BundleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion)

Creates a version identifier from the specified numerical components.

The qualifier is set to the empty string.

Parameters
  • majorVersion -- Major component of the version identifier.
  • minorVersion -- Minor component of the version identifier.
  • microVersion -- Micro component of the version identifier.
BundleVersion(unsigned int majorVersion, unsigned int minorVersion, unsigned int microVersion, std::string qualifier)

Creates a version identifier from the specified components.

Parameters
  • majorVersion -- Major component of the version identifier.
  • minorVersion -- Minor component of the version identifier.
  • microVersion -- Micro component of the version identifier.
  • qualifier -- Qualifier component of the version identifier.
BundleVersion(std::string const &version)

Created a version identifier from the specified string.

Here is the grammar for version strings.

There must be no whitespace in version.

Parameters

version -- string representation of the version identifier.

BundleVersion(BundleVersion const &version)

Create a version identifier from another.

Parameters

version -- Another version identifier

bool IsUndefined() const

Returns the undefined state of this version identifier.

Returns

true if this version identifier is undefined, false otherwise.

unsigned int GetMajor() const

Returns the majorVersion component of this version identifier.

Returns

The majorVersion component.

unsigned int GetMinor() const

Returns the minorVersion component of this version identifier.

Returns

The minorVersion component.

unsigned int GetMicro() const

Returns the microVersion component of this version identifier.

Returns

The microVersion component.

std::string GetQualifier() const

Returns the qualifier component of this version identifier.

Returns

The qualifier component.

std::string ToString() const

Returns the string representation of this version identifier.

The format of the version string will be majorVersion.minorVersion.microVersion if qualifier is the empty string or majorVersion.minorVersion.microVersion.qualifier otherwise.

Returns

The string representation of this version identifier.

bool operator==(BundleVersion const &object) const

Compares this BundleVersion object to another object.

A version is considered to be equal to another version if the majorVersion, minorVersion and microVersion components are equal and the qualifier component is equal.

Parameters

object -- The BundleVersion object to be compared.

Returns

true if object is a BundleVersion and is equal to this object; false otherwise.

int Compare(BundleVersion const &object) const

Compares this BundleVersion object to another object.

A version is considered to be less than another version if its majorVersion component is less than the other version's majorVersion component, or the majorVersion components are equal and its minorVersion component is less than the other version's minorVersion component, or the majorVersion and minorVersion components are equal and its microVersion component is less than the other version's microVersion component, or the majorVersion, minorVersion and microVersion components are equal and it's qualifier component is less than the other version's qualifier component (using std::string::operator<()).

A version is considered to be equal to another version if the majorVersion, minorVersion and microVersion components are equal and the qualifier component is equal.

Parameters

object -- The BundleVersion object to be compared.

Returns

A negative integer, zero, or a positive integer if this object is less than, equal to, or greater than the specified BundleVersion object.

Public Static Functions

static BundleVersion EmptyVersion()

The empty version "0.0.0".

static BundleVersion UndefinedVersion()

Creates an undefined version identifier, representing either infinity or minus infinity.

static BundleVersion ParseVersion(std::string const &version)

Parses a version identifier from the specified string.

See BundleVersion(const std::string&) for the format of the version string.

Parameters

version -- string representation of the version identifier. Leading and trailing whitespace will be ignored.

Returns

A BundleVersion object representing the version identifier. If version is the empty string then EmptyVersion will be returned.

Constants

namespace Constants

Defines standard names for the CppMicroServices environment system properties, service properties, and Manifest header attribute keys.

The values associated with these keys are of type std::string, unless otherwise indicated.

Variables

const std::string SYSTEM_BUNDLE_LOCATION

Location identifier of the OSGi system bundle , which is defined to be "System Bundle".

const std::string SYSTEM_BUNDLE_SYMBOLICNAME

Alias for the symbolic name of the OSGi system bundle .

It is defined to be "system.bundle".

const std::string BUNDLE_ACTIVATOR

Manifest header identifying the bundle's activator.

The value for this attribute is of type bool. false - the bundle has no activator true - the bundle has an activator The behavior if the attribute is not specified is the same as when it is set to 'false'.

The header value may be retrieved via the Bundle::GetProperty method.

const std::string BUNDLE_CATEGORY

Manifest header identifying the bundle's category.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_COPYRIGHT

Manifest header identifying the bundle's copyright information.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_DESCRIPTION

Manifest header containing a brief description of the bundle's functionality.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_MANIFESTVERSION

Manifest header identifying the bundle's manifest version.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_NAME

Manifest header identifying the bundle's name.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_VENDOR

Manifest header identifying the bundle's vendor.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_VERSION

Manifest header identifying the bundle's version.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_DOCURL

Manifest header identifying the bundle's documentation URL, from which further information about the bundle may be obtained.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_CONTACTADDRESS

Manifest header identifying the contact address where problems with the bundle may be reported; for example, an email address.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_SYMBOLICNAME

Manifest header identifying the bundle's symbolic name.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

const std::string BUNDLE_LOCALIZATION

Manifest header identifying the base name of the bundle's localization entries.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

SEE ALSO:

BUNDLE_LOCALIZATION_DEFAULT_BASENAME

const std::string BUNDLE_LOCALIZATION_DEFAULT_BASENAME

Default value for the bundle.localization manifest header.

SEE ALSO:

BUNDLE_LOCALIZATION

const std::string BUNDLE_ACTIVATIONPOLICY

Manifest header identifying the bundle's activation policy.

The header value may be retrieved from the AnyMap object returned by the Bundle::GetHeaders() method.

SEE ALSO:

ACTIVATION_LAZY

const std::string ACTIVATION_LAZY

Bundle activation policy declaring the bundle must be activated when the library containing it is loaded into memory.

A bundle with the lazy activation policy that is started with the START_ACTIVATION_POLICY option will wait in the STATE_STARTING state until its library is loaded. The bundle will then be activated.

The activation policy value is specified as in the bundle.activation_policy manifest header like:

SEE ALSO:

BUNDLE_ACTIVATIONPOLICY

SEE ALSO:

Bundle::Start(uint32_t)

SEE ALSO:

Bundle::START_ACTIVATION_POLICY

const std::string FRAMEWORK_VERSION

Framework environment property identifying the Framework version.

The header value may be retrieved via the BundleContext::GetProperty method.

const std::string FRAMEWORK_VENDOR

Framework environment property identifying the Framework implementation vendor.

The header value may be retrieved via the BundleContext::GetProperty method.

const std::string FRAMEWORK_STORAGE

Framework launching property specifying the persistent storage area used by the framework.

The value of this property must be a valid file path in the file system to a directory. If the specified directory does not exist then the framework will create the directory. If the specified path exists but is not a directory or if the framework fails to create the storage directory, then framework initialization fails. This area can not be shared with anything else.

If this property is not set, the framework uses the "fwdir" directory in the current working directory for the persistent storage area.

const std::string FRAMEWORK_STORAGE_CLEAN

Framework launching property specifying if and when the persistent storage area for the framework should be cleaned.

If this property is not set, then the framework storage area must not be cleaned.

SEE ALSO:

FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT

const std::string FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT

Specifies that the framework storage area must be cleaned before the framework is initialized for the first time.

Subsequent inits, starts or updates of the framework will not result in cleaning the framework storage area.

const std::string FRAMEWORK_THREADING_SUPPORT

The framework's threading support property key name.

This property's default value is "single". Valid key values are:.INDENT 7.0

·

"single" - The framework APIs are not thread-safe.

·

"multi" - The framework APIs are thread-safe.

NOTE:

This is a read-only property and cannot be altered at run-time. The key's value is set at compile time by the US_ENABLE_THREADING_SUPPORT option. See Build Instructions for more information.

const std::string FRAMEWORK_THREADING_SINGLE

Framework threading support configuration declaring that the framework is configured for single thread usage.

It is not safe to use the framework API concurrently from multiple threads.

const std::string FRAMEWORK_THREADING_MULTI

Framework threading support configuration declaring that the framework is configured for multi-thread usage.

The framework API uses internal locks such that it is safe to use the API concurrently from multiple threads.

const std::string FRAMEWORK_LOG

The framework's log property key name.

This property's default value is off (boolean 'false').

const std::string FRAMEWORK_UUID

Framework environment property identifying the Framework's universally unique identifier (UUID).

A UUID represents a 128-bit value. A new UUID is generated by the Framework#Init() method each time a framework is initialized. The value of this property conforms to the UUID string representation specified in RFC 4122.

The header value may be retrieved via the BundleContext::GetProperty method.

const std::string FRAMEWORK_WORKING_DIR

Framework launching property specifying the working directory used for resolving relative path names.

If not set, the framework will use the process current working directory as set during static initialization of the framework library.

const std::string FRAMEWORK_BUNDLE_VALIDATION_FUNC

Framework bundle validation property specifying a function that control whether a shared library is loaded or not into the process.

const std::string OBJECTCLASS

Service property identifying all of the class names under which a service was registered in the Framework.

The value of this property must be of type std::vector<std::string>.

This property is set by the Framework when a service is registered.

const std::string SERVICE_ID

Service property identifying a service's registration number.

The value of this property must be of type long int.

The value of this property is assigned by the Framework when a service is registered. The Framework assigns a unique value that is larger than all previously assigned values since the Framework was started. These values are NOT persistent across restarts of the Framework.

const std::string SERVICE_PID

Service property identifying a service's persistent identifier.

This property may be supplied in the properties ServiceProperties object passed to the BundleContext::RegisterService method. The value of this property must be of type std::string or std::vector<std::string>.

A service's persistent identifier uniquely identifies the service and persists across multiple Framework invocations.

By convention, every bundle has its own unique namespace, starting with the bundle's identifier (see Bundle#GetBundleId()) and followed by a dot (.). A bundle may use this as the prefix of the persistent identifiers for the services it registers.

const std::string SERVICE_RANKING

Service property identifying a service's ranking number.

This property may be supplied in the ServiceProperties object passed to the BundleContext::RegisterService method. The value of this property must be of type int.

The service ranking is used by the framework to determine the natural order of services, see ServiceReference::operator<(const ServiceReference&), and the default service to be returned from a call to the BundleContext::GetServiceReference method.

The default ranking is zero (0). A service with a ranking of std::numeric_limits<int>::max() is very likely to be returned as the default service, whereas a service with a ranking of std::numeric_limits<int>::min() is very unlikely to be returned.

If the supplied property value is not of type int, it is deemed to have a ranking value of zero.

const std::string SERVICE_VENDOR

Service property identifying a service's vendor.

This property may be supplied in the properties ServiceProperties object passed to the BundleContext::RegisterService method.

const std::string SERVICE_DESCRIPTION

Service property identifying a service's description.

This property may be supplied in the properties ServiceProperties object passed to the BundleContext::RegisterService method.

const std::string SERVICE_SCOPE

Service property identifying a service's scope.

This property is set by the framework when a service is registered. If the registered object implements PrototypeServiceFactory, then the value of this service property will be SCOPE_PROTOTYPE. Otherwise, if the registered object implements ServiceFactory, then the value of this service property will be SCOPE_BUNDLE. Otherwise, the value of this service property will be SCOPE_SINGLETON.

const std::string SCOPE_SINGLETON

Service scope is singleton.

All bundles using the service receive the same service object.

SEE ALSO:

SERVICE_SCOPE

const std::string SCOPE_BUNDLE

Service scope is bundle.

Each bundle using the service receives a distinct service object.

SEE ALSO:

SERVICE_SCOPE

const std::string SCOPE_PROTOTYPE

Service scope is prototype.

Each bundle using the service receives either a distinct service object or can request multiple distinct service objects via ServiceObjects.

SEE ALSO:

SERVICE_SCOPE

const std::string LIBRARY_LOAD_OPTIONS

Service property that holds optional flags for dlopen calls on POSIX systems.

FrameworkFactory

class FrameworkFactory

A factory for creating Framework instances.

Remark

This class is thread-safe.

Public Functions

Framework NewFramework(FrameworkConfiguration const &configuration, std::ostream *logger = nullptr)

Create a new Framework instance.

Parameters
  • configuration -- The framework properties to configure the new framework instance. If framework properties are not provided by the configuration argument, the created framework instance will use a reasonable default configuration.
  • logger -- Any ostream object which will receieve redirected debug log output.
Returns

A new, configured Framework instance.

Framework NewFramework()

Create a new Framework instance.

This is the same as calling .INDENT 7.0

NewFramework(FrameworkConfiguration())

.

Returns

A new, configured Framework instance.

Framework NewFramework(std::map<std::string, Any> const &configuration, std::ostream *logger = nullptr)

Create a new Framework instance.

Deprecated:

Since 3.1, use NewFramework() or NewFramework(const FramworkConfiguration&, std::ostream*) instead.

Returns

A new, configured Framework instance.

GetBundleContext

static inline BundleContext cppmicroservices::GetBundleContext()

Returns the bundle context of the calling bundle.

This function allows easy access to the BundleContext instance from inside a C++ Micro Services bundle.

Returns

The BundleContext of the calling bundle. If the caller is not part of an active bundle, an invalid BundleContext is returned.

LDAPFilter

std::ostream &operator<<(std::ostream &os, LDAPFilter const &filter)

Streams the string representation of filter into the stream os via LDAPFilter::ToString().

LDAPPropExpr operator==(std::string const &s) const

LDAPPropExpr operator==(cppmicroservices::Any const &s) const

LDAPPropExpr operator==(bool b) const

template<class T> inline LDAPPropExpr operator==(T const &s) const

LDAPPropExpr operator!=(std::string const &s) const

LDAPPropExpr operator!=(cppmicroservices::Any const &s) const

template<class T> inline LDAPPropExpr operator!=(T const &s) const

LDAPPropExpr operator>=(std::string const &s) const

LDAPPropExpr operator>=(cppmicroservices::Any const &s) const

template<class T> inline LDAPPropExpr operator>=(T const &s) const

LDAPPropExpr operator<=(std::string const &s) const

LDAPPropExpr operator<=(cppmicroservices::Any const &s) const

template<class T> inline LDAPPropExpr operator<=(T const &s) const

LDAPPropExpr Approx(std::string const &s) const

LDAPPropExpr Approx(cppmicroservices::Any const &s) const

template<class T> inline LDAPPropExpr Approx(T const &s) const

cppmicroservices::LDAPPropExpr operator&&(cppmicroservices::LDAPPropExpr const &left, cppmicroservices::LDAPPropExpr const &right)

LDAP logical and '&'.

Parameters
  • left -- A LDAP expression.
  • right -- A LDAP expression.
Returns

A LDAP expression

cppmicroservices::LDAPPropExpr operator||(cppmicroservices::LDAPPropExpr const &left, cppmicroservices::LDAPPropExpr const &right)

LDAP logical or '|'.

Parameters
  • left -- A LDAP expression.
  • right -- A LDAP expression.
Returns

A LDAP expression

class LDAPFilter

#include <cppmicroservices/LDAPFilter.h>

An RFC 1960-based Filter.

A LDAPFilter can be used numerous times to determine if the match argument matches the filter string that was used to create the LDAPFilter.

Some examples of LDAP filters are:

  • "(cn=Babs Jensen)"
  • "(!(cn=Tim Howes))"
  • "(&(" + Constants::OBJECTCLASS + "=Person)(|(sn=Jensen)(cn=Babs J*)))"
  • "(o=univ*of*mich*)"

LDAPFilters have been extended to make it easier to query nested JSON keys. This is disabled by default. To enable this functionality, define SUPPORT_NESTED_LOOKUP at compile time. For example, if using "make" to build:

make clean make SUPPORT_NESTED_LOOKUP=1

Nested Lookup Description

Keys which contain the "." character may refer to nested values. The top level is checked first for a matching entry. If one isn't found, the key is decomposed and the JSON structure "walked down" to look for a match.

For example, given a key "a.b.c.d", if a value exists in the top level map with that key, it's retuned. If a value is not found at the top level with that key, it's decomposed into a vector: ["a","b","c","d"]. Ultimately for the filter to be applied, there must be a value in a nested AnyMap with a key ending with "d". So, the top level map is checked for the key "a". If a value rather than a map is found there, there is no path to "d", so the algorithm stops with an unsuccessful lookup. If a map does exist, the algorithm continues and looks for a key of "b" in that map and continues from there with the same algorithm (looking at that submap for keys "b", "b.c", and "b.c.d"). Finally, if nothing has been found for key "a", the algorithm combines the first two keys together into "a.b" and looks for a submap. Again, if a value is found rather than a map, there is no path to "d" so we halt the lookup. If a submap is found there, we then look in that map for a key of "c" and continue from there. Finally, if there is no item in the to plevel map at "a.b", we look at "a.b.c". And again, a value there halts the algorithm. If a map is found there, it's checked for a value at key "d".

A real world example:

  • "("bundle.symbolic_name=my_bundle)". This will look for a match in two places. First it

    will look in the JSON manifest for:

    { "bundle.symbolic_name" : "my_bundle" }

    If not found there, this will be checked:

    { "bundle" : { "symbolic_name" : "my_bundle" } }

  • top level flat keys are preferred in order to preserve the behavior of existing filters.

    Remark

    This class is thread safe.

SEE ALSO:

Use LDAPProp class to conveniently generate LDAP filter strings

Public Functions

LDAPFilter()

Creates a valid LDAPFilter object that matches nothing.

LDAPFilter(std::string const &filter)

Creates a LDAPFilter object encapsulating the filter string.

This LDAPFilter object may be used to match a ServiceReference object or a ServiceProperties object.

If the filter cannot be parsed, an std::invalid_argument will be thrown with a human readable message where the filter became unparsable.

SEE ALSO:

"Framework specification for a description of the filter string syntax." TODO!

Parameters

filter -- The filter string.

Throws

std::invalid_argument -- If filter contains an invalid filter string that cannot be parsed.

LDAPFilter(LDAPFilter const &other)

~LDAPFilter()

explicit operator bool() const

bool Match(ServiceReferenceBase const &reference) const

Filter using a service's properties.

This LDAPFilter is executed using the keys and values of the referenced service's properties. The keys are looked up in a case insensitive manner.

Parameters

reference -- The reference to the service whose properties are used in the match.

Returns

true if the service's properties match this LDAPFilter false otherwise.

bool Match(Bundle const &bundle) const

Filter using a bundle's manifest headers.

This LDAPFilter is executed using the keys and values of the bundle's manifest headers. The keys are looked up in a case insensitive manner.

Parameters

bundle -- The bundle whose manifest's headers are used in the match.

Throws

std::runtime_error -- If the number of keys of the bundle's manifest headers exceeds the value returned by std::numeric_limits<int>::max().

Returns

true if the bundle's manifest headers match this LDAPFilter false otherwise.

bool Match(AnyMap const &dictionary) const

Filter using a AnyMap object with case insensitive key lookup.

This LDAPFilter is executed using the specified AnyMap's keys and values. The keys are looked up in a case insensitive manner.

Parameters

dictionary -- The AnyMap whose key/value pairs are used in the match.

Throws
  • std::runtime_error -- If the number of keys in the dictionary exceeds the value returned by std::numeric_limits<int>::max().
  • std::runtime_error -- If the dictionary contains case variants of the same key name.
Returns

true if the AnyMap's values match this filter; false otherwise.

bool MatchCase(AnyMap const &dictionary) const

Filter using a AnyMap.

This LDAPFilter is executed using the specified AnyMap's keys and values. The keys are looked up in a normal manner respecting case.

Parameters

dictionary -- The AnyMap whose key/value pairs are used in the match.

Throws
  • std::runtime_error -- If the number of keys in the dictionary exceeds the value returned by std::numeric_limits<int>::max().
  • std::runtime_error -- If the dictionary contains case variants of the same key name.
Returns

true if the AnyMap's values match this filter; false otherwise.

std::string ToString() const

Returns this LDAPFilter's filter string.

The filter string is normalized by removing whitespace which does not affect the meaning of the filter.

Returns

This LDAPFilter's filter string.

bool operator==(LDAPFilter const &other) const

Compares this LDAPFilter to another LDAPFilter.

This implementation returns the result of calling this->ToString() == other.ToString().

Parameters

other -- The object to compare against this LDAPFilter.

Returns

Returns the result of calling this->ToString() == other.ToString().

LDAPFilter &operator=(LDAPFilter const &filter)

Protected Attributes

std::shared_ptr<LDAPFilterData> d

class LDAPProp

#include <cppmicroservices/LDAPProp.h>

A fluent API for creating LDAP filter strings.

Examples for creating LDAPFilter objects: .INDENT 7.0

// This creates the filter "(&(name=Ben)(!(count=1)))"
LDAPFilter filter(LDAPProp("name") == "Ben" && !(LDAPProp("count") == 1));

// This creates the filter "(|(presence=*)(!(absence=*)))"
LDAPFilter filter(LDAPProp("presence") || !LDAPProp("absence"));

// This creates the filter "(&(ge>=-3)(approx~=hi))"
LDAPFilter filter(LDAPProp("ge") >= -3 && LDAPProp("approx").Approx("hi"));
SEE ALSO:

LDAPFilter

Public Functions

LDAPProp(std::string property)

Create a LDAPProp instance for the named LDAP property.

Parameters

property -- The name of the LDAP property.

operator LDAPPropExpr() const

LDAPPropExpr operator!() const

States the absence of the LDAP property.

Returns

A LDAP expression object.

Listeners

using ServiceListener = std::function<void(ServiceEvent const&)>

A ServiceEvent listener.

A ServiceListener can be any callable object and is registered with the Framework using the BundleContext#AddServiceListener(const ServiceListener&, const std::string&) method. ServiceListener instances are called with a ServiceEvent object when a service has been registered, unregistered, or modified.

SEE ALSO:

ServiceEvent

using BundleListener = std::function<void(BundleEvent const&)>

A BundleEvent listener.

When a BundleEvent is fired, it is asynchronously (if threading support is enabled) delivered to a BundleListener. The Framework delivers BundleEvent objects to a BundleListener in order and does not concurrently call a BundleListener.

A BundleListener can be any callable object and is registered with the Framework using the BundleContext#AddBundleListener(const BundleListener&) method. BundleListener instances are called with a BundleEvent object when a bundle has been installed, resolved, started, stopped, updated, unresolved, or uninstalled.

SEE ALSO:

BundleEvent

using FrameworkListener = std::function<void(FrameworkEvent const&)>

A FrameworkEvent listener.

When a BundleEvent is fired, it is asynchronously (if threading support is enabled) delivered to a FrameworkListener. The Framework delivers FrameworkEvent objects to a FrameworkListener in order and does not concurrently call a FrameworkListener.

A FrameworkListener can be any callable object and is registered with the Framework using the BundleContext#AddFrameworkListener(const FrameworkListener&) method. FrameworkListener instances are called with a FrameworkEvent object when a framework life-cycle event or notification message occured.

SEE ALSO:

FrameworkEvent

template<class R> ServiceListener ServiceListenerMemberFunctor(R *receiver, void (R::* callback)(ServiceEvent const&))

A convenience function that binds the member function callback of an object of type R and returns a ServiceListener object.

This object can then be passed into AddServiceListener().

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility
and will be removed in the next major release. Use std::bind instead.

Template Parameters

R -- The type containing the member function.

Parameters
  • receiver -- The object of type R.
  • callback -- The member function pointer.
Returns

a ServiceListener object.

template<class R> BundleListener BundleListenerMemberFunctor(R *receiver, void (R::* callback)(BundleEvent const&))

A convenience function that binds the member function callback of an object of type R and returns a BundleListener object.

This object can then be passed into AddBundleListener().

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility
and will be removed in the next major release. Use std::bind instead.

Template Parameters

R -- The type containing the member function.

Parameters
  • receiver -- The object of type R.
  • callback -- The member function pointer.
Returns

a BundleListener object.

template<class R> FrameworkListener BindFrameworkListenerToFunctor(R *receiver, void (R::* callback)(FrameworkEvent const&))

A convenience function that binds the member function callback of an object of type R and returns a FrameworkListener object.

This object can then be passed into AddFrameworkListener().

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility
and will be removed in the next major release. Use std::bind instead.

Template Parameters

R -- The type containing the member function.

Parameters
  • receiver -- The object of type R.
  • callback -- The member function pointer.
Returns

a FrameworkListener object.

SharedLibrary

class SharedLibrary

The SharedLibrary class loads shared libraries at runtime.

Public Functions

SharedLibrary()

SharedLibrary(SharedLibrary const &other)

SharedLibrary(std::string const &libPath, std::string const &name)

Construct a SharedLibrary object using a library search path and a library base name.

Parameters
  • libPath -- An absolute path containing the shared library
  • name -- The base name of the shared library, without prefix and suffix.
SharedLibrary(std::string const &absoluteFilePath)

Construct a SharedLibrary object using an absolute file path to the shared library.

Using this constructor effectively disables all setters except SetFilePath().

Parameters

absoluteFilePath -- The absolute path to the shared library.

~SharedLibrary()

Destroys this object but does not unload the shared library.

SharedLibrary &operator=(SharedLibrary const &other)

void Load()

Loads the shared library pointed to by this SharedLibrary object.

On POSIX systems dlopen() is called with the RTLD_LAZY and RTLD_LOCAL flags unless the compiler is gcc 4.4.x or older. Then the RTLD_LAZY and RTLD_GLOBAL flags are used to load the shared library to work around RTTI problems across shared library boundaries.

Throws
  • std::logic_error -- If the library is already loaded.
  • std::system_error -- If loading the library failed.
void Load(int flags)

Loads the shared library pointed to by this SharedLibrary object, using the specified flags on POSIX systems.

Throws
  • std::logic_error -- If the library is already loaded.
  • std::system_error -- If loading the library failed.
void Unload()

Un-loads the shared library pointed to by this SharedLibrary object.

Throws

std::runtime_error -- If an error occurred while un-loading the shared library.

void SetName(std::string const &name)

Sets the base name of the shared library.

Does nothing if the shared library is already loaded or the SharedLibrary(const std::string&) constructor was used.

Parameters

name -- The base name of the shared library, without prefix and suffix.

std::string GetName() const

Gets the base name of the shared library.

Returns

The shared libraries base name.

std::string GetFilePath(std::string const &name) const

Gets the absolute file path for the shared library with base name name, using the search path returned by GetLibraryPath().

Parameters

name -- The shared library base name.

Returns

The absolute file path of the shared library.

void SetFilePath(std::string const &absoluteFilePath)

Sets the absolute file path of this SharedLibrary object.

Using this methods with a non-empty absoluteFilePath argument effectively disables all other setters.

Parameters

absoluteFilePath -- The new absolute file path of this SharedLibrary object.

std::string GetFilePath() const

Gets the absolute file path of this SharedLibrary object.

Returns

The absolute file path of the shared library.

void SetLibraryPath(std::string const &path)

Sets a new library search path.

Does nothing if the shared library is already loaded or the SharedLibrary(const std::string&) constructor was used.

Parameters

path -- The new shared library search path.

std::string GetLibraryPath() const

Gets the library search path of this SharedLibrary object.

Returns

The library search path.

void SetSuffix(std::string const &suffix)

Sets the suffix for shared library names (e.g.

lib). Does nothing if the shared library is already loaded or the SharedLibrary(const std::string&) constructor was used.

Parameters

suffix -- The shared library name suffix.

std::string GetSuffix() const

Gets the file name suffix of this SharedLibrary object.

Returns

The file name suffix of the shared library.

void SetPrefix(std::string const &prefix)

Sets the file name prefix for shared library names (e.g.

.dll or .so). Does nothing if the shared library is already loaded or the SharedLibrary(const std::string&) constructor was used.

Parameters

prefix -- The shared library name prefix.

std::string GetPrefix() const

Gets the file name prefix of this SharedLibrary object.

Returns

The file name prefix of the shared library.

void *GetHandle() const

Gets the internal handle of this SharedLibrary object.

Returns

nullptr if the shared library is not loaded, the operating system specific handle otherwise.

bool IsLoaded() const

Gets the loaded/unloaded stated of this SharedLibrary object.

Returns

true if the shared library is loaded, false otherwise.

ShrinkableMap

template<class Key, class T> class ShrinkableMap

A std::map style associative container allowing query and removal operations only.

Public Types

using container_type = std::map<Key, T>

using iterator = typename container_type::iterator

using const_iterator = typename container_type::const_iterator

using size_type = typename container_type::size_type

using key_type = typename container_type::key_type

using mapped_type = typename container_type::mapped_type

using value_type = typename container_type::value_type

using reference = typename container_type::reference

using const_reference = typename container_type::const_reference

Public Functions

inline ShrinkableMap()

inline iterator begin()

inline const_iterator begin() const

inline iterator end()

inline const_iterator end() const

inline void erase(iterator pos)

inline void erase(iterator first, iterator last)

inline size_type erase(Key const &key)

inline bool empty() const

inline void clear()

inline size_type size() const

inline size_type max_size() const

inline T &operator[](Key const &key)

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use at(size_type pos) instead.

inline T &at(Key const &key)

inline T const &at(Key const &key) const

inline size_type count(Key const &key) const

inline iterator find(Key const &key)

inline const_iterator find(Key const &key) const

inline std::pair<iterator, iterator> equal_range(Key const &key)

inline std::pair<const_iterator, const_iterator> equal_range(Key const &key) const

inline iterator lower_bound(Key const &key)

inline const_iterator lower_bound(Key const &key) const

inline iterator upper_bound(Key const &key)

inline const_iterator upper_bound(Key const &key) const

ShrinkableVector

template<class E> class ShrinkableVector

A std::vector style container allowing query and removal operations only.

Public Types

using container_type = std::vector<E>

using iterator = typename container_type::iterator

using const_iterator = typename container_type::const_iterator

using size_type = typename container_type::size_type

using reference = typename container_type::reference

using const_reference = typename container_type::const_reference

using value_type = typename container_type::value_type

Public Functions

inline ShrinkableVector()

inline iterator begin()

inline const_iterator begin() const

inline iterator end()

inline const_iterator end() const

inline reference front()

inline const_reference front() const

inline reference back()

inline const_reference back() const

inline iterator erase(iterator pos)

inline iterator erase(iterator first, iterator last)

inline void pop_back()

inline bool empty() const

inline void clear()

inline size_type size() const

inline reference at(size_type pos)

inline const_reference at(size_type pos) const

inline const_reference operator[](size_type i) const

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use at(size_type pos) instead.

inline reference operator[](size_type i)

Deprecated since version 3.1.0: This function exists only to maintain backwards compatibility and will be removed in the next major release. Use at(size_type pos) instead.

Macros

Preprocessor macros provided by CppMicroServices.

Cppmicroservices_initialize_bundle

CPPMICROSERVICES_INITIALIZE_BUNDLE

Creates initialization code for a bundle.

Each bundle which wants to register itself with the CppMicroServices library has to put a call to this macro in one of its source files. Further, the bundle's source files must be compiled with the US_BUNDLE_NAME pre-processor definition set to a bundle-unique identifier.

Calling the CPPMICROSERVICES_INITIALIZE_BUNDLE macro will initialize the bundle for use with the CppMicroServices library.

HINT:

If you are using CMake, consider using the provided CMake macro usFunctionGenerateBundleInit().

Cppmicroservices_initialize_static_bundle

CPPMICROSERVICES_INITIALIZE_STATIC_BUNDLE(_bundle_name)

Initialize a static bundle.

This macro initializes the static bundle named _bundle_name.

If the bundle provides an activator, use the Cppmicroservices_import_bundle macro instead, to ensure that the activator is referenced and can be called. Do not forget to actually link the static bundle to the importing executable or shared library.

SEE ALSO:

CPPMICROSERVICES_IMPORT_BUNDLE
Static Bundles
Parameters
  • _bundle_name -- The name of the bundle to initialize.

Cppmicroservices_import_bundle

CPPMICROSERVICES_IMPORT_BUNDLE(_bundle_name)

Import a static bundle.

This macro imports the static bundle named _bundle_name.

Inserting this macro into your application's source code will allow you to make use of a static bundle. It will initialize the static bundle and reference its BundleActivator. If the bundle does not provide an activator, use the Cppmicroservices_initialize_static_bundle macro instead. Do not forget to actually link the static bundle to the importing executable or shared library.

Example: .INDENT 7.0

#include "cppmicroservices/BundleImport.h"

CPPMICROSERVICES_IMPORT_BUNDLE(MyStaticBundle1)

SEE ALSO:

CPPMICROSERVICES_INITIALIZE_STATIC_BUNDLE
Static Bundles
Parameters
  • _bundle_name -- The name of the bundle to import.

Cppmicroservices_export_bundle_activator

WARNING:

doxygendefine: Cannot find define "CPPMICROSERVICES_EXPORT_BUNDLE_ACTIVATOR" in doxygen xml output for project "us" from directory: doc/_api/xml/

Cppmicroservices_declare_service_interface

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(_service_interface_type, _service_interface_id)

Declare a service interface id.

This macro associates the given identifier _service_interface_id (a string literal) to the interface class called _service_interface_type. The Identifier must be unique. For example:

#include "cppmicroservices/ServiceInterface.h"

struct ISomeInterace { ... };

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(ISomeInterface, "com.mycompany.service.ISomeInterface/1.0")

The usage of this macro is optional and the service interface id which is automatically associated with any type is usually good enough (the demangled type name). However, care must be taken if the default id is compared with a string literal hard-coding a service interface id. E.g. the default id for templated types in the STL may differ between platforms. For user-defined types and templates the ids are typically consistent, but platform specific default template arguments will lead to different ids.

This macro is normally used right after the class definition for _service_interface_type, in a header file.

If you want to use CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE with interface classes declared in a namespace then you have to make sure the CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE macro call is not inside a namespace though. For example:

#include "cppmicroservices/ServiceInterface.h"

namespace Foo
{
  struct ISomeInterface { ... };
}

CPPMICROSERVICES_DECLARE_SERVICE_INTERFACE(Foo::ISomeInterface, "com.mycompany.service.ISomeInterface/1.0")
Parameters
  • _service_interface_type -- The service interface type.
  • _service_interface_id -- A string literal representing a globally unique identifier.

Author

CppMicroServices Team

Info

Feb 05, 2025 3.8.5 C++ Micro Services