id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
9,600
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.__get_stored_instances
def __get_stored_instances(self, factory_name): # type: (str) -> List[StoredInstance] """ Retrieves the list of all stored instances objects corresponding to the given factory name :param factory_name: A factory name :return: All components instantiated from the given factory """ with self.__instances_lock: return [ stored_instance for stored_instance in self.__instances.values() if stored_instance.factory_name == factory_name ]
python
def __get_stored_instances(self, factory_name): # type: (str) -> List[StoredInstance] with self.__instances_lock: return [ stored_instance for stored_instance in self.__instances.values() if stored_instance.factory_name == factory_name ]
[ "def", "__get_stored_instances", "(", "self", ",", "factory_name", ")", ":", "# type: (str) -> List[StoredInstance]", "with", "self", ".", "__instances_lock", ":", "return", "[", "stored_instance", "for", "stored_instance", "in", "self", ".", "__instances", ".", "valu...
Retrieves the list of all stored instances objects corresponding to the given factory name :param factory_name: A factory name :return: All components instantiated from the given factory
[ "Retrieves", "the", "list", "of", "all", "stored", "instances", "objects", "corresponding", "to", "the", "given", "factory", "name" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L337-L351
9,601
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.__try_instantiate
def __try_instantiate(self, component_context, instance): # type: (ComponentContext, object) -> bool """ Instantiates a component, if all of its handlers are there. Returns False if a handler is missing. :param component_context: A ComponentContext bean :param instance: The component instance :return: True if the component has started, False if a handler is missing """ with self.__instances_lock: # Extract information about the component factory_context = component_context.factory_context handlers_ids = factory_context.get_handlers_ids() name = component_context.name factory_name = factory_context.name try: # Get handlers handler_factories = self.__get_handler_factories(handlers_ids) except KeyError: # A handler is missing, stop here return False # Instantiate the handlers all_handlers = set() # type: Set[Any] for handler_factory in handler_factories: handlers = handler_factory.get_handlers( component_context, instance ) if handlers: all_handlers.update(handlers) # Prepare the stored instance stored_instance = StoredInstance( self, component_context, instance, all_handlers ) # Manipulate the properties for handler in all_handlers: handler.manipulate(stored_instance, instance) # Store the instance self.__instances[name] = stored_instance # Start the manager stored_instance.start() # Notify listeners now that every thing is ready to run self._fire_ipopo_event( constants.IPopoEvent.INSTANTIATED, factory_name, name ) # Try to validate it stored_instance.update_bindings() stored_instance.check_lifecycle() return True
python
def __try_instantiate(self, component_context, instance): # type: (ComponentContext, object) -> bool with self.__instances_lock: # Extract information about the component factory_context = component_context.factory_context handlers_ids = factory_context.get_handlers_ids() name = component_context.name factory_name = factory_context.name try: # Get handlers handler_factories = self.__get_handler_factories(handlers_ids) except KeyError: # A handler is missing, stop here return False # Instantiate the handlers all_handlers = set() # type: Set[Any] for handler_factory in handler_factories: handlers = handler_factory.get_handlers( component_context, instance ) if handlers: all_handlers.update(handlers) # Prepare the stored instance stored_instance = StoredInstance( self, component_context, instance, all_handlers ) # Manipulate the properties for handler in all_handlers: handler.manipulate(stored_instance, instance) # Store the instance self.__instances[name] = stored_instance # Start the manager stored_instance.start() # Notify listeners now that every thing is ready to run self._fire_ipopo_event( constants.IPopoEvent.INSTANTIATED, factory_name, name ) # Try to validate it stored_instance.update_bindings() stored_instance.check_lifecycle() return True
[ "def", "__try_instantiate", "(", "self", ",", "component_context", ",", "instance", ")", ":", "# type: (ComponentContext, object) -> bool", "with", "self", ".", "__instances_lock", ":", "# Extract information about the component", "factory_context", "=", "component_context", ...
Instantiates a component, if all of its handlers are there. Returns False if a handler is missing. :param component_context: A ComponentContext bean :param instance: The component instance :return: True if the component has started, False if a handler is missing
[ "Instantiates", "a", "component", "if", "all", "of", "its", "handlers", "are", "there", ".", "Returns", "False", "if", "a", "handler", "is", "missing", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L353-L410
9,602
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._autorestart_store_components
def _autorestart_store_components(self, bundle): # type: (Bundle) -> None """ Stores the components of the given bundle with the auto-restart property :param bundle: A Bundle object """ with self.__instances_lock: # Prepare the list of components store = self.__auto_restart.setdefault(bundle, []) for stored_instance in self.__instances.values(): # Get the factory name factory = stored_instance.factory_name if self.get_factory_bundle(factory) is bundle: # Factory from this bundle # Test component properties properties = stored_instance.context.properties if properties.get(constants.IPOPO_AUTO_RESTART): # Auto-restart property found store.append( (factory, stored_instance.name, properties) )
python
def _autorestart_store_components(self, bundle): # type: (Bundle) -> None with self.__instances_lock: # Prepare the list of components store = self.__auto_restart.setdefault(bundle, []) for stored_instance in self.__instances.values(): # Get the factory name factory = stored_instance.factory_name if self.get_factory_bundle(factory) is bundle: # Factory from this bundle # Test component properties properties = stored_instance.context.properties if properties.get(constants.IPOPO_AUTO_RESTART): # Auto-restart property found store.append( (factory, stored_instance.name, properties) )
[ "def", "_autorestart_store_components", "(", "self", ",", "bundle", ")", ":", "# type: (Bundle) -> None", "with", "self", ".", "__instances_lock", ":", "# Prepare the list of components", "store", "=", "self", ".", "__auto_restart", ".", "setdefault", "(", "bundle", "...
Stores the components of the given bundle with the auto-restart property :param bundle: A Bundle object
[ "Stores", "the", "components", "of", "the", "given", "bundle", "with", "the", "auto", "-", "restart", "property" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L412-L434
9,603
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._autorestart_components
def _autorestart_components(self, bundle): # type: (Bundle) -> None """ Restart the components of the given bundle :param bundle: A Bundle object """ with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: # Nothing to do return for factory, name, properties in instances: try: # Instantiate the given component self.instantiate(factory, name, properties) except Exception as ex: # Log error, but continue to work _logger.exception( "Error restarting component '%s' ('%s') " "from bundle %s (%d): %s", name, factory, bundle.get_symbolic_name(), bundle.get_bundle_id(), ex, )
python
def _autorestart_components(self, bundle): # type: (Bundle) -> None with self.__instances_lock: instances = self.__auto_restart.get(bundle) if not instances: # Nothing to do return for factory, name, properties in instances: try: # Instantiate the given component self.instantiate(factory, name, properties) except Exception as ex: # Log error, but continue to work _logger.exception( "Error restarting component '%s' ('%s') " "from bundle %s (%d): %s", name, factory, bundle.get_symbolic_name(), bundle.get_bundle_id(), ex, )
[ "def", "_autorestart_components", "(", "self", ",", "bundle", ")", ":", "# type: (Bundle) -> None", "with", "self", ".", "__instances_lock", ":", "instances", "=", "self", ".", "__auto_restart", ".", "get", "(", "bundle", ")", "if", "not", "instances", ":", "#...
Restart the components of the given bundle :param bundle: A Bundle object
[ "Restart", "the", "components", "of", "the", "given", "bundle" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L436-L463
9,604
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._fire_ipopo_event
def _fire_ipopo_event(self, kind, factory_name, instance_name=None): # type: (int, str, Optional[str]) -> None """ Triggers an iPOPO event :param kind: Kind of event :param factory_name: Name of the factory associated to the event :param instance_name: Name of the component instance associated to the event """ with self.__listeners_lock: # Use a copy of the list of listeners listeners = self.__listeners[:] for listener in listeners: try: listener.handle_ipopo_event( constants.IPopoEvent(kind, factory_name, instance_name) ) except: _logger.exception("Error calling an iPOPO event handler")
python
def _fire_ipopo_event(self, kind, factory_name, instance_name=None): # type: (int, str, Optional[str]) -> None with self.__listeners_lock: # Use a copy of the list of listeners listeners = self.__listeners[:] for listener in listeners: try: listener.handle_ipopo_event( constants.IPopoEvent(kind, factory_name, instance_name) ) except: _logger.exception("Error calling an iPOPO event handler")
[ "def", "_fire_ipopo_event", "(", "self", ",", "kind", ",", "factory_name", ",", "instance_name", "=", "None", ")", ":", "# type: (int, str, Optional[str]) -> None", "with", "self", ".", "__listeners_lock", ":", "# Use a copy of the list of listeners", "listeners", "=", ...
Triggers an iPOPO event :param kind: Kind of event :param factory_name: Name of the factory associated to the event :param instance_name: Name of the component instance associated to the event
[ "Triggers", "an", "iPOPO", "event" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L479-L499
9,605
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._prepare_instance_properties
def _prepare_instance_properties(self, properties, factory_properties): # type: (dict, dict) -> dict """ Prepares the properties of a component instance, based on its configuration, factory and framework properties :param properties: Component instance properties :param factory_properties: Component factory "default" properties :return: The merged properties """ # Normalize given properties if properties is None or not isinstance(properties, dict): properties = {} # Use framework properties to fill missing ones framework = self.__context.get_framework() for property_name in factory_properties: if property_name not in properties: # Missing property value = framework.get_property(property_name) if value is not None: # Set the property value properties[property_name] = value return properties
python
def _prepare_instance_properties(self, properties, factory_properties): # type: (dict, dict) -> dict # Normalize given properties if properties is None or not isinstance(properties, dict): properties = {} # Use framework properties to fill missing ones framework = self.__context.get_framework() for property_name in factory_properties: if property_name not in properties: # Missing property value = framework.get_property(property_name) if value is not None: # Set the property value properties[property_name] = value return properties
[ "def", "_prepare_instance_properties", "(", "self", ",", "properties", ",", "factory_properties", ")", ":", "# type: (dict, dict) -> dict", "# Normalize given properties", "if", "properties", "is", "None", "or", "not", "isinstance", "(", "properties", ",", "dict", ")", ...
Prepares the properties of a component instance, based on its configuration, factory and framework properties :param properties: Component instance properties :param factory_properties: Component factory "default" properties :return: The merged properties
[ "Prepares", "the", "properties", "of", "a", "component", "instance", "based", "on", "its", "configuration", "factory", "and", "framework", "properties" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L501-L525
9,606
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._register_bundle_factories
def _register_bundle_factories(self, bundle): # type: (Bundle) -> None """ Registers all factories found in the given bundle :param bundle: A bundle """ # Load the bundle factories factories = _load_bundle_factories(bundle) for context, factory_class in factories: try: # Register each found factory self._register_factory(context.name, factory_class, False) except ValueError as ex: # Already known factory _logger.error( "Cannot register factory '%s' of bundle %d (%s): %s", context.name, bundle.get_bundle_id(), bundle.get_symbolic_name(), ex, ) _logger.error( "class: %s -- module: %s", factory_class, factory_class.__module__, ) else: # Instantiate components for name, properties in context.get_instances().items(): self.instantiate(context.name, name, properties)
python
def _register_bundle_factories(self, bundle): # type: (Bundle) -> None # Load the bundle factories factories = _load_bundle_factories(bundle) for context, factory_class in factories: try: # Register each found factory self._register_factory(context.name, factory_class, False) except ValueError as ex: # Already known factory _logger.error( "Cannot register factory '%s' of bundle %d (%s): %s", context.name, bundle.get_bundle_id(), bundle.get_symbolic_name(), ex, ) _logger.error( "class: %s -- module: %s", factory_class, factory_class.__module__, ) else: # Instantiate components for name, properties in context.get_instances().items(): self.instantiate(context.name, name, properties)
[ "def", "_register_bundle_factories", "(", "self", ",", "bundle", ")", ":", "# type: (Bundle) -> None", "# Load the bundle factories", "factories", "=", "_load_bundle_factories", "(", "bundle", ")", "for", "context", ",", "factory_class", "in", "factories", ":", "try", ...
Registers all factories found in the given bundle :param bundle: A bundle
[ "Registers", "all", "factories", "found", "in", "the", "given", "bundle" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L527-L558
9,607
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._register_factory
def _register_factory(self, factory_name, factory, override): # type: (str, type, bool) -> None """ Registers a component factory :param factory_name: The name of the factory :param factory: The factory class object :param override: If true, previous factory is overridden, else an exception is risen if a previous factory with that name already exists :raise ValueError: The factory name already exists or is invalid :raise TypeError: Invalid factory type """ if not factory_name or not is_string(factory_name): raise ValueError("A factory name must be a non-empty string") if not inspect.isclass(factory): raise TypeError( "Invalid factory class '{0}'".format(type(factory).__name__) ) with self.__factories_lock: if factory_name in self.__factories: if override: _logger.info("Overriding factory '%s'", factory_name) else: raise ValueError( "'{0}' factory already exist".format(factory_name) ) self.__factories[factory_name] = factory # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.REGISTERED, factory_name )
python
def _register_factory(self, factory_name, factory, override): # type: (str, type, bool) -> None if not factory_name or not is_string(factory_name): raise ValueError("A factory name must be a non-empty string") if not inspect.isclass(factory): raise TypeError( "Invalid factory class '{0}'".format(type(factory).__name__) ) with self.__factories_lock: if factory_name in self.__factories: if override: _logger.info("Overriding factory '%s'", factory_name) else: raise ValueError( "'{0}' factory already exist".format(factory_name) ) self.__factories[factory_name] = factory # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.REGISTERED, factory_name )
[ "def", "_register_factory", "(", "self", ",", "factory_name", ",", "factory", ",", "override", ")", ":", "# type: (str, type, bool) -> None", "if", "not", "factory_name", "or", "not", "is_string", "(", "factory_name", ")", ":", "raise", "ValueError", "(", "\"A fac...
Registers a component factory :param factory_name: The name of the factory :param factory: The factory class object :param override: If true, previous factory is overridden, else an exception is risen if a previous factory with that name already exists :raise ValueError: The factory name already exists or is invalid :raise TypeError: Invalid factory type
[ "Registers", "a", "component", "factory" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L560-L595
9,608
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService._unregister_bundle_factories
def _unregister_bundle_factories(self, bundle): # type: (Bundle) -> None """ Unregisters all factories of the given bundle :param bundle: A bundle """ with self.__factories_lock: # Find out which factories must be removed to_remove = [ factory_name for factory_name in self.__factories if self.get_factory_bundle(factory_name) is bundle ] # Remove all of them for factory_name in to_remove: try: self.unregister_factory(factory_name) except ValueError as ex: _logger.warning( "Error unregistering factory '%s': %s", factory_name, ex )
python
def _unregister_bundle_factories(self, bundle): # type: (Bundle) -> None with self.__factories_lock: # Find out which factories must be removed to_remove = [ factory_name for factory_name in self.__factories if self.get_factory_bundle(factory_name) is bundle ] # Remove all of them for factory_name in to_remove: try: self.unregister_factory(factory_name) except ValueError as ex: _logger.warning( "Error unregistering factory '%s': %s", factory_name, ex )
[ "def", "_unregister_bundle_factories", "(", "self", ",", "bundle", ")", ":", "# type: (Bundle) -> None", "with", "self", ".", "__factories_lock", ":", "# Find out which factories must be removed", "to_remove", "=", "[", "factory_name", "for", "factory_name", "in", "self",...
Unregisters all factories of the given bundle :param bundle: A bundle
[ "Unregisters", "all", "factories", "of", "the", "given", "bundle" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L606-L628
9,609
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.bundle_changed
def bundle_changed(self, event): # type: (BundleEvent) -> None """ A bundle event has been triggered :param event: The bundle event """ kind = event.get_kind() bundle = event.get_bundle() if kind == BundleEvent.STOPPING_PRECLEAN: # A bundle is gone, remove its factories after the deactivator has # been called. That way, the deactivator can kill manually started # components. self._unregister_bundle_factories(bundle) elif kind == BundleEvent.STARTED: # A bundle is staring, register its factories before its activator # is called. That way, the activator can use the registered # factories. self._register_bundle_factories(bundle) elif kind == BundleEvent.UPDATE_BEGIN: # A bundle will be updated, store its auto-restart component self._autorestart_store_components(bundle) elif kind == BundleEvent.UPDATED: # Update has finished, restart stored components self._autorestart_components(bundle) self._autorestart_clear_components(bundle) elif kind == BundleEvent.UPDATE_FAILED: # Update failed, clean the stored components self._autorestart_clear_components(bundle)
python
def bundle_changed(self, event): # type: (BundleEvent) -> None kind = event.get_kind() bundle = event.get_bundle() if kind == BundleEvent.STOPPING_PRECLEAN: # A bundle is gone, remove its factories after the deactivator has # been called. That way, the deactivator can kill manually started # components. self._unregister_bundle_factories(bundle) elif kind == BundleEvent.STARTED: # A bundle is staring, register its factories before its activator # is called. That way, the activator can use the registered # factories. self._register_bundle_factories(bundle) elif kind == BundleEvent.UPDATE_BEGIN: # A bundle will be updated, store its auto-restart component self._autorestart_store_components(bundle) elif kind == BundleEvent.UPDATED: # Update has finished, restart stored components self._autorestart_components(bundle) self._autorestart_clear_components(bundle) elif kind == BundleEvent.UPDATE_FAILED: # Update failed, clean the stored components self._autorestart_clear_components(bundle)
[ "def", "bundle_changed", "(", "self", ",", "event", ")", ":", "# type: (BundleEvent) -> None", "kind", "=", "event", ".", "get_kind", "(", ")", "bundle", "=", "event", ".", "get_bundle", "(", ")", "if", "kind", "==", "BundleEvent", ".", "STOPPING_PRECLEAN", ...
A bundle event has been triggered :param event: The bundle event
[ "A", "bundle", "event", "has", "been", "triggered" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L654-L687
9,610
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.instantiate
def instantiate(self, factory_name, name, properties=None): # type: (str, str, dict) -> Any """ Instantiates a component from the given factory, with the given name :param factory_name: Name of the component factory :param name: Name of the instance to be started :param properties: Initial properties of the component instance :return: The component instance :raise TypeError: The given factory is unknown :raise ValueError: The given name or factory name is invalid, or an instance with the given name already exists :raise Exception: Something wrong occurred in the factory """ # Test parameters if not factory_name or not is_string(factory_name): raise ValueError("Invalid factory name") if not name or not is_string(name): raise ValueError("Invalid component name") if not self.running: # Stop working if the framework is stopping raise ValueError("Framework is stopping") with self.__instances_lock: if name in self.__instances or name in self.__waiting_handlers: raise ValueError( "'{0}' is an already running instance name".format(name) ) with self.__factories_lock: # Can raise a TypeError exception factory, factory_context = self.__get_factory_with_context( factory_name ) # Check if the factory is singleton and if a component is # already started if ( factory_context.is_singleton and factory_context.is_singleton_active ): raise ValueError( "{0} is a singleton: {1} can't be " "instantiated.".format(factory_name, name) ) # Create component instance try: instance = factory() except Exception: _logger.exception( "Error creating the instance '%s' from factory '%s'", name, factory_name, ) raise TypeError( "Factory '{0}' failed to create '{1}'".format( factory_name, name ) ) # Instantiation succeeded: update singleton status if factory_context.is_singleton: factory_context.is_singleton_active = True # Normalize the given properties properties = self._prepare_instance_properties( properties, factory_context.properties ) # Set up the component instance context component_context = ComponentContext( factory_context, name, properties ) # Try to instantiate the component immediately if not self.__try_instantiate(component_context, instance): # A handler is missing, put the component in the queue self.__waiting_handlers[name] = (component_context, instance) return instance
python
def instantiate(self, factory_name, name, properties=None): # type: (str, str, dict) -> Any # Test parameters if not factory_name or not is_string(factory_name): raise ValueError("Invalid factory name") if not name or not is_string(name): raise ValueError("Invalid component name") if not self.running: # Stop working if the framework is stopping raise ValueError("Framework is stopping") with self.__instances_lock: if name in self.__instances or name in self.__waiting_handlers: raise ValueError( "'{0}' is an already running instance name".format(name) ) with self.__factories_lock: # Can raise a TypeError exception factory, factory_context = self.__get_factory_with_context( factory_name ) # Check if the factory is singleton and if a component is # already started if ( factory_context.is_singleton and factory_context.is_singleton_active ): raise ValueError( "{0} is a singleton: {1} can't be " "instantiated.".format(factory_name, name) ) # Create component instance try: instance = factory() except Exception: _logger.exception( "Error creating the instance '%s' from factory '%s'", name, factory_name, ) raise TypeError( "Factory '{0}' failed to create '{1}'".format( factory_name, name ) ) # Instantiation succeeded: update singleton status if factory_context.is_singleton: factory_context.is_singleton_active = True # Normalize the given properties properties = self._prepare_instance_properties( properties, factory_context.properties ) # Set up the component instance context component_context = ComponentContext( factory_context, name, properties ) # Try to instantiate the component immediately if not self.__try_instantiate(component_context, instance): # A handler is missing, put the component in the queue self.__waiting_handlers[name] = (component_context, instance) return instance
[ "def", "instantiate", "(", "self", ",", "factory_name", ",", "name", ",", "properties", "=", "None", ")", ":", "# type: (str, str, dict) -> Any", "# Test parameters", "if", "not", "factory_name", "or", "not", "is_string", "(", "factory_name", ")", ":", "raise", ...
Instantiates a component from the given factory, with the given name :param factory_name: Name of the component factory :param name: Name of the instance to be started :param properties: Initial properties of the component instance :return: The component instance :raise TypeError: The given factory is unknown :raise ValueError: The given name or factory name is invalid, or an instance with the given name already exists :raise Exception: Something wrong occurred in the factory
[ "Instantiates", "a", "component", "from", "the", "given", "factory", "with", "the", "given", "name" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L708-L790
9,611
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.retry_erroneous
def retry_erroneous(self, name, properties_update=None): # type: (str, dict) -> int """ Removes the ERRONEOUS state of the given component, and retries a validation :param name: Name of the component to retry :param properties_update: A dictionary to update the initial properties of the component :return: The new state of the component :raise ValueError: Invalid component name """ with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: return stored_instance.retry_erroneous(properties_update)
python
def retry_erroneous(self, name, properties_update=None): # type: (str, dict) -> int with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: return stored_instance.retry_erroneous(properties_update)
[ "def", "retry_erroneous", "(", "self", ",", "name", ",", "properties_update", "=", "None", ")", ":", "# type: (str, dict) -> int", "with", "self", ".", "__instances_lock", ":", "try", ":", "stored_instance", "=", "self", ".", "__instances", "[", "name", "]", "...
Removes the ERRONEOUS state of the given component, and retries a validation :param name: Name of the component to retry :param properties_update: A dictionary to update the initial properties of the component :return: The new state of the component :raise ValueError: Invalid component name
[ "Removes", "the", "ERRONEOUS", "state", "of", "the", "given", "component", "and", "retries", "a", "validation" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L792-L812
9,612
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.invalidate
def invalidate(self, name): # type: (str) -> None """ Invalidates the given component :param name: Name of the component to invalidate :raise ValueError: Invalid component name """ with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: # Call back the component during the invalidation stored_instance.invalidate(True)
python
def invalidate(self, name): # type: (str) -> None with self.__instances_lock: try: stored_instance = self.__instances[name] except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) ) else: # Call back the component during the invalidation stored_instance.invalidate(True)
[ "def", "invalidate", "(", "self", ",", "name", ")", ":", "# type: (str) -> None", "with", "self", ".", "__instances_lock", ":", "try", ":", "stored_instance", "=", "self", ".", "__instances", "[", "name", "]", "except", "KeyError", ":", "raise", "ValueError", ...
Invalidates the given component :param name: Name of the component to invalidate :raise ValueError: Invalid component name
[ "Invalidates", "the", "given", "component" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L814-L831
9,613
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.kill
def kill(self, name): # type: (str) -> None """ Kills the given component :param name: Name of the component to kill :raise ValueError: Invalid component name """ if not name: raise ValueError("Name can't be None or empty") with self.__instances_lock: try: # Running instance stored_instance = self.__instances.pop(name) # Store the reference to the factory context factory_context = stored_instance.context.factory_context # Kill it stored_instance.kill() # Update the singleton state flag factory_context.is_singleton_active = False except KeyError: # Queued instance try: # Extract the component context context, _ = self.__waiting_handlers.pop(name) # Update the singleton state flag context.factory_context.is_singleton_active = False except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) )
python
def kill(self, name): # type: (str) -> None if not name: raise ValueError("Name can't be None or empty") with self.__instances_lock: try: # Running instance stored_instance = self.__instances.pop(name) # Store the reference to the factory context factory_context = stored_instance.context.factory_context # Kill it stored_instance.kill() # Update the singleton state flag factory_context.is_singleton_active = False except KeyError: # Queued instance try: # Extract the component context context, _ = self.__waiting_handlers.pop(name) # Update the singleton state flag context.factory_context.is_singleton_active = False except KeyError: raise ValueError( "Unknown component instance '{0}'".format(name) )
[ "def", "kill", "(", "self", ",", "name", ")", ":", "# type: (str) -> None", "if", "not", "name", ":", "raise", "ValueError", "(", "\"Name can't be None or empty\"", ")", "with", "self", ".", "__instances_lock", ":", "try", ":", "# Running instance", "stored_instan...
Kills the given component :param name: Name of the component to kill :raise ValueError: Invalid component name
[ "Kills", "the", "given", "component" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L854-L889
9,614
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.register_factory
def register_factory(self, bundle_context, factory): # type: (BundleContext, type) -> bool """ Registers a manually created factory, using decorators programmatically :param bundle_context: The factory bundle context :param factory: A manipulated class :return: True if the factory has been registered :raise ValueError: Invalid parameter, or factory already registered :raise TypeError: Invalid factory type (not a manipulated class) """ if factory is None or bundle_context is None: # Invalid parameter, to nothing raise ValueError("Invalid parameter") context = _set_factory_context(factory, bundle_context) if not context: raise TypeError("Not a manipulated class (no context found)") self._register_factory(context.name, factory, False) return True
python
def register_factory(self, bundle_context, factory): # type: (BundleContext, type) -> bool if factory is None or bundle_context is None: # Invalid parameter, to nothing raise ValueError("Invalid parameter") context = _set_factory_context(factory, bundle_context) if not context: raise TypeError("Not a manipulated class (no context found)") self._register_factory(context.name, factory, False) return True
[ "def", "register_factory", "(", "self", ",", "bundle_context", ",", "factory", ")", ":", "# type: (BundleContext, type) -> bool", "if", "factory", "is", "None", "or", "bundle_context", "is", "None", ":", "# Invalid parameter, to nothing", "raise", "ValueError", "(", "...
Registers a manually created factory, using decorators programmatically :param bundle_context: The factory bundle context :param factory: A manipulated class :return: True if the factory has been registered :raise ValueError: Invalid parameter, or factory already registered :raise TypeError: Invalid factory type (not a manipulated class)
[ "Registers", "a", "manually", "created", "factory", "using", "decorators", "programmatically" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L891-L911
9,615
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.unregister_factory
def unregister_factory(self, factory_name): # type: (str) -> bool """ Unregisters the given component factory :param factory_name: Name of the factory to unregister :return: True the factory has been removed, False if the factory is unknown """ if not factory_name or not is_string(factory_name): # Invalid name return False with self.__factories_lock: try: # Remove the factory from the registry factory_class = self.__factories.pop(factory_name) except KeyError: # Unknown factory return False # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.UNREGISTERED, factory_name ) # Invalidate and delete all components of this factory with self.__instances_lock: # Compute the list of __instances to remove to_remove = self.__get_stored_instances(factory_name) # Remove instances from the registry: avoids dependencies \ # update to link against a component from this factory again. for instance in to_remove: try: # Kill the instance self.kill(instance.name) except ValueError: # Unknown instance: already killed by the invalidation # callback of a component killed in this loop # => ignore pass # Remove waiting component names = [ name for name, (context, _) in self.__waiting_handlers.items() if context.factory_context.name == factory_name ] for name in names: del self.__waiting_handlers[name] # Clear the bundle context of the factory _set_factory_context(factory_class, None) return True
python
def unregister_factory(self, factory_name): # type: (str) -> bool if not factory_name or not is_string(factory_name): # Invalid name return False with self.__factories_lock: try: # Remove the factory from the registry factory_class = self.__factories.pop(factory_name) except KeyError: # Unknown factory return False # Trigger an event self._fire_ipopo_event( constants.IPopoEvent.UNREGISTERED, factory_name ) # Invalidate and delete all components of this factory with self.__instances_lock: # Compute the list of __instances to remove to_remove = self.__get_stored_instances(factory_name) # Remove instances from the registry: avoids dependencies \ # update to link against a component from this factory again. for instance in to_remove: try: # Kill the instance self.kill(instance.name) except ValueError: # Unknown instance: already killed by the invalidation # callback of a component killed in this loop # => ignore pass # Remove waiting component names = [ name for name, (context, _) in self.__waiting_handlers.items() if context.factory_context.name == factory_name ] for name in names: del self.__waiting_handlers[name] # Clear the bundle context of the factory _set_factory_context(factory_class, None) return True
[ "def", "unregister_factory", "(", "self", ",", "factory_name", ")", ":", "# type: (str) -> bool", "if", "not", "factory_name", "or", "not", "is_string", "(", "factory_name", ")", ":", "# Invalid name", "return", "False", "with", "self", ".", "__factories_lock", ":...
Unregisters the given component factory :param factory_name: Name of the factory to unregister :return: True the factory has been removed, False if the factory is unknown
[ "Unregisters", "the", "given", "component", "factory" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L913-L968
9,616
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.get_instances
def get_instances(self): # type: () -> List[Tuple[str, str, int]] """ Retrieves the list of the currently registered component instances :return: A list of (name, factory name, state) tuples. """ with self.__instances_lock: return sorted( (name, stored_instance.factory_name, stored_instance.state) for name, stored_instance in self.__instances.items() )
python
def get_instances(self): # type: () -> List[Tuple[str, str, int]] with self.__instances_lock: return sorted( (name, stored_instance.factory_name, stored_instance.state) for name, stored_instance in self.__instances.items() )
[ "def", "get_instances", "(", "self", ")", ":", "# type: () -> List[Tuple[str, str, int]]", "with", "self", ".", "__instances_lock", ":", "return", "sorted", "(", "(", "name", ",", "stored_instance", ".", "factory_name", ",", "stored_instance", ".", "state", ")", "...
Retrieves the list of the currently registered component instances :return: A list of (name, factory name, state) tuples.
[ "Retrieves", "the", "list", "of", "the", "currently", "registered", "component", "instances" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L998-L1009
9,617
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.get_waiting_components
def get_waiting_components(self): # type: () -> List[Tuple[str, str, Set[str]]] """ Returns the list of the instances waiting for their handlers :return: A list of (name, factory name, missing handlers) tuples """ with self.__instances_lock: result = [] for name, (context, _) in self.__waiting_handlers.items(): # Compute missing handlers missing = set(context.factory_context.get_handlers_ids()) missing.difference_update(self._handlers.keys()) result.append((name, context.factory_context.name, missing)) result.sort() return result
python
def get_waiting_components(self): # type: () -> List[Tuple[str, str, Set[str]]] with self.__instances_lock: result = [] for name, (context, _) in self.__waiting_handlers.items(): # Compute missing handlers missing = set(context.factory_context.get_handlers_ids()) missing.difference_update(self._handlers.keys()) result.append((name, context.factory_context.name, missing)) result.sort() return result
[ "def", "get_waiting_components", "(", "self", ")", ":", "# type: () -> List[Tuple[str, str, Set[str]]]", "with", "self", ".", "__instances_lock", ":", "result", "=", "[", "]", "for", "name", ",", "(", "context", ",", "_", ")", "in", "self", ".", "__waiting_handl...
Returns the list of the instances waiting for their handlers :return: A list of (name, factory name, missing handlers) tuples
[ "Returns", "the", "list", "of", "the", "instances", "waiting", "for", "their", "handlers" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L1022-L1039
9,618
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.get_factory_bundle
def get_factory_bundle(self, name): # type: (str) -> Bundle """ Retrieves the Pelix Bundle object that registered the given factory :param name: The name of a factory :return: The Bundle that registered the given factory :raise ValueError: Invalid factory """ with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) else: # Bundle Context is stored in the Factory Context factory_context = getattr( factory, constants.IPOPO_FACTORY_CONTEXT ) return factory_context.bundle_context.get_bundle()
python
def get_factory_bundle(self, name): # type: (str) -> Bundle with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) else: # Bundle Context is stored in the Factory Context factory_context = getattr( factory, constants.IPOPO_FACTORY_CONTEXT ) return factory_context.bundle_context.get_bundle()
[ "def", "get_factory_bundle", "(", "self", ",", "name", ")", ":", "# type: (str) -> Bundle", "with", "self", ".", "__factories_lock", ":", "try", ":", "factory", "=", "self", ".", "__factories", "[", "name", "]", "except", "KeyError", ":", "raise", "ValueError"...
Retrieves the Pelix Bundle object that registered the given factory :param name: The name of a factory :return: The Bundle that registered the given factory :raise ValueError: Invalid factory
[ "Retrieves", "the", "Pelix", "Bundle", "object", "that", "registered", "the", "given", "factory" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L1148-L1167
9,619
tcalmant/ipopo
pelix/ipopo/core.py
_IPopoService.get_factory_details
def get_factory_details(self, name): # type: (str) -> Dict[str, Any] """ Retrieves a dictionary with details about the given factory * ``name``: The factory name * ``bundle``: The Bundle object of the bundle providing the factory * ``properties``: Copy of the components properties defined by the factory * ``requirements``: List of the requirements defined by the factory * ``id``: Requirement ID (field where it is injected) * ``specification``: Specification of the required service * ``aggregate``: If True, multiple services will be injected * ``optional``: If True, the requirement is optional * ``services``: List of the specifications of the services provided by components of this factory * ``handlers``: Dictionary of the non-built-in handlers required by this factory. The dictionary keys are handler IDs, and it contains a tuple with: * A copy of the configuration of the handler (0) * A flag indicating if the handler is present or not :param name: The name of a factory :return: A dictionary describing the factory :raise ValueError: Invalid factory """ with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) context = getattr(factory, constants.IPOPO_FACTORY_CONTEXT) assert isinstance(context, FactoryContext) result = {} # type: Dict[Any, Any] # Factory name & bundle result["name"] = context.name result["bundle"] = context.bundle_context.get_bundle() # Configurable properties # Name -> Default value result["properties"] = { prop_name: context.properties.get(prop_name) for prop_name in context.properties_fields.values() } # Requirements (list of dictionaries) reqs = result["requirements"] = [] handler_requires = context.get_handler(constants.HANDLER_REQUIRES) if handler_requires is not None: for field, requirement in handler_requires.items(): reqs.append( { "id": field, "specification": requirement.specification, "aggregate": requirement.aggregate, "optional": requirement.optional, "filter": requirement.original_filter, } ) # Provided services (list of list of specifications) handler_provides = context.get_handler(constants.HANDLER_PROVIDES) if handler_provides is not None: result["services"] = [ specs_controller[0] for specs_controller in handler_provides ] else: result["services"] = [] # Other handlers handlers = set(context.get_handlers_ids()) handlers.difference_update( ( constants.HANDLER_PROPERTY, constants.HANDLER_PROVIDES, constants.HANDLER_REQUIRES, ) ) result["handlers"] = { handler: copy.deepcopy(context.get_handler(handler)) for handler in handlers } return result
python
def get_factory_details(self, name): # type: (str) -> Dict[str, Any] with self.__factories_lock: try: factory = self.__factories[name] except KeyError: raise ValueError("Unknown factory '{0}'".format(name)) context = getattr(factory, constants.IPOPO_FACTORY_CONTEXT) assert isinstance(context, FactoryContext) result = {} # type: Dict[Any, Any] # Factory name & bundle result["name"] = context.name result["bundle"] = context.bundle_context.get_bundle() # Configurable properties # Name -> Default value result["properties"] = { prop_name: context.properties.get(prop_name) for prop_name in context.properties_fields.values() } # Requirements (list of dictionaries) reqs = result["requirements"] = [] handler_requires = context.get_handler(constants.HANDLER_REQUIRES) if handler_requires is not None: for field, requirement in handler_requires.items(): reqs.append( { "id": field, "specification": requirement.specification, "aggregate": requirement.aggregate, "optional": requirement.optional, "filter": requirement.original_filter, } ) # Provided services (list of list of specifications) handler_provides = context.get_handler(constants.HANDLER_PROVIDES) if handler_provides is not None: result["services"] = [ specs_controller[0] for specs_controller in handler_provides ] else: result["services"] = [] # Other handlers handlers = set(context.get_handlers_ids()) handlers.difference_update( ( constants.HANDLER_PROPERTY, constants.HANDLER_PROVIDES, constants.HANDLER_REQUIRES, ) ) result["handlers"] = { handler: copy.deepcopy(context.get_handler(handler)) for handler in handlers } return result
[ "def", "get_factory_details", "(", "self", ",", "name", ")", ":", "# type: (str) -> Dict[str, Any]", "with", "self", ".", "__factories_lock", ":", "try", ":", "factory", "=", "self", ".", "__factories", "[", "name", "]", "except", "KeyError", ":", "raise", "Va...
Retrieves a dictionary with details about the given factory * ``name``: The factory name * ``bundle``: The Bundle object of the bundle providing the factory * ``properties``: Copy of the components properties defined by the factory * ``requirements``: List of the requirements defined by the factory * ``id``: Requirement ID (field where it is injected) * ``specification``: Specification of the required service * ``aggregate``: If True, multiple services will be injected * ``optional``: If True, the requirement is optional * ``services``: List of the specifications of the services provided by components of this factory * ``handlers``: Dictionary of the non-built-in handlers required by this factory. The dictionary keys are handler IDs, and it contains a tuple with: * A copy of the configuration of the handler (0) * A flag indicating if the handler is present or not :param name: The name of a factory :return: A dictionary describing the factory :raise ValueError: Invalid factory
[ "Retrieves", "a", "dictionary", "with", "details", "about", "the", "given", "factory" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/core.py#L1169-L1257
9,620
tcalmant/ipopo
pelix/ipv6utils.py
set_double_stack
def set_double_stack(socket_obj, double_stack=True): # type: (socket.socket, bool) -> None """ Sets up the IPv6 double stack according to the operating system :param socket_obj: A socket object :param double_stack: If True, use the double stack, else only support IPv6 :raise AttributeError: Python or system doesn't support V6 :raise socket.error: Error setting up the double stack value """ try: # Use existing value opt_ipv6_only = socket.IPV6_V6ONLY except AttributeError: # Use "known" value if os.name == "nt": # Windows: see ws2ipdef.h opt_ipv6_only = 27 elif platform.system() == "Linux": # Linux: see linux/in6.h (in recent kernels) opt_ipv6_only = 26 else: # Unknown value: do nothing raise # Setup the socket (can raise a socket.error) socket_obj.setsockopt(ipproto_ipv6(), opt_ipv6_only, int(not double_stack))
python
def set_double_stack(socket_obj, double_stack=True): # type: (socket.socket, bool) -> None try: # Use existing value opt_ipv6_only = socket.IPV6_V6ONLY except AttributeError: # Use "known" value if os.name == "nt": # Windows: see ws2ipdef.h opt_ipv6_only = 27 elif platform.system() == "Linux": # Linux: see linux/in6.h (in recent kernels) opt_ipv6_only = 26 else: # Unknown value: do nothing raise # Setup the socket (can raise a socket.error) socket_obj.setsockopt(ipproto_ipv6(), opt_ipv6_only, int(not double_stack))
[ "def", "set_double_stack", "(", "socket_obj", ",", "double_stack", "=", "True", ")", ":", "# type: (socket.socket, bool) -> None", "try", ":", "# Use existing value", "opt_ipv6_only", "=", "socket", ".", "IPV6_V6ONLY", "except", "AttributeError", ":", "# Use \"known\" val...
Sets up the IPv6 double stack according to the operating system :param socket_obj: A socket object :param double_stack: If True, use the double stack, else only support IPv6 :raise AttributeError: Python or system doesn't support V6 :raise socket.error: Error setting up the double stack value
[ "Sets", "up", "the", "IPv6", "double", "stack", "according", "to", "the", "operating", "system" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipv6utils.py#L64-L90
9,621
tcalmant/ipopo
pelix/ldapfilter.py
escape_LDAP
def escape_LDAP(ldap_string): # type: (str) -> str # pylint: disable=C0103 """ Escape a string to let it go in an LDAP filter :param ldap_string: The string to escape :return: The protected string """ if not ldap_string: # No content return ldap_string # Protect escape character previously in the string assert is_string(ldap_string) ldap_string = ldap_string.replace( ESCAPE_CHARACTER, ESCAPE_CHARACTER + ESCAPE_CHARACTER ) # Leading space if ldap_string.startswith(" "): ldap_string = "\\ {0}".format(ldap_string[1:]) # Trailing space if ldap_string.endswith(" "): ldap_string = "{0}\\ ".format(ldap_string[:-1]) # Escape other characters for escaped in ESCAPED_CHARACTERS: ldap_string = ldap_string.replace(escaped, ESCAPE_CHARACTER + escaped) return ldap_string
python
def escape_LDAP(ldap_string): # type: (str) -> str # pylint: disable=C0103 if not ldap_string: # No content return ldap_string # Protect escape character previously in the string assert is_string(ldap_string) ldap_string = ldap_string.replace( ESCAPE_CHARACTER, ESCAPE_CHARACTER + ESCAPE_CHARACTER ) # Leading space if ldap_string.startswith(" "): ldap_string = "\\ {0}".format(ldap_string[1:]) # Trailing space if ldap_string.endswith(" "): ldap_string = "{0}\\ ".format(ldap_string[:-1]) # Escape other characters for escaped in ESCAPED_CHARACTERS: ldap_string = ldap_string.replace(escaped, ESCAPE_CHARACTER + escaped) return ldap_string
[ "def", "escape_LDAP", "(", "ldap_string", ")", ":", "# type: (str) -> str", "# pylint: disable=C0103", "if", "not", "ldap_string", ":", "# No content", "return", "ldap_string", "# Protect escape character previously in the string", "assert", "is_string", "(", "ldap_string", "...
Escape a string to let it go in an LDAP filter :param ldap_string: The string to escape :return: The protected string
[ "Escape", "a", "string", "to", "let", "it", "go", "in", "an", "LDAP", "filter" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L308-L339
9,622
tcalmant/ipopo
pelix/ldapfilter.py
unescape_LDAP
def unescape_LDAP(ldap_string): # type: (str) -> str # pylint: disable=C0103 """ Unespaces an LDAP string :param ldap_string: The string to unescape :return: The unprotected string """ if ldap_string is None: return None if ESCAPE_CHARACTER not in ldap_string: # No need to loop return ldap_string escaped = False result = "" for character in ldap_string: if not escaped and character == ESCAPE_CHARACTER: # Escape character found escaped = True else: # Copy the character escaped = False result += character return result
python
def unescape_LDAP(ldap_string): # type: (str) -> str # pylint: disable=C0103 if ldap_string is None: return None if ESCAPE_CHARACTER not in ldap_string: # No need to loop return ldap_string escaped = False result = "" for character in ldap_string: if not escaped and character == ESCAPE_CHARACTER: # Escape character found escaped = True else: # Copy the character escaped = False result += character return result
[ "def", "unescape_LDAP", "(", "ldap_string", ")", ":", "# type: (str) -> str", "# pylint: disable=C0103", "if", "ldap_string", "is", "None", ":", "return", "None", "if", "ESCAPE_CHARACTER", "not", "in", "ldap_string", ":", "# No need to loop", "return", "ldap_string", ...
Unespaces an LDAP string :param ldap_string: The string to unescape :return: The unprotected string
[ "Unespaces", "an", "LDAP", "string" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L342-L370
9,623
tcalmant/ipopo
pelix/ldapfilter.py
_comparator_presence
def _comparator_presence(_, tested_value): """ Tests a filter which simply a joker, i.e. a value presence test """ # The filter value is a joker : simple presence test if tested_value is None: return False elif hasattr(tested_value, "__len__"): # Refuse empty values # pylint: disable=C1801 return len(tested_value) != 0 # Presence validated return True
python
def _comparator_presence(_, tested_value): # The filter value is a joker : simple presence test if tested_value is None: return False elif hasattr(tested_value, "__len__"): # Refuse empty values # pylint: disable=C1801 return len(tested_value) != 0 # Presence validated return True
[ "def", "_comparator_presence", "(", "_", ",", "tested_value", ")", ":", "# The filter value is a joker : simple presence test", "if", "tested_value", "is", "None", ":", "return", "False", "elif", "hasattr", "(", "tested_value", ",", "\"__len__\"", ")", ":", "# Refuse ...
Tests a filter which simply a joker, i.e. a value presence test
[ "Tests", "a", "filter", "which", "simply", "a", "joker", "i", ".", "e", ".", "a", "value", "presence", "test" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L380-L393
9,624
tcalmant/ipopo
pelix/ldapfilter.py
_comparator_eq
def _comparator_eq(filter_value, tested_value): """ Tests if the filter value is equal to the tested value """ if isinstance(tested_value, ITERABLES): # Convert the list items to strings for value in tested_value: # Try with the string conversion if not is_string(value): value = repr(value) if filter_value == value: # Match ! return True # Standard comparison elif not is_string(tested_value): # String vs string representation return filter_value == repr(tested_value) else: # String vs string return filter_value == tested_value return False
python
def _comparator_eq(filter_value, tested_value): if isinstance(tested_value, ITERABLES): # Convert the list items to strings for value in tested_value: # Try with the string conversion if not is_string(value): value = repr(value) if filter_value == value: # Match ! return True # Standard comparison elif not is_string(tested_value): # String vs string representation return filter_value == repr(tested_value) else: # String vs string return filter_value == tested_value return False
[ "def", "_comparator_eq", "(", "filter_value", ",", "tested_value", ")", ":", "if", "isinstance", "(", "tested_value", ",", "ITERABLES", ")", ":", "# Convert the list items to strings", "for", "value", "in", "tested_value", ":", "# Try with the string conversion", "if", ...
Tests if the filter value is equal to the tested value
[ "Tests", "if", "the", "filter", "value", "is", "equal", "to", "the", "tested", "value" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L452-L474
9,625
tcalmant/ipopo
pelix/ldapfilter.py
_comparator_approximate
def _comparator_approximate(filter_value, tested_value): """ Tests if the filter value is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms """ lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_eq(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_eq(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_eq(filter_value, tested_value) or _comparator_eq( lower_filter_value, tested_value )
python
def _comparator_approximate(filter_value, tested_value): lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_eq(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_eq(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_eq(filter_value, tested_value) or _comparator_eq( lower_filter_value, tested_value )
[ "def", "_comparator_approximate", "(", "filter_value", ",", "tested_value", ")", ":", "lower_filter_value", "=", "filter_value", ".", "lower", "(", ")", "if", "is_string", "(", "tested_value", ")", ":", "# Lower case comparison", "return", "_comparator_eq", "(", "lo...
Tests if the filter value is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms
[ "Tests", "if", "the", "filter", "value", "is", "nearly", "equal", "to", "the", "tested", "value", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L477-L503
9,626
tcalmant/ipopo
pelix/ldapfilter.py
_comparator_approximate_star
def _comparator_approximate_star(filter_value, tested_value): """ Tests if the filter value, which contains a joker, is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms """ lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_star(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_star(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_star(filter_value, tested_value) or _comparator_star( lower_filter_value, tested_value )
python
def _comparator_approximate_star(filter_value, tested_value): lower_filter_value = filter_value.lower() if is_string(tested_value): # Lower case comparison return _comparator_star(lower_filter_value, tested_value.lower()) elif hasattr(tested_value, "__iter__"): # Extract a list of strings new_tested = [ value.lower() for value in tested_value if is_string(value) ] if _comparator_star(lower_filter_value, new_tested): # Value found in the strings return True # Compare the raw values return _comparator_star(filter_value, tested_value) or _comparator_star( lower_filter_value, tested_value )
[ "def", "_comparator_approximate_star", "(", "filter_value", ",", "tested_value", ")", ":", "lower_filter_value", "=", "filter_value", ".", "lower", "(", ")", "if", "is_string", "(", "tested_value", ")", ":", "# Lower case comparison", "return", "_comparator_star", "("...
Tests if the filter value, which contains a joker, is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms
[ "Tests", "if", "the", "filter", "value", "which", "contains", "a", "joker", "is", "nearly", "equal", "to", "the", "tested", "value", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L506-L533
9,627
tcalmant/ipopo
pelix/ldapfilter.py
_comparator_lt
def _comparator_lt(filter_value, tested_value): """ Tests if the filter value is strictly greater than the tested value tested_value < filter_value """ if is_string(filter_value): value_type = type(tested_value) try: # Try a conversion filter_value = value_type(filter_value) except (TypeError, ValueError): if value_type is int: # Integer/float comparison trick try: filter_value = float(filter_value) except (TypeError, ValueError): # None-float value return False else: # Incompatible type return False try: return tested_value < filter_value except TypeError: # Incompatible type return False
python
def _comparator_lt(filter_value, tested_value): if is_string(filter_value): value_type = type(tested_value) try: # Try a conversion filter_value = value_type(filter_value) except (TypeError, ValueError): if value_type is int: # Integer/float comparison trick try: filter_value = float(filter_value) except (TypeError, ValueError): # None-float value return False else: # Incompatible type return False try: return tested_value < filter_value except TypeError: # Incompatible type return False
[ "def", "_comparator_lt", "(", "filter_value", ",", "tested_value", ")", ":", "if", "is_string", "(", "filter_value", ")", ":", "value_type", "=", "type", "(", "tested_value", ")", "try", ":", "# Try a conversion", "filter_value", "=", "value_type", "(", "filter_...
Tests if the filter value is strictly greater than the tested value tested_value < filter_value
[ "Tests", "if", "the", "filter", "value", "is", "strictly", "greater", "than", "the", "tested", "value" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L547-L574
9,628
tcalmant/ipopo
pelix/ldapfilter.py
_compute_comparator
def _compute_comparator(string, idx): # type: (str, int) -> Optional[Callable[[Any, Any], bool]] """ Tries to compute the LDAP comparator at the given index Valid operators are : * = : equality * <= : less than * >= : greater than * ~= : approximate :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator, None if unknown """ part1 = string[idx] try: part2 = string[idx + 1] except IndexError: # String is too short (no comparison) return None if part1 == "=": # Equality return _comparator_eq elif part2 != "=": # It's a "strict" operator if part1 == "<": # Strictly lesser return _comparator_lt elif part1 == ">": # Strictly greater return _comparator_gt else: if part1 == "<": # Less or equal return _comparator_le elif part1 == ">": # Greater or equal return _comparator_ge elif part1 == "~": # Approximate equality return _comparator_approximate return None
python
def _compute_comparator(string, idx): # type: (str, int) -> Optional[Callable[[Any, Any], bool]] part1 = string[idx] try: part2 = string[idx + 1] except IndexError: # String is too short (no comparison) return None if part1 == "=": # Equality return _comparator_eq elif part2 != "=": # It's a "strict" operator if part1 == "<": # Strictly lesser return _comparator_lt elif part1 == ">": # Strictly greater return _comparator_gt else: if part1 == "<": # Less or equal return _comparator_le elif part1 == ">": # Greater or equal return _comparator_ge elif part1 == "~": # Approximate equality return _comparator_approximate return None
[ "def", "_compute_comparator", "(", "string", ",", "idx", ")", ":", "# type: (str, int) -> Optional[Callable[[Any, Any], bool]]", "part1", "=", "string", "[", "idx", "]", "try", ":", "part2", "=", "string", "[", "idx", "+", "1", "]", "except", "IndexError", ":", ...
Tries to compute the LDAP comparator at the given index Valid operators are : * = : equality * <= : less than * >= : greater than * ~= : approximate :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator, None if unknown
[ "Tries", "to", "compute", "the", "LDAP", "comparator", "at", "the", "given", "index" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L660-L704
9,629
tcalmant/ipopo
pelix/ldapfilter.py
_compute_operation
def _compute_operation(string, idx): # type: (str, int) -> Optional[int] """ Tries to compute the LDAP operation at the given index Valid operations are : * & : AND * | : OR * ! : NOT :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator (AND, OR or NOT) """ operator = string[idx] if operator == "&": return AND elif operator == "|": return OR elif operator == "!": return NOT return None
python
def _compute_operation(string, idx): # type: (str, int) -> Optional[int] operator = string[idx] if operator == "&": return AND elif operator == "|": return OR elif operator == "!": return NOT return None
[ "def", "_compute_operation", "(", "string", ",", "idx", ")", ":", "# type: (str, int) -> Optional[int]", "operator", "=", "string", "[", "idx", "]", "if", "operator", "==", "\"&\"", ":", "return", "AND", "elif", "operator", "==", "\"|\"", ":", "return", "OR", ...
Tries to compute the LDAP operation at the given index Valid operations are : * & : AND * | : OR * ! : NOT :param string: A LDAP filter string :param idx: An index in the given string :return: The corresponding operator (AND, OR or NOT)
[ "Tries", "to", "compute", "the", "LDAP", "operation", "at", "the", "given", "index" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L707-L730
9,630
tcalmant/ipopo
pelix/ldapfilter.py
_skip_spaces
def _skip_spaces(string, idx): # type: (str, int) -> int """ Retrieves the next non-space character after idx index in the given string :param string: The string to look into :param idx: The base search index :return: The next non-space character index, -1 if not found """ i = idx for char in string[idx:]: if not char.isspace(): return i i += 1 return -1
python
def _skip_spaces(string, idx): # type: (str, int) -> int i = idx for char in string[idx:]: if not char.isspace(): return i i += 1 return -1
[ "def", "_skip_spaces", "(", "string", ",", "idx", ")", ":", "# type: (str, int) -> int", "i", "=", "idx", "for", "char", "in", "string", "[", "idx", ":", "]", ":", "if", "not", "char", ".", "isspace", "(", ")", ":", "return", "i", "i", "+=", "1", "...
Retrieves the next non-space character after idx index in the given string :param string: The string to look into :param idx: The base search index :return: The next non-space character index, -1 if not found
[ "Retrieves", "the", "next", "non", "-", "space", "character", "after", "idx", "index", "in", "the", "given", "string" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L733-L748
9,631
tcalmant/ipopo
pelix/ldapfilter.py
_parse_ldap
def _parse_ldap(ldap_filter): # type: (str) -> Optional[LDAPFilter] """ Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid """ if ldap_filter is None: # Nothing to do return None assert is_string(ldap_filter) # Remove surrounding spaces ldap_filter = ldap_filter.strip() if not ldap_filter: # Empty string return None escaped = False filter_len = len(ldap_filter) root = None stack = [] subfilter_stack = [] idx = 0 while idx < filter_len: if not escaped: if ldap_filter[idx] == "(": # Opening filter : get the operator idx = _skip_spaces(ldap_filter, idx + 1) if idx == -1: raise ValueError( "Missing filter operator: {0}".format(ldap_filter) ) operator = _compute_operation(ldap_filter, idx) if operator is not None: # New sub-filter stack.append(LDAPFilter(operator)) else: # Sub-filter content subfilter_stack.append(idx) elif ldap_filter[idx] == ")": # Ending filter : store it in its parent if subfilter_stack: # criterion finished start_idx = subfilter_stack.pop() criterion = _parse_ldap_criteria( ldap_filter, start_idx, idx ) if stack: top = stack.pop() top.append(criterion) stack.append(top) else: # No parent : filter contains only one criterion # Make a parent to stay homogeneous root = LDAPFilter(AND) root.append(criterion) elif stack: # Sub filter finished ended_filter = stack.pop() if stack: top = stack.pop() top.append(ended_filter) stack.append(top) else: # End of the parse root = ended_filter else: raise ValueError( "Too many end of parenthesis:{0}: {1}".format( idx, ldap_filter[idx:] ) ) elif ldap_filter[idx] == "\\": # Next character must be ignored escaped = True else: # Escaped character ignored escaped = False # Don't forget to increment... idx += 1 # No root : invalid content if root is None: raise ValueError("Invalid filter string: {0}".format(ldap_filter)) # Return the root of the filter return root.normalize()
python
def _parse_ldap(ldap_filter): # type: (str) -> Optional[LDAPFilter] if ldap_filter is None: # Nothing to do return None assert is_string(ldap_filter) # Remove surrounding spaces ldap_filter = ldap_filter.strip() if not ldap_filter: # Empty string return None escaped = False filter_len = len(ldap_filter) root = None stack = [] subfilter_stack = [] idx = 0 while idx < filter_len: if not escaped: if ldap_filter[idx] == "(": # Opening filter : get the operator idx = _skip_spaces(ldap_filter, idx + 1) if idx == -1: raise ValueError( "Missing filter operator: {0}".format(ldap_filter) ) operator = _compute_operation(ldap_filter, idx) if operator is not None: # New sub-filter stack.append(LDAPFilter(operator)) else: # Sub-filter content subfilter_stack.append(idx) elif ldap_filter[idx] == ")": # Ending filter : store it in its parent if subfilter_stack: # criterion finished start_idx = subfilter_stack.pop() criterion = _parse_ldap_criteria( ldap_filter, start_idx, idx ) if stack: top = stack.pop() top.append(criterion) stack.append(top) else: # No parent : filter contains only one criterion # Make a parent to stay homogeneous root = LDAPFilter(AND) root.append(criterion) elif stack: # Sub filter finished ended_filter = stack.pop() if stack: top = stack.pop() top.append(ended_filter) stack.append(top) else: # End of the parse root = ended_filter else: raise ValueError( "Too many end of parenthesis:{0}: {1}".format( idx, ldap_filter[idx:] ) ) elif ldap_filter[idx] == "\\": # Next character must be ignored escaped = True else: # Escaped character ignored escaped = False # Don't forget to increment... idx += 1 # No root : invalid content if root is None: raise ValueError("Invalid filter string: {0}".format(ldap_filter)) # Return the root of the filter return root.normalize()
[ "def", "_parse_ldap", "(", "ldap_filter", ")", ":", "# type: (str) -> Optional[LDAPFilter]", "if", "ldap_filter", "is", "None", ":", "# Nothing to do", "return", "None", "assert", "is_string", "(", "ldap_filter", ")", "# Remove surrounding spaces", "ldap_filter", "=", "...
Parses the given LDAP filter string :param ldap_filter: An LDAP filter string :return: An LDAPFilter object, None if the filter was empty :raise ValueError: The LDAP filter string is invalid
[ "Parses", "the", "given", "LDAP", "filter", "string" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L834-L929
9,632
tcalmant/ipopo
pelix/ldapfilter.py
get_ldap_filter
def get_ldap_filter(ldap_filter): # type: (Any) -> Optional[Union[LDAPFilter, LDAPCriteria]] """ Retrieves the LDAP filter object corresponding to the given filter. Parses it the argument if it is an LDAPFilter instance :param ldap_filter: An LDAP filter (LDAPFilter or string) :return: The corresponding filter, can be None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type """ if ldap_filter is None: return None if isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): # No conversion needed return ldap_filter elif is_string(ldap_filter): # Parse the filter return _parse_ldap(ldap_filter) # Unknown type raise TypeError( "Unhandled filter type {0}".format(type(ldap_filter).__name__) )
python
def get_ldap_filter(ldap_filter): # type: (Any) -> Optional[Union[LDAPFilter, LDAPCriteria]] if ldap_filter is None: return None if isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): # No conversion needed return ldap_filter elif is_string(ldap_filter): # Parse the filter return _parse_ldap(ldap_filter) # Unknown type raise TypeError( "Unhandled filter type {0}".format(type(ldap_filter).__name__) )
[ "def", "get_ldap_filter", "(", "ldap_filter", ")", ":", "# type: (Any) -> Optional[Union[LDAPFilter, LDAPCriteria]]", "if", "ldap_filter", "is", "None", ":", "return", "None", "if", "isinstance", "(", "ldap_filter", ",", "(", "LDAPFilter", ",", "LDAPCriteria", ")", ")...
Retrieves the LDAP filter object corresponding to the given filter. Parses it the argument if it is an LDAPFilter instance :param ldap_filter: An LDAP filter (LDAPFilter or string) :return: The corresponding filter, can be None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type
[ "Retrieves", "the", "LDAP", "filter", "object", "corresponding", "to", "the", "given", "filter", ".", "Parses", "it", "the", "argument", "if", "it", "is", "an", "LDAPFilter", "instance" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L932-L956
9,633
tcalmant/ipopo
pelix/ldapfilter.py
combine_filters
def combine_filters(filters, operator=AND): # type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]] """ Combines two LDAP filters, which can be strings or LDAPFilter objects :param filters: Filters to combine :param operator: The operator for combination :return: The combined filter, can be None if all filters are None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type """ if not filters: return None if not hasattr(filters, "__iter__") or is_string(filters): raise TypeError("Filters argument must be iterable") # Remove None filters and convert others ldap_filters = [] for sub_filter in filters: if sub_filter is None: # Ignore None filters continue ldap_filter = get_ldap_filter(sub_filter) if ldap_filter is not None: # Valid filter ldap_filters.append(ldap_filter) if not ldap_filters: # Do nothing return None elif len(ldap_filters) == 1: # Only one filter, return it return ldap_filters[0] new_filter = LDAPFilter(operator) for sub_filter in ldap_filters: # Direct combination new_filter.append(sub_filter) return new_filter.normalize()
python
def combine_filters(filters, operator=AND): # type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]] if not filters: return None if not hasattr(filters, "__iter__") or is_string(filters): raise TypeError("Filters argument must be iterable") # Remove None filters and convert others ldap_filters = [] for sub_filter in filters: if sub_filter is None: # Ignore None filters continue ldap_filter = get_ldap_filter(sub_filter) if ldap_filter is not None: # Valid filter ldap_filters.append(ldap_filter) if not ldap_filters: # Do nothing return None elif len(ldap_filters) == 1: # Only one filter, return it return ldap_filters[0] new_filter = LDAPFilter(operator) for sub_filter in ldap_filters: # Direct combination new_filter.append(sub_filter) return new_filter.normalize()
[ "def", "combine_filters", "(", "filters", ",", "operator", "=", "AND", ")", ":", "# type: (Iterable[Any], int) -> Optional[Union[LDAPFilter, LDAPCriteria]]", "if", "not", "filters", ":", "return", "None", "if", "not", "hasattr", "(", "filters", ",", "\"__iter__\"", ")...
Combines two LDAP filters, which can be strings or LDAPFilter objects :param filters: Filters to combine :param operator: The operator for combination :return: The combined filter, can be None if all filters are None :raise ValueError: Invalid filter string found :raise TypeError: Unknown filter type
[ "Combines", "two", "LDAP", "filters", "which", "can", "be", "strings", "or", "LDAPFilter", "objects" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L959-L1000
9,634
tcalmant/ipopo
pelix/ldapfilter.py
LDAPFilter.append
def append(self, ldap_filter): """ Appends a filter or a criterion to this filter :param ldap_filter: An LDAP filter or criterion :raise TypeError: If the parameter is not of a known type :raise ValueError: If the more than one filter is associated to a NOT operator """ if not isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): raise TypeError( "Invalid filter type: {0}".format(type(ldap_filter).__name__) ) if len(self.subfilters) >= 1 and self.operator == NOT: raise ValueError("Not operator only handles one child") self.subfilters.append(ldap_filter)
python
def append(self, ldap_filter): if not isinstance(ldap_filter, (LDAPFilter, LDAPCriteria)): raise TypeError( "Invalid filter type: {0}".format(type(ldap_filter).__name__) ) if len(self.subfilters) >= 1 and self.operator == NOT: raise ValueError("Not operator only handles one child") self.subfilters.append(ldap_filter)
[ "def", "append", "(", "self", ",", "ldap_filter", ")", ":", "if", "not", "isinstance", "(", "ldap_filter", ",", "(", "LDAPFilter", ",", "LDAPCriteria", ")", ")", ":", "raise", "TypeError", "(", "\"Invalid filter type: {0}\"", ".", "format", "(", "type", "(",...
Appends a filter or a criterion to this filter :param ldap_filter: An LDAP filter or criterion :raise TypeError: If the parameter is not of a known type :raise ValueError: If the more than one filter is associated to a NOT operator
[ "Appends", "a", "filter", "or", "a", "criterion", "to", "this", "filter" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L139-L156
9,635
tcalmant/ipopo
pelix/ldapfilter.py
LDAPFilter.matches
def matches(self, properties): """ Tests if the given properties matches this LDAP filter and its children :param properties: A dictionary of properties :return: True if the properties matches this filter, else False """ # Use a generator, and declare it outside of the method call # => seems to be quite a speed up trick generator = ( criterion.matches(properties) for criterion in self.subfilters ) # Extract "if" from loops and use built-in methods if self.operator == OR: result = any(generator) else: result = all(generator) if self.operator == NOT: # Revert result return not result return result
python
def matches(self, properties): # Use a generator, and declare it outside of the method call # => seems to be quite a speed up trick generator = ( criterion.matches(properties) for criterion in self.subfilters ) # Extract "if" from loops and use built-in methods if self.operator == OR: result = any(generator) else: result = all(generator) if self.operator == NOT: # Revert result return not result return result
[ "def", "matches", "(", "self", ",", "properties", ")", ":", "# Use a generator, and declare it outside of the method call", "# => seems to be quite a speed up trick", "generator", "=", "(", "criterion", ".", "matches", "(", "properties", ")", "for", "criterion", "in", "se...
Tests if the given properties matches this LDAP filter and its children :param properties: A dictionary of properties :return: True if the properties matches this filter, else False
[ "Tests", "if", "the", "given", "properties", "matches", "this", "LDAP", "filter", "and", "its", "children" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L158-L180
9,636
tcalmant/ipopo
pelix/ldapfilter.py
LDAPFilter.normalize
def normalize(self): """ Returns the first meaningful object in this filter. """ if not self.subfilters: # No sub-filters return None # New sub-filters list new_filters = [] for subfilter in self.subfilters: # Normalize the sub-filter before storing it norm_filter = subfilter.normalize() if norm_filter is not None and norm_filter not in new_filters: new_filters.append(norm_filter) # Update the instance self.subfilters = new_filters size = len(self.subfilters) if size > 1 or self.operator == NOT: # Normal filter or NOT # NOT is the only operator to accept 1 operand return self # Return the only child as the filter object return self.subfilters[0].normalize()
python
def normalize(self): if not self.subfilters: # No sub-filters return None # New sub-filters list new_filters = [] for subfilter in self.subfilters: # Normalize the sub-filter before storing it norm_filter = subfilter.normalize() if norm_filter is not None and norm_filter not in new_filters: new_filters.append(norm_filter) # Update the instance self.subfilters = new_filters size = len(self.subfilters) if size > 1 or self.operator == NOT: # Normal filter or NOT # NOT is the only operator to accept 1 operand return self # Return the only child as the filter object return self.subfilters[0].normalize()
[ "def", "normalize", "(", "self", ")", ":", "if", "not", "self", ".", "subfilters", ":", "# No sub-filters", "return", "None", "# New sub-filters list", "new_filters", "=", "[", "]", "for", "subfilter", "in", "self", ".", "subfilters", ":", "# Normalize the sub-f...
Returns the first meaningful object in this filter.
[ "Returns", "the", "first", "meaningful", "object", "in", "this", "filter", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L182-L208
9,637
tcalmant/ipopo
pelix/ldapfilter.py
LDAPCriteria.matches
def matches(self, properties): """ Tests if the given criterion matches this LDAP criterion :param properties: A dictionary of properties :return: True if the properties matches this criterion, else False """ try: # Use the comparator return self.comparator(self.value, properties[self.name]) except KeyError: # Criterion key is not in the properties return False
python
def matches(self, properties): try: # Use the comparator return self.comparator(self.value, properties[self.name]) except KeyError: # Criterion key is not in the properties return False
[ "def", "matches", "(", "self", ",", "properties", ")", ":", "try", ":", "# Use the comparator", "return", "self", ".", "comparator", "(", "self", ".", "value", ",", "properties", "[", "self", ".", "name", "]", ")", "except", "KeyError", ":", "# Criterion k...
Tests if the given criterion matches this LDAP criterion :param properties: A dictionary of properties :return: True if the properties matches this criterion, else False
[ "Tests", "if", "the", "given", "criterion", "matches", "this", "LDAP", "criterion" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ldapfilter.py#L284-L296
9,638
tcalmant/ipopo
samples/run_remote.py
InstallUtils.discovery_multicast
def discovery_multicast(self): """ Installs the multicast discovery bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.discovery.multicast").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MULTICAST, "pelix-discovery-multicast" )
python
def discovery_multicast(self): # Install the bundle self.context.install_bundle("pelix.remote.discovery.multicast").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MULTICAST, "pelix-discovery-multicast" )
[ "def", "discovery_multicast", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.discovery.multicast\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as"...
Installs the multicast discovery bundles and instantiates components
[ "Installs", "the", "multicast", "discovery", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L88-L99
9,639
tcalmant/ipopo
samples/run_remote.py
InstallUtils.discovery_mdns
def discovery_mdns(self): """ Installs the mDNS discovery bundles and instantiates components """ # Remove Zeroconf debug output logging.getLogger("zeroconf").setLevel(logging.WARNING) # Install the bundle self.context.install_bundle("pelix.remote.discovery.mdns").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add(rs.FACTORY_DISCOVERY_ZEROCONF, "pelix-discovery-zeroconf")
python
def discovery_mdns(self): # Remove Zeroconf debug output logging.getLogger("zeroconf").setLevel(logging.WARNING) # Install the bundle self.context.install_bundle("pelix.remote.discovery.mdns").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add(rs.FACTORY_DISCOVERY_ZEROCONF, "pelix-discovery-zeroconf")
[ "def", "discovery_mdns", "(", "self", ")", ":", "# Remove Zeroconf debug output", "logging", ".", "getLogger", "(", "\"zeroconf\"", ")", ".", "setLevel", "(", "logging", ".", "WARNING", ")", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(...
Installs the mDNS discovery bundles and instantiates components
[ "Installs", "the", "mDNS", "discovery", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L101-L113
9,640
tcalmant/ipopo
samples/run_remote.py
InstallUtils.discovery_mqtt
def discovery_mqtt(self): """ Installs the MQTT discovery bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.discovery.mqtt").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MQTT, "pelix-discovery-mqtt", { "application.id": "sample.rs", "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
python
def discovery_mqtt(self): # Install the bundle self.context.install_bundle("pelix.remote.discovery.mqtt").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_MQTT, "pelix-discovery-mqtt", { "application.id": "sample.rs", "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
[ "def", "discovery_mqtt", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.discovery.mqtt\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipopo...
Installs the MQTT discovery bundles and instantiates components
[ "Installs", "the", "MQTT", "discovery", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L115-L132
9,641
tcalmant/ipopo
samples/run_remote.py
InstallUtils.discovery_redis
def discovery_redis(self): """ Installs the Redis discovery bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.discovery.redis").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_REDIS, "pelix-discovery-redis", { "application.id": "sample.rs", "redis.host": self.arguments.redis_host, "redis.port": self.arguments.redis_port, }, )
python
def discovery_redis(self): # Install the bundle self.context.install_bundle("pelix.remote.discovery.redis").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_REDIS, "pelix-discovery-redis", { "application.id": "sample.rs", "redis.host": self.arguments.redis_host, "redis.port": self.arguments.redis_port, }, )
[ "def", "discovery_redis", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.discovery.redis\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipo...
Installs the Redis discovery bundles and instantiates components
[ "Installs", "the", "Redis", "discovery", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L134-L151
9,642
tcalmant/ipopo
samples/run_remote.py
InstallUtils.discovery_zookeeper
def discovery_zookeeper(self): """ Installs the ZooKeeper discovery bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.discovery.zookeeper").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_ZOOKEEPER, "pelix-discovery-zookeeper", { "application.id": "sample.rs", "zookeeper.hosts": self.arguments.zk_hosts, "zookeeper.prefix": self.arguments.zk_prefix, }, )
python
def discovery_zookeeper(self): # Install the bundle self.context.install_bundle("pelix.remote.discovery.zookeeper").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_DISCOVERY_ZOOKEEPER, "pelix-discovery-zookeeper", { "application.id": "sample.rs", "zookeeper.hosts": self.arguments.zk_hosts, "zookeeper.prefix": self.arguments.zk_prefix, }, )
[ "def", "discovery_zookeeper", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.discovery.zookeeper\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as"...
Installs the ZooKeeper discovery bundles and instantiates components
[ "Installs", "the", "ZooKeeper", "discovery", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L153-L170
9,643
tcalmant/ipopo
samples/run_remote.py
InstallUtils.transport_jsonrpc
def transport_jsonrpc(self): """ Installs the JSON-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.json_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_EXPORTER, "pelix-jsonrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_IMPORTER, "pelix-jsonrpc-importer" )
python
def transport_jsonrpc(self): # Install the bundle self.context.install_bundle("pelix.remote.json_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_EXPORTER, "pelix-jsonrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_JSONRPC_IMPORTER, "pelix-jsonrpc-importer" )
[ "def", "transport_jsonrpc", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.json_rpc\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipopo", ...
Installs the JSON-RPC transport bundles and instantiates components
[ "Installs", "the", "JSON", "-", "RPC", "transport", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L172-L186
9,644
tcalmant/ipopo
samples/run_remote.py
InstallUtils.transport_jabsorbrpc
def transport_jabsorbrpc(self): """ Installs the JABSORB-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle( "pelix.remote.transport.jabsorb_rpc" ).start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER, "pelix-jabsorbrpc-exporter", ) ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_IMPORTER, "pelix-jabsorbrpc-importer", )
python
def transport_jabsorbrpc(self): # Install the bundle self.context.install_bundle( "pelix.remote.transport.jabsorb_rpc" ).start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_EXPORTER, "pelix-jabsorbrpc-exporter", ) ipopo.add( rs.FACTORY_TRANSPORT_JABSORBRPC_IMPORTER, "pelix-jabsorbrpc-importer", )
[ "def", "transport_jabsorbrpc", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.transport.jabsorb_rpc\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "...
Installs the JABSORB-RPC transport bundles and instantiates components
[ "Installs", "the", "JABSORB", "-", "RPC", "transport", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L188-L206
9,645
tcalmant/ipopo
samples/run_remote.py
InstallUtils.transport_mqttrpc
def transport_mqttrpc(self): """ Installs the MQTT-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.transport.mqtt_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_EXPORTER, "pelix-mqttrpc-exporter", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, ) ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_IMPORTER, "pelix-mqttrpc-importer", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
python
def transport_mqttrpc(self): # Install the bundle self.context.install_bundle("pelix.remote.transport.mqtt_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_EXPORTER, "pelix-mqttrpc-exporter", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, ) ipopo.add( rs.FACTORY_TRANSPORT_MQTTRPC_IMPORTER, "pelix-mqttrpc-importer", { "mqtt.host": self.arguments.mqtt_host, "mqtt.port": self.arguments.mqtt_port, }, )
[ "def", "transport_mqttrpc", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.transport.mqtt_rpc\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", ...
Installs the MQTT-RPC transport bundles and instantiates components
[ "Installs", "the", "MQTT", "-", "RPC", "transport", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L208-L232
9,646
tcalmant/ipopo
samples/run_remote.py
InstallUtils.transport_xmlrpc
def transport_xmlrpc(self): """ Installs the XML-RPC transport bundles and instantiates components """ # Install the bundle self.context.install_bundle("pelix.remote.xml_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_EXPORTER, "pelix-xmlrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_IMPORTER, "pelix-xmlrpc-importer" )
python
def transport_xmlrpc(self): # Install the bundle self.context.install_bundle("pelix.remote.xml_rpc").start() with use_waiting_list(self.context) as ipopo: # Instantiate the discovery ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_EXPORTER, "pelix-xmlrpc-exporter" ) ipopo.add( rs.FACTORY_TRANSPORT_XMLRPC_IMPORTER, "pelix-xmlrpc-importer" )
[ "def", "transport_xmlrpc", "(", "self", ")", ":", "# Install the bundle", "self", ".", "context", ".", "install_bundle", "(", "\"pelix.remote.xml_rpc\"", ")", ".", "start", "(", ")", "with", "use_waiting_list", "(", "self", ".", "context", ")", "as", "ipopo", ...
Installs the XML-RPC transport bundles and instantiates components
[ "Installs", "the", "XML", "-", "RPC", "transport", "bundles", "and", "instantiates", "components" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/run_remote.py#L234-L248
9,647
tcalmant/ipopo
pelix/services/configadmin.py
Configuration.get_properties
def get_properties(self): """ Return the properties of this Configuration object. The Dictionary object returned is a private copy for the caller and may be changed without influencing the stored configuration. If called just after the configuration is created and before update has been called, this method returns None. :return: A private copy of the properties for the caller or null. These properties must not contain the "service.bundleLocation" property. The value of this property may be obtained from the get_bundle_location() method. """ with self.__lock: if self.__deleted: raise ValueError("{0} has been deleted".format(self.__pid)) elif not self.__updated: # Fresh configuration return None # Filter a copy of the properties props = self.__properties.copy() try: del props[services.CONFIG_PROP_BUNDLE_LOCATION] except KeyError: # Ignore pass return props
python
def get_properties(self): with self.__lock: if self.__deleted: raise ValueError("{0} has been deleted".format(self.__pid)) elif not self.__updated: # Fresh configuration return None # Filter a copy of the properties props = self.__properties.copy() try: del props[services.CONFIG_PROP_BUNDLE_LOCATION] except KeyError: # Ignore pass return props
[ "def", "get_properties", "(", "self", ")", ":", "with", "self", ".", "__lock", ":", "if", "self", ".", "__deleted", ":", "raise", "ValueError", "(", "\"{0} has been deleted\"", ".", "format", "(", "self", ".", "__pid", ")", ")", "elif", "not", "self", "....
Return the properties of this Configuration object. The Dictionary object returned is a private copy for the caller and may be changed without influencing the stored configuration. If called just after the configuration is created and before update has been called, this method returns None. :return: A private copy of the properties for the caller or null. These properties must not contain the "service.bundleLocation" property. The value of this property may be obtained from the get_bundle_location() method.
[ "Return", "the", "properties", "of", "this", "Configuration", "object", ".", "The", "Dictionary", "object", "returned", "is", "a", "private", "copy", "for", "the", "caller", "and", "may", "be", "changed", "without", "influencing", "the", "stored", "configuration...
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L170-L201
9,648
tcalmant/ipopo
pelix/services/configadmin.py
Configuration.__properties_update
def __properties_update(self, properties): """ Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else False """ if not properties: # Nothing to do return False with self.__lock: # Make a copy of the properties properties = properties.copy() # Override properties properties[services.CONFIG_PROP_PID] = self.__pid if self.__location: properties[ services.CONFIG_PROP_BUNDLE_LOCATION ] = self.__location if self.__factory_pid: properties[ services.CONFIG_PROP_FACTORY_PID ] = self.__factory_pid # See if new properties are different if properties == self.__properties: return False # Store the copy (before storing data) self.__properties = properties self.__updated = True # Store the data # it will cause FileInstall to update this configuration again, but # this will ignored because self.__properties has already been # saved self.__persistence.store(self.__pid, properties) return True
python
def __properties_update(self, properties): if not properties: # Nothing to do return False with self.__lock: # Make a copy of the properties properties = properties.copy() # Override properties properties[services.CONFIG_PROP_PID] = self.__pid if self.__location: properties[ services.CONFIG_PROP_BUNDLE_LOCATION ] = self.__location if self.__factory_pid: properties[ services.CONFIG_PROP_FACTORY_PID ] = self.__factory_pid # See if new properties are different if properties == self.__properties: return False # Store the copy (before storing data) self.__properties = properties self.__updated = True # Store the data # it will cause FileInstall to update this configuration again, but # this will ignored because self.__properties has already been # saved self.__persistence.store(self.__pid, properties) return True
[ "def", "__properties_update", "(", "self", ",", "properties", ")", ":", "if", "not", "properties", ":", "# Nothing to do", "return", "False", "with", "self", ".", "__lock", ":", "# Make a copy of the properties", "properties", "=", "properties", ".", "copy", "(", ...
Internal update of configuration properties. Does not notifies the ConfigurationAdmin of this modification. :param properties: the new set of properties for this configuration :return: True if the properties have been updated, else False
[ "Internal", "update", "of", "configuration", "properties", ".", "Does", "not", "notifies", "the", "ConfigurationAdmin", "of", "this", "modification", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L213-L255
9,649
tcalmant/ipopo
pelix/services/configadmin.py
Configuration.update
def update(self, properties=None): # pylint: disable=W0212 """ If called without properties, only notifies listeners Update the properties of this Configuration object. Stores the properties in persistent storage after adding or overwriting the following properties: * "service.pid" : is set to be the PID of this configuration. * "service.factoryPid" : if this is a factory configuration it is set to the factory PID else it is not set. These system properties are all of type String. If the corresponding Managed Service/Managed Service Factory is registered, its updated method must be called asynchronously. Else, this callback is delayed until aforementioned registration occurs. Also initiates an asynchronous call to all ConfigurationListeners with a ConfigurationEvent.CM_UPDATED event. :param properties: the new set of properties for this configuration :raise IOError: Error storing the configuration """ with self.__lock: # Update properties if self.__properties_update(properties): # Update configurations, if something changed self.__config_admin._update(self)
python
def update(self, properties=None): # pylint: disable=W0212 with self.__lock: # Update properties if self.__properties_update(properties): # Update configurations, if something changed self.__config_admin._update(self)
[ "def", "update", "(", "self", ",", "properties", "=", "None", ")", ":", "# pylint: disable=W0212", "with", "self", ".", "__lock", ":", "# Update properties", "if", "self", ".", "__properties_update", "(", "properties", ")", ":", "# Update configurations, if somethin...
If called without properties, only notifies listeners Update the properties of this Configuration object. Stores the properties in persistent storage after adding or overwriting the following properties: * "service.pid" : is set to be the PID of this configuration. * "service.factoryPid" : if this is a factory configuration it is set to the factory PID else it is not set. These system properties are all of type String. If the corresponding Managed Service/Managed Service Factory is registered, its updated method must be called asynchronously. Else, this callback is delayed until aforementioned registration occurs. Also initiates an asynchronous call to all ConfigurationListeners with a ConfigurationEvent.CM_UPDATED event. :param properties: the new set of properties for this configuration :raise IOError: Error storing the configuration
[ "If", "called", "without", "properties", "only", "notifies", "listeners" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L266-L296
9,650
tcalmant/ipopo
pelix/services/configadmin.py
Configuration.delete
def delete(self, directory_updated=False): # pylint: disable=W0212 """ Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only) """ with self.__lock: if self.__deleted: # Nothing to do return # Update status self.__deleted = True # Notify ConfigurationAdmin, notify services only if the # configuration had been updated before self.__config_admin._delete(self, self.__updated, directory_updated) # Remove the file self.__persistence.delete(self.__pid) # Clean up if self.__properties: self.__properties.clear() self.__persistence = None self.__pid = None
python
def delete(self, directory_updated=False): # pylint: disable=W0212 with self.__lock: if self.__deleted: # Nothing to do return # Update status self.__deleted = True # Notify ConfigurationAdmin, notify services only if the # configuration had been updated before self.__config_admin._delete(self, self.__updated, directory_updated) # Remove the file self.__persistence.delete(self.__pid) # Clean up if self.__properties: self.__properties.clear() self.__persistence = None self.__pid = None
[ "def", "delete", "(", "self", ",", "directory_updated", "=", "False", ")", ":", "# pylint: disable=W0212", "with", "self", ".", "__lock", ":", "if", "self", ".", "__deleted", ":", "# Nothing to do", "return", "# Update status", "self", ".", "__deleted", "=", "...
Delete this configuration :param directory_updated: If True, tell ConfigurationAdmin to not recall the directory of this deletion (internal use only)
[ "Delete", "this", "configuration" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L298-L327
9,651
tcalmant/ipopo
pelix/services/configadmin.py
Configuration.matches
def matches(self, ldap_filter): """ Tests if this configuration matches the given filter. :param ldap_filter: A parsed LDAP filter object :return: True if the properties of this configuration matches the filter """ if not self.is_valid(): # Do not test invalid configurations return False return ldap_filter.matches(self.__properties)
python
def matches(self, ldap_filter): if not self.is_valid(): # Do not test invalid configurations return False return ldap_filter.matches(self.__properties)
[ "def", "matches", "(", "self", ",", "ldap_filter", ")", ":", "if", "not", "self", ".", "is_valid", "(", ")", ":", "# Do not test invalid configurations", "return", "False", "return", "ldap_filter", ".", "matches", "(", "self", ".", "__properties", ")" ]
Tests if this configuration matches the given filter. :param ldap_filter: A parsed LDAP filter object :return: True if the properties of this configuration matches the filter
[ "Tests", "if", "this", "configuration", "matches", "the", "given", "filter", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/configadmin.py#L329-L341
9,652
tcalmant/ipopo
pelix/framework.py
_package_exists
def _package_exists(path): # type: (str) -> bool """ Checks if the given Python path matches a valid file or a valid container file :param path: A Python path :return: True if the module or its container exists """ while path: if os.path.exists(path): return True else: path = os.path.dirname(path) return False
python
def _package_exists(path): # type: (str) -> bool while path: if os.path.exists(path): return True else: path = os.path.dirname(path) return False
[ "def", "_package_exists", "(", "path", ")", ":", "# type: (str) -> bool", "while", "path", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "True", "else", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ...
Checks if the given Python path matches a valid file or a valid container file :param path: A Python path :return: True if the module or its container exists
[ "Checks", "if", "the", "given", "Python", "path", "matches", "a", "valid", "file", "or", "a", "valid", "container", "file" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1945-L1960
9,653
tcalmant/ipopo
pelix/framework.py
normalize_path
def normalize_path(): """ Normalizes sys.path to avoid the use of relative folders """ # Normalize Python paths whole_path = [ os.path.abspath(path) for path in sys.path if os.path.exists(path) ] # Keep the "dynamic" current folder indicator and add the "static" # current path # Use an OrderedDict to have a faster lookup (path not in whole_set) whole_set = collections.OrderedDict((("", 1), (os.getcwd(), 1))) # Add original path entries for path in whole_path: if path not in whole_set: whole_set[path] = 1 # Set the new content of sys.path (still ordered thanks to OrderedDict) sys.path = list(whole_set) # Normalize paths in loaded modules for module_ in sys.modules.values(): try: module_.__path__ = [ os.path.abspath(path) for path in module_.__path__ if _package_exists(path) ] except AttributeError: # builtin modules don't have a __path__ pass except ImportError: pass
python
def normalize_path(): # Normalize Python paths whole_path = [ os.path.abspath(path) for path in sys.path if os.path.exists(path) ] # Keep the "dynamic" current folder indicator and add the "static" # current path # Use an OrderedDict to have a faster lookup (path not in whole_set) whole_set = collections.OrderedDict((("", 1), (os.getcwd(), 1))) # Add original path entries for path in whole_path: if path not in whole_set: whole_set[path] = 1 # Set the new content of sys.path (still ordered thanks to OrderedDict) sys.path = list(whole_set) # Normalize paths in loaded modules for module_ in sys.modules.values(): try: module_.__path__ = [ os.path.abspath(path) for path in module_.__path__ if _package_exists(path) ] except AttributeError: # builtin modules don't have a __path__ pass except ImportError: pass
[ "def", "normalize_path", "(", ")", ":", "# Normalize Python paths", "whole_path", "=", "[", "os", ".", "path", ".", "abspath", "(", "path", ")", "for", "path", "in", "sys", ".", "path", "if", "os", ".", "path", ".", "exists", "(", "path", ")", "]", "...
Normalizes sys.path to avoid the use of relative folders
[ "Normalizes", "sys", ".", "path", "to", "avoid", "the", "use", "of", "relative", "folders" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1963-L1997
9,654
tcalmant/ipopo
pelix/framework.py
Bundle.__get_activator_method
def __get_activator_method(self, method_name): """ Retrieves the requested method of the activator, or returns None :param method_name: A method name :return: A method, or None """ # Get the activator activator = getattr(self.__module, ACTIVATOR, None) if activator is None: # Get the old activator activator = getattr(self.__module, ACTIVATOR_LEGACY, None) if activator is not None: # Old activator found: print a deprecation warning _logger.warning( "Bundle %s uses the deprecated '%s' to declare" " its activator. Use @BundleActivator instead.", self.__name, ACTIVATOR_LEGACY, ) return getattr(activator, method_name, None)
python
def __get_activator_method(self, method_name): # Get the activator activator = getattr(self.__module, ACTIVATOR, None) if activator is None: # Get the old activator activator = getattr(self.__module, ACTIVATOR_LEGACY, None) if activator is not None: # Old activator found: print a deprecation warning _logger.warning( "Bundle %s uses the deprecated '%s' to declare" " its activator. Use @BundleActivator instead.", self.__name, ACTIVATOR_LEGACY, ) return getattr(activator, method_name, None)
[ "def", "__get_activator_method", "(", "self", ",", "method_name", ")", ":", "# Get the activator", "activator", "=", "getattr", "(", "self", ".", "__module", ",", "ACTIVATOR", ",", "None", ")", "if", "activator", "is", "None", ":", "# Get the old activator", "ac...
Retrieves the requested method of the activator, or returns None :param method_name: A method name :return: A method, or None
[ "Retrieves", "the", "requested", "method", "of", "the", "activator", "or", "returns", "None" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L236-L256
9,655
tcalmant/ipopo
pelix/framework.py
Bundle._fire_bundle_event
def _fire_bundle_event(self, kind): # type: (int) -> None """ Fires a bundle event of the given kind :param kind: Kind of event """ self.__framework._dispatcher.fire_bundle_event(BundleEvent(kind, self))
python
def _fire_bundle_event(self, kind): # type: (int) -> None self.__framework._dispatcher.fire_bundle_event(BundleEvent(kind, self))
[ "def", "_fire_bundle_event", "(", "self", ",", "kind", ")", ":", "# type: (int) -> None", "self", ".", "__framework", ".", "_dispatcher", ".", "fire_bundle_event", "(", "BundleEvent", "(", "kind", ",", "self", ")", ")" ]
Fires a bundle event of the given kind :param kind: Kind of event
[ "Fires", "a", "bundle", "event", "of", "the", "given", "kind" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L258-L265
9,656
tcalmant/ipopo
pelix/framework.py
Bundle.get_registered_services
def get_registered_services(self): # type: () -> List[ServiceReference] """ Returns this bundle's ServiceReference list for all services it has registered or an empty list 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 any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled """ if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_registered_services' on an " "uninstalled bundle" ) return self.__framework._registry.get_bundle_registered_services(self)
python
def get_registered_services(self): # type: () -> List[ServiceReference] if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_registered_services' on an " "uninstalled bundle" ) return self.__framework._registry.get_bundle_registered_services(self)
[ "def", "get_registered_services", "(", "self", ")", ":", "# type: () -> List[ServiceReference]", "if", "self", ".", "_state", "==", "Bundle", ".", "UNINSTALLED", ":", "raise", "BundleException", "(", "\"Can't call 'get_registered_services' on an \"", "\"uninstalled bundle\"",...
Returns this bundle's ServiceReference list for all services it has registered or an empty list 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 any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled
[ "Returns", "this", "bundle", "s", "ServiceReference", "list", "for", "all", "services", "it", "has", "registered", "or", "an", "empty", "list" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L326-L344
9,657
tcalmant/ipopo
pelix/framework.py
Bundle.get_services_in_use
def get_services_in_use(self): # type: () -> List[ServiceReference] """ Returns this bundle's ServiceReference list for all services it is using or an empty list. 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 any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled """ if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_services_in_use' on an uninstalled bundle" ) return self.__framework._registry.get_bundle_imported_services(self)
python
def get_services_in_use(self): # type: () -> List[ServiceReference] if self._state == Bundle.UNINSTALLED: raise BundleException( "Can't call 'get_services_in_use' on an uninstalled bundle" ) return self.__framework._registry.get_bundle_imported_services(self)
[ "def", "get_services_in_use", "(", "self", ")", ":", "# type: () -> List[ServiceReference]", "if", "self", ".", "_state", "==", "Bundle", ".", "UNINSTALLED", ":", "raise", "BundleException", "(", "\"Can't call 'get_services_in_use' on an uninstalled bundle\"", ")", "return"...
Returns this bundle's ServiceReference list for all services it is using or an empty list. 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 any time. :return: An array of ServiceReference objects :raise BundleException: If the bundle has been uninstalled
[ "Returns", "this", "bundle", "s", "ServiceReference", "list", "for", "all", "services", "it", "is", "using", "or", "an", "empty", "list", ".", "A", "bundle", "is", "considered", "to", "be", "using", "a", "service", "if", "its", "use", "count", "for", "th...
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L346-L365
9,658
tcalmant/ipopo
pelix/framework.py
Bundle.start
def start(self): """ Starts the bundle. Does nothing if the bundle is already starting or active. :raise BundleException: The framework is not yet started or the bundle activator failed. """ if self.__framework._state not in (Bundle.STARTING, Bundle.ACTIVE): # Framework is not running raise BundleException( "Framework must be started before its bundles" ) with self._lock: if self._state in (Bundle.ACTIVE, Bundle.STARTING): # Already started bundle, do nothing return # Store the bundle current state previous_state = self._state # Starting... self._state = Bundle.STARTING self._fire_bundle_event(BundleEvent.STARTING) # Call the activator, if any starter = self.__get_activator_method("start") if starter is not None: try: # Call the start method starter(self.__context) except (FrameworkException, BundleException): # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while starting", self.__name ) raise except Exception as ex: # Restore previous state self._state = previous_state # Raise the error _logger.exception( "Error raised by %s while starting", self.__name ) raise BundleException(ex) # Bundle is now active self._state = Bundle.ACTIVE self._fire_bundle_event(BundleEvent.STARTED)
python
def start(self): if self.__framework._state not in (Bundle.STARTING, Bundle.ACTIVE): # Framework is not running raise BundleException( "Framework must be started before its bundles" ) with self._lock: if self._state in (Bundle.ACTIVE, Bundle.STARTING): # Already started bundle, do nothing return # Store the bundle current state previous_state = self._state # Starting... self._state = Bundle.STARTING self._fire_bundle_event(BundleEvent.STARTING) # Call the activator, if any starter = self.__get_activator_method("start") if starter is not None: try: # Call the start method starter(self.__context) except (FrameworkException, BundleException): # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while starting", self.__name ) raise except Exception as ex: # Restore previous state self._state = previous_state # Raise the error _logger.exception( "Error raised by %s while starting", self.__name ) raise BundleException(ex) # Bundle is now active self._state = Bundle.ACTIVE self._fire_bundle_event(BundleEvent.STARTED)
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "__framework", ".", "_state", "not", "in", "(", "Bundle", ".", "STARTING", ",", "Bundle", ".", "ACTIVE", ")", ":", "# Framework is not running", "raise", "BundleException", "(", "\"Framework must be sta...
Starts the bundle. Does nothing if the bundle is already starting or active. :raise BundleException: The framework is not yet started or the bundle activator failed.
[ "Starts", "the", "bundle", ".", "Does", "nothing", "if", "the", "bundle", "is", "already", "starting", "or", "active", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L406-L459
9,659
tcalmant/ipopo
pelix/framework.py
Bundle.stop
def stop(self): """ Stops the bundle. Does nothing if the bundle is already stopped. :raise BundleException: The bundle activator failed. """ if self._state != Bundle.ACTIVE: # Invalid state return exception = None with self._lock: # Store the bundle current state previous_state = self._state # Stopping... self._state = Bundle.STOPPING self._fire_bundle_event(BundleEvent.STOPPING) # Call the activator, if any stopper = self.__get_activator_method("stop") if stopper is not None: try: # Call the start method stopper(self.__context) except (FrameworkException, BundleException) as ex: # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while stopping", self.__name ) exception = ex except Exception as ex: _logger.exception( "Error raised by %s while stopping", self.__name ) # Store the exception (raised after service clean up) exception = BundleException(ex) # Hide remaining services self.__framework._hide_bundle_services(self) # Intermediate bundle event : activator should have cleaned up # everything, but some element could stay (iPOPO components, ...) self._fire_bundle_event(BundleEvent.STOPPING_PRECLEAN) # Remove remaining services (the hard way) self.__unregister_services() # Cleanup service usages self.__framework._unget_used_services(self) # Bundle is now stopped and all its services have been unregistered self._state = Bundle.RESOLVED self._fire_bundle_event(BundleEvent.STOPPED) # Raise the exception, if any # pylint: disable=E0702 # Pylint seems to miss the "is not None" check below if exception is not None: raise exception
python
def stop(self): if self._state != Bundle.ACTIVE: # Invalid state return exception = None with self._lock: # Store the bundle current state previous_state = self._state # Stopping... self._state = Bundle.STOPPING self._fire_bundle_event(BundleEvent.STOPPING) # Call the activator, if any stopper = self.__get_activator_method("stop") if stopper is not None: try: # Call the start method stopper(self.__context) except (FrameworkException, BundleException) as ex: # Restore previous state self._state = previous_state # Re-raise directly Pelix exceptions _logger.exception( "Pelix error raised by %s while stopping", self.__name ) exception = ex except Exception as ex: _logger.exception( "Error raised by %s while stopping", self.__name ) # Store the exception (raised after service clean up) exception = BundleException(ex) # Hide remaining services self.__framework._hide_bundle_services(self) # Intermediate bundle event : activator should have cleaned up # everything, but some element could stay (iPOPO components, ...) self._fire_bundle_event(BundleEvent.STOPPING_PRECLEAN) # Remove remaining services (the hard way) self.__unregister_services() # Cleanup service usages self.__framework._unget_used_services(self) # Bundle is now stopped and all its services have been unregistered self._state = Bundle.RESOLVED self._fire_bundle_event(BundleEvent.STOPPED) # Raise the exception, if any # pylint: disable=E0702 # Pylint seems to miss the "is not None" check below if exception is not None: raise exception
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_state", "!=", "Bundle", ".", "ACTIVE", ":", "# Invalid state", "return", "exception", "=", "None", "with", "self", ".", "_lock", ":", "# Store the bundle current state", "previous_state", "=", "self", ...
Stops the bundle. Does nothing if the bundle is already stopped. :raise BundleException: The bundle activator failed.
[ "Stops", "the", "bundle", ".", "Does", "nothing", "if", "the", "bundle", "is", "already", "stopped", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L461-L523
9,660
tcalmant/ipopo
pelix/framework.py
Bundle.__unregister_services
def __unregister_services(self): """ Unregisters all bundle services """ # Copy the services list, as it will be modified during the process with self.__registration_lock: registered_services = self.__registered_services.copy() for registration in registered_services: try: registration.unregister() except BundleException: # Ignore errors at this level pass if self.__registered_services: _logger.warning("Not all services have been unregistered...") with self.__registration_lock: # Clear the list, just to be clean self.__registered_services.clear()
python
def __unregister_services(self): # Copy the services list, as it will be modified during the process with self.__registration_lock: registered_services = self.__registered_services.copy() for registration in registered_services: try: registration.unregister() except BundleException: # Ignore errors at this level pass if self.__registered_services: _logger.warning("Not all services have been unregistered...") with self.__registration_lock: # Clear the list, just to be clean self.__registered_services.clear()
[ "def", "__unregister_services", "(", "self", ")", ":", "# Copy the services list, as it will be modified during the process", "with", "self", ".", "__registration_lock", ":", "registered_services", "=", "self", ".", "__registered_services", ".", "copy", "(", ")", "for", "...
Unregisters all bundle services
[ "Unregisters", "all", "bundle", "services" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L525-L545
9,661
tcalmant/ipopo
pelix/framework.py
Bundle.uninstall
def uninstall(self): """ Uninstalls the bundle """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework.uninstall_bundle(self)
python
def uninstall(self): with self._lock: if self._state == Bundle.ACTIVE: self.stop() # Change the bundle state self._state = Bundle.UNINSTALLED # Call the framework self.__framework.uninstall_bundle(self)
[ "def", "uninstall", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_state", "==", "Bundle", ".", "ACTIVE", ":", "self", ".", "stop", "(", ")", "# Change the bundle state", "self", ".", "_state", "=", "Bundle", ".", "UNINS...
Uninstalls the bundle
[ "Uninstalls", "the", "bundle" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L547-L559
9,662
tcalmant/ipopo
pelix/framework.py
Bundle.update
def update(self): """ Updates the bundle """ with self._lock: # Was it active ? restart = self._state == Bundle.ACTIVE # Send the update event self._fire_bundle_event(BundleEvent.UPDATE_BEGIN) try: # Stop the bundle self.stop() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Change the source file age module_stat = None module_file = getattr(self.__module, "__file__", None) if module_file is not None and os.path.isfile(module_file): try: module_stat = os.stat(module_file) # Change modification time to bypass weak time resolution # of the underlying file system os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime + 1), ) except OSError: # Can't touch the file _logger.warning( "Failed to update the modification time of '%s'. " "The bundle update might not reflect the latest " "changes.", module_file, ) # Clean up the module constants (otherwise kept by reload) # Keep special members (__name__, __file__, ...) old_content = self.__module.__dict__.copy() for name in list(self.__module.__dict__): if not (name.startswith("__") and name.endswith("__")): del self.__module.__dict__[name] try: # Reload the module reload_module(self.__module) except (ImportError, SyntaxError) as ex: # Exception raised if the file is unreadable _logger.exception("Error updating %s: %s", self.__name, ex) # Reset module content self.__module.__dict__.clear() self.__module.__dict__.update(old_content) if module_stat is not None: try: # Reset times os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime), ) except OSError: # Shouldn't occur, since we succeeded before the update _logger.debug( "Failed to reset the modification time of '%s'", module_file, ) if restart: try: # Re-start the bundle self.start() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Bundle update finished self._fire_bundle_event(BundleEvent.UPDATED)
python
def update(self): with self._lock: # Was it active ? restart = self._state == Bundle.ACTIVE # Send the update event self._fire_bundle_event(BundleEvent.UPDATE_BEGIN) try: # Stop the bundle self.stop() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Change the source file age module_stat = None module_file = getattr(self.__module, "__file__", None) if module_file is not None and os.path.isfile(module_file): try: module_stat = os.stat(module_file) # Change modification time to bypass weak time resolution # of the underlying file system os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime + 1), ) except OSError: # Can't touch the file _logger.warning( "Failed to update the modification time of '%s'. " "The bundle update might not reflect the latest " "changes.", module_file, ) # Clean up the module constants (otherwise kept by reload) # Keep special members (__name__, __file__, ...) old_content = self.__module.__dict__.copy() for name in list(self.__module.__dict__): if not (name.startswith("__") and name.endswith("__")): del self.__module.__dict__[name] try: # Reload the module reload_module(self.__module) except (ImportError, SyntaxError) as ex: # Exception raised if the file is unreadable _logger.exception("Error updating %s: %s", self.__name, ex) # Reset module content self.__module.__dict__.clear() self.__module.__dict__.update(old_content) if module_stat is not None: try: # Reset times os.utime( module_file, (module_stat.st_atime, module_stat.st_mtime), ) except OSError: # Shouldn't occur, since we succeeded before the update _logger.debug( "Failed to reset the modification time of '%s'", module_file, ) if restart: try: # Re-start the bundle self.start() except: # Something wrong occurred, notify listeners self._fire_bundle_event(BundleEvent.UPDATE_FAILED) raise # Bundle update finished self._fire_bundle_event(BundleEvent.UPDATED)
[ "def", "update", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "# Was it active ?", "restart", "=", "self", ".", "_state", "==", "Bundle", ".", "ACTIVE", "# Send the update event", "self", ".", "_fire_bundle_event", "(", "BundleEvent", ".", "UPDATE...
Updates the bundle
[ "Updates", "the", "bundle" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L561-L644
9,663
tcalmant/ipopo
pelix/framework.py
Framework.get_bundle_by_id
def get_bundle_by_id(self, bundle_id): # type: (int) -> Union[Bundle, Framework] """ Retrieves the bundle with the given ID :param bundle_id: ID of an installed bundle :return: The requested bundle :raise BundleException: The ID is invalid """ if bundle_id == 0: # "System bundle" return self with self.__bundles_lock: if bundle_id not in self.__bundles: raise BundleException("Invalid bundle ID {0}".format(bundle_id)) return self.__bundles[bundle_id]
python
def get_bundle_by_id(self, bundle_id): # type: (int) -> Union[Bundle, Framework] if bundle_id == 0: # "System bundle" return self with self.__bundles_lock: if bundle_id not in self.__bundles: raise BundleException("Invalid bundle ID {0}".format(bundle_id)) return self.__bundles[bundle_id]
[ "def", "get_bundle_by_id", "(", "self", ",", "bundle_id", ")", ":", "# type: (int) -> Union[Bundle, Framework]", "if", "bundle_id", "==", "0", ":", "# \"System bundle\"", "return", "self", "with", "self", ".", "__bundles_lock", ":", "if", "bundle_id", "not", "in", ...
Retrieves the bundle with the given ID :param bundle_id: ID of an installed bundle :return: The requested bundle :raise BundleException: The ID is invalid
[ "Retrieves", "the", "bundle", "with", "the", "given", "ID" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L745-L762
9,664
tcalmant/ipopo
pelix/framework.py
Framework.get_bundle_by_name
def get_bundle_by_name(self, bundle_name): # type: (str) -> Optional[Bundle] """ Retrieves the bundle with the given name :param bundle_name: Name of the bundle to look for :return: The requested bundle, None if not found """ if bundle_name is None: # Nothing to do return None if bundle_name is self.get_symbolic_name(): # System bundle requested return self with self.__bundles_lock: for bundle in self.__bundles.values(): if bundle_name == bundle.get_symbolic_name(): # Found ! return bundle # Not found... return None
python
def get_bundle_by_name(self, bundle_name): # type: (str) -> Optional[Bundle] if bundle_name is None: # Nothing to do return None if bundle_name is self.get_symbolic_name(): # System bundle requested return self with self.__bundles_lock: for bundle in self.__bundles.values(): if bundle_name == bundle.get_symbolic_name(): # Found ! return bundle # Not found... return None
[ "def", "get_bundle_by_name", "(", "self", ",", "bundle_name", ")", ":", "# type: (str) -> Optional[Bundle]", "if", "bundle_name", "is", "None", ":", "# Nothing to do", "return", "None", "if", "bundle_name", "is", "self", ".", "get_symbolic_name", "(", ")", ":", "#...
Retrieves the bundle with the given name :param bundle_name: Name of the bundle to look for :return: The requested bundle, None if not found
[ "Retrieves", "the", "bundle", "with", "the", "given", "name" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L764-L787
9,665
tcalmant/ipopo
pelix/framework.py
Framework.get_bundles
def get_bundles(self): # type: () -> List[Bundle] """ Returns the list of all installed bundles :return: the list of all installed bundles """ with self.__bundles_lock: return [ self.__bundles[bundle_id] for bundle_id in sorted(self.__bundles.keys()) ]
python
def get_bundles(self): # type: () -> List[Bundle] with self.__bundles_lock: return [ self.__bundles[bundle_id] for bundle_id in sorted(self.__bundles.keys()) ]
[ "def", "get_bundles", "(", "self", ")", ":", "# type: () -> List[Bundle]", "with", "self", ".", "__bundles_lock", ":", "return", "[", "self", ".", "__bundles", "[", "bundle_id", "]", "for", "bundle_id", "in", "sorted", "(", "self", ".", "__bundles", ".", "ke...
Returns the list of all installed bundles :return: the list of all installed bundles
[ "Returns", "the", "list", "of", "all", "installed", "bundles" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L789-L800
9,666
tcalmant/ipopo
pelix/framework.py
Framework.get_property
def get_property(self, name): # type: (str) -> object """ Retrieves a framework or system property. As framework properties don't change while it's running, this method don't need to be protected. :param name: The property name """ with self.__properties_lock: return self.__properties.get(name, os.getenv(name))
python
def get_property(self, name): # type: (str) -> object with self.__properties_lock: return self.__properties.get(name, os.getenv(name))
[ "def", "get_property", "(", "self", ",", "name", ")", ":", "# type: (str) -> object", "with", "self", ".", "__properties_lock", ":", "return", "self", ".", "__properties", ".", "get", "(", "name", ",", "os", ".", "getenv", "(", "name", ")", ")" ]
Retrieves a framework or system property. As framework properties don't change while it's running, this method don't need to be protected. :param name: The property name
[ "Retrieves", "a", "framework", "or", "system", "property", ".", "As", "framework", "properties", "don", "t", "change", "while", "it", "s", "running", "this", "method", "don", "t", "need", "to", "be", "protected", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L810-L819
9,667
tcalmant/ipopo
pelix/framework.py
Framework.install_bundle
def install_bundle(self, name, path=None): # type: (str, str) -> Bundle """ Installs the bundle with the given name *Note:* Before Pelix 0.5.0, this method returned the ID of the installed bundle, instead of the Bundle object. **WARNING:** The behavior of the loading process is subject to changes, as it does not allow to safely run multiple frameworks in the same Python interpreter, as they might share global module values. :param name: A bundle name :param path: Preferred path to load the module :return: The installed Bundle object :raise BundleException: Something happened """ with self.__bundles_lock: # A bundle can't be installed twice for bundle in self.__bundles.values(): if bundle.get_symbolic_name() == name: _logger.debug("Already installed bundle: %s", name) return bundle # Load the module try: if path: # Use the given path in priority sys.path.insert(0, path) try: # The module has already been loaded module_ = sys.modules[name] except KeyError: # Load the module # __import__(name) -> package level # import_module -> module level module_ = importlib.import_module(name) except (ImportError, IOError) as ex: # Error importing the module raise BundleException( "Error installing bundle {0}: {1}".format(name, ex) ) finally: if path: # Clean up the path. The loaded module(s) might # have changed the path content, so do not use an # index sys.path.remove(path) # Add the module to sys.modules, just to be sure sys.modules[name] = module_ # Compute the bundle ID bundle_id = self.__next_bundle_id # Prepare the bundle object and its context bundle = Bundle(self, bundle_id, name, module_) # Store the bundle self.__bundles[bundle_id] = bundle # Update the bundle ID counter self.__next_bundle_id += 1 # Fire the bundle installed event event = BundleEvent(BundleEvent.INSTALLED, bundle) self._dispatcher.fire_bundle_event(event) return bundle
python
def install_bundle(self, name, path=None): # type: (str, str) -> Bundle with self.__bundles_lock: # A bundle can't be installed twice for bundle in self.__bundles.values(): if bundle.get_symbolic_name() == name: _logger.debug("Already installed bundle: %s", name) return bundle # Load the module try: if path: # Use the given path in priority sys.path.insert(0, path) try: # The module has already been loaded module_ = sys.modules[name] except KeyError: # Load the module # __import__(name) -> package level # import_module -> module level module_ = importlib.import_module(name) except (ImportError, IOError) as ex: # Error importing the module raise BundleException( "Error installing bundle {0}: {1}".format(name, ex) ) finally: if path: # Clean up the path. The loaded module(s) might # have changed the path content, so do not use an # index sys.path.remove(path) # Add the module to sys.modules, just to be sure sys.modules[name] = module_ # Compute the bundle ID bundle_id = self.__next_bundle_id # Prepare the bundle object and its context bundle = Bundle(self, bundle_id, name, module_) # Store the bundle self.__bundles[bundle_id] = bundle # Update the bundle ID counter self.__next_bundle_id += 1 # Fire the bundle installed event event = BundleEvent(BundleEvent.INSTALLED, bundle) self._dispatcher.fire_bundle_event(event) return bundle
[ "def", "install_bundle", "(", "self", ",", "name", ",", "path", "=", "None", ")", ":", "# type: (str, str) -> Bundle", "with", "self", ".", "__bundles_lock", ":", "# A bundle can't be installed twice", "for", "bundle", "in", "self", ".", "__bundles", ".", "values"...
Installs the bundle with the given name *Note:* Before Pelix 0.5.0, this method returned the ID of the installed bundle, instead of the Bundle object. **WARNING:** The behavior of the loading process is subject to changes, as it does not allow to safely run multiple frameworks in the same Python interpreter, as they might share global module values. :param name: A bundle name :param path: Preferred path to load the module :return: The installed Bundle object :raise BundleException: Something happened
[ "Installs", "the", "bundle", "with", "the", "given", "name" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L874-L942
9,668
tcalmant/ipopo
pelix/framework.py
Framework.install_package
def install_package(self, path, recursive=False, prefix=None): # type: (str, bool, str) -> tuple """ Installs all the modules found in the given package :param path: Path of the package (folder) :param recursive: If True, install the sub-packages too :param prefix: (**internal**) Prefix for all found modules :return: A 2-tuple, with the list of installed bundles and the list of failed modules names :raise ValueError: Invalid path """ if not path: raise ValueError("Empty path") elif not is_string(path): raise ValueError("Path must be a string") # Use an absolute path path = os.path.abspath(path) if not os.path.exists(path): raise ValueError("Nonexistent path: {0}".format(path)) # Create a simple visitor def visitor(fullname, is_package, module_path): # pylint: disable=W0613 """ Package visitor: accepts everything in recursive mode, else avoids packages """ return recursive or not is_package # Set up the prefix if needed if prefix is None: prefix = os.path.basename(path) bundles = set() # type: Set[Bundle] failed = set() # type: Set[str] with self.__bundles_lock: try: # Install the package first, resolved from the parent directory bundles.add(self.install_bundle(prefix, os.path.dirname(path))) # Visit the package visited, sub_failed = self.install_visiting( path, visitor, prefix ) # Update the sets bundles.update(visited) failed.update(sub_failed) except BundleException as ex: # Error loading the module _logger.warning("Error loading package %s: %s", prefix, ex) failed.add(prefix) return bundles, failed
python
def install_package(self, path, recursive=False, prefix=None): # type: (str, bool, str) -> tuple if not path: raise ValueError("Empty path") elif not is_string(path): raise ValueError("Path must be a string") # Use an absolute path path = os.path.abspath(path) if not os.path.exists(path): raise ValueError("Nonexistent path: {0}".format(path)) # Create a simple visitor def visitor(fullname, is_package, module_path): # pylint: disable=W0613 """ Package visitor: accepts everything in recursive mode, else avoids packages """ return recursive or not is_package # Set up the prefix if needed if prefix is None: prefix = os.path.basename(path) bundles = set() # type: Set[Bundle] failed = set() # type: Set[str] with self.__bundles_lock: try: # Install the package first, resolved from the parent directory bundles.add(self.install_bundle(prefix, os.path.dirname(path))) # Visit the package visited, sub_failed = self.install_visiting( path, visitor, prefix ) # Update the sets bundles.update(visited) failed.update(sub_failed) except BundleException as ex: # Error loading the module _logger.warning("Error loading package %s: %s", prefix, ex) failed.add(prefix) return bundles, failed
[ "def", "install_package", "(", "self", ",", "path", ",", "recursive", "=", "False", ",", "prefix", "=", "None", ")", ":", "# type: (str, bool, str) -> tuple", "if", "not", "path", ":", "raise", "ValueError", "(", "\"Empty path\"", ")", "elif", "not", "is_strin...
Installs all the modules found in the given package :param path: Path of the package (folder) :param recursive: If True, install the sub-packages too :param prefix: (**internal**) Prefix for all found modules :return: A 2-tuple, with the list of installed bundles and the list of failed modules names :raise ValueError: Invalid path
[ "Installs", "all", "the", "modules", "found", "in", "the", "given", "package" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L944-L1000
9,669
tcalmant/ipopo
pelix/framework.py
Framework.install_visiting
def install_visiting(self, path, visitor, prefix=None): """ Installs all the modules found in the given path if they are accepted by the visitor. The visitor must be a callable accepting 3 parameters: * fullname: The full name of the module * is_package: If True, the module is a package * module_path: The path to the module file :param path: Root search path :param visitor: The visiting callable :param prefix: (**internal**) Prefix for all found modules :return: A 2-tuple, with the list of installed bundles and the list of failed modules names :raise ValueError: Invalid path or visitor """ # Validate the path if not path: raise ValueError("Empty path") elif not is_string(path): raise ValueError("Path must be a string") # Validate the visitor if visitor is None: raise ValueError("No visitor method given") # Use an absolute path path = os.path.abspath(path) if not os.path.exists(path): raise ValueError("Inexistent path: {0}".format(path)) # Set up the prefix if needed if prefix is None: prefix = os.path.basename(path) bundles = set() failed = set() with self.__bundles_lock: # Walk through the folder to find modules for name, is_package in walk_modules(path): # Ignore '__main__' modules if name == "__main__": continue # Compute the full name of the module fullname = ".".join((prefix, name)) if prefix else name try: if visitor(fullname, is_package, path): if is_package: # Install the package bundles.add(self.install_bundle(fullname, path)) # Visit the package sub_path = os.path.join(path, name) sub_bundles, sub_failed = self.install_visiting( sub_path, visitor, fullname ) bundles.update(sub_bundles) failed.update(sub_failed) else: # Install the bundle bundles.add(self.install_bundle(fullname, path)) except BundleException as ex: # Error loading the module _logger.warning("Error visiting %s: %s", fullname, ex) # Try the next module failed.add(fullname) continue return bundles, failed
python
def install_visiting(self, path, visitor, prefix=None): # Validate the path if not path: raise ValueError("Empty path") elif not is_string(path): raise ValueError("Path must be a string") # Validate the visitor if visitor is None: raise ValueError("No visitor method given") # Use an absolute path path = os.path.abspath(path) if not os.path.exists(path): raise ValueError("Inexistent path: {0}".format(path)) # Set up the prefix if needed if prefix is None: prefix = os.path.basename(path) bundles = set() failed = set() with self.__bundles_lock: # Walk through the folder to find modules for name, is_package in walk_modules(path): # Ignore '__main__' modules if name == "__main__": continue # Compute the full name of the module fullname = ".".join((prefix, name)) if prefix else name try: if visitor(fullname, is_package, path): if is_package: # Install the package bundles.add(self.install_bundle(fullname, path)) # Visit the package sub_path = os.path.join(path, name) sub_bundles, sub_failed = self.install_visiting( sub_path, visitor, fullname ) bundles.update(sub_bundles) failed.update(sub_failed) else: # Install the bundle bundles.add(self.install_bundle(fullname, path)) except BundleException as ex: # Error loading the module _logger.warning("Error visiting %s: %s", fullname, ex) # Try the next module failed.add(fullname) continue return bundles, failed
[ "def", "install_visiting", "(", "self", ",", "path", ",", "visitor", ",", "prefix", "=", "None", ")", ":", "# Validate the path", "if", "not", "path", ":", "raise", "ValueError", "(", "\"Empty path\"", ")", "elif", "not", "is_string", "(", "path", ")", ":"...
Installs all the modules found in the given path if they are accepted by the visitor. The visitor must be a callable accepting 3 parameters: * fullname: The full name of the module * is_package: If True, the module is a package * module_path: The path to the module file :param path: Root search path :param visitor: The visiting callable :param prefix: (**internal**) Prefix for all found modules :return: A 2-tuple, with the list of installed bundles and the list of failed modules names :raise ValueError: Invalid path or visitor
[ "Installs", "all", "the", "modules", "found", "in", "the", "given", "path", "if", "they", "are", "accepted", "by", "the", "visitor", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1002-L1075
9,670
tcalmant/ipopo
pelix/framework.py
Framework.register_service
def register_service( self, bundle, clazz, service, properties, send_event, factory=False, prototype=False, ): # type: (Bundle, Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration """ Registers a service and calls the listeners :param bundle: The bundle registering the service :param clazz: Name(s) of the interface(s) implemented by service :param service: The service to register :param properties: Service properties :param send_event: If not, doesn't trigger a service registered event :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: A ServiceRegistration object :raise BundleException: An error occurred while registering the service """ if bundle is None or service is None or not clazz: raise BundleException("Invalid registration parameters") if not isinstance(properties, dict): # Be sure we have a valid dictionary properties = {} else: # Use a copy of the given properties properties = properties.copy() # Prepare the class specification if not isinstance(clazz, (list, tuple)): # Make a list from the single class clazz = [clazz] # Test the list content classes = [] for svc_clazz in clazz: if inspect.isclass(svc_clazz): # Keep the type name svc_clazz = svc_clazz.__name__ if not svc_clazz or not is_string(svc_clazz): # Invalid class name raise BundleException( "Invalid class name: {0}".format(svc_clazz) ) # Class OK classes.append(svc_clazz) # Make the service registration registration = self._registry.register( bundle, classes, properties, service, factory, prototype ) # Update the bundle registration information bundle._registered_service(registration) if send_event: # Call the listeners event = ServiceEvent( ServiceEvent.REGISTERED, registration.get_reference() ) self._dispatcher.fire_service_event(event) return registration
python
def register_service( self, bundle, clazz, service, properties, send_event, factory=False, prototype=False, ): # type: (Bundle, Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration if bundle is None or service is None or not clazz: raise BundleException("Invalid registration parameters") if not isinstance(properties, dict): # Be sure we have a valid dictionary properties = {} else: # Use a copy of the given properties properties = properties.copy() # Prepare the class specification if not isinstance(clazz, (list, tuple)): # Make a list from the single class clazz = [clazz] # Test the list content classes = [] for svc_clazz in clazz: if inspect.isclass(svc_clazz): # Keep the type name svc_clazz = svc_clazz.__name__ if not svc_clazz or not is_string(svc_clazz): # Invalid class name raise BundleException( "Invalid class name: {0}".format(svc_clazz) ) # Class OK classes.append(svc_clazz) # Make the service registration registration = self._registry.register( bundle, classes, properties, service, factory, prototype ) # Update the bundle registration information bundle._registered_service(registration) if send_event: # Call the listeners event = ServiceEvent( ServiceEvent.REGISTERED, registration.get_reference() ) self._dispatcher.fire_service_event(event) return registration
[ "def", "register_service", "(", "self", ",", "bundle", ",", "clazz", ",", "service", ",", "properties", ",", "send_event", ",", "factory", "=", "False", ",", "prototype", "=", "False", ",", ")", ":", "# type: (Bundle, Union[List[Any], type, str], object, dict, bool,...
Registers a service and calls the listeners :param bundle: The bundle registering the service :param clazz: Name(s) of the interface(s) implemented by service :param service: The service to register :param properties: Service properties :param send_event: If not, doesn't trigger a service registered event :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: A ServiceRegistration object :raise BundleException: An error occurred while registering the service
[ "Registers", "a", "service", "and", "calls", "the", "listeners" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1077-L1148
9,671
tcalmant/ipopo
pelix/framework.py
Framework.start
def start(self): # type: () -> bool """ Starts the framework :return: True if the bundle has been started, False if it was already running :raise BundleException: A bundle failed to start """ with self._lock: if self._state in (Bundle.STARTING, Bundle.ACTIVE): # Already started framework return False # Reset the stop event self._fw_stop_event.clear() # Starting... self._state = Bundle.STARTING self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STARTING, self) ) # Start all registered bundles (use a copy, just in case...) for bundle in self.__bundles.copy().values(): try: bundle.start() except FrameworkException as ex: # Important error _logger.exception( "Important error starting bundle: %s", bundle ) if ex.needs_stop: # Stop the framework (has to be in active state) self._state = Bundle.ACTIVE self.stop() return False except BundleException: # A bundle failed to start : just log _logger.exception("Error starting bundle: %s", bundle) # Bundle is now active self._state = Bundle.ACTIVE return True
python
def start(self): # type: () -> bool with self._lock: if self._state in (Bundle.STARTING, Bundle.ACTIVE): # Already started framework return False # Reset the stop event self._fw_stop_event.clear() # Starting... self._state = Bundle.STARTING self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STARTING, self) ) # Start all registered bundles (use a copy, just in case...) for bundle in self.__bundles.copy().values(): try: bundle.start() except FrameworkException as ex: # Important error _logger.exception( "Important error starting bundle: %s", bundle ) if ex.needs_stop: # Stop the framework (has to be in active state) self._state = Bundle.ACTIVE self.stop() return False except BundleException: # A bundle failed to start : just log _logger.exception("Error starting bundle: %s", bundle) # Bundle is now active self._state = Bundle.ACTIVE return True
[ "def", "start", "(", "self", ")", ":", "# type: () -> bool", "with", "self", ".", "_lock", ":", "if", "self", ".", "_state", "in", "(", "Bundle", ".", "STARTING", ",", "Bundle", ".", "ACTIVE", ")", ":", "# Already started framework", "return", "False", "# ...
Starts the framework :return: True if the bundle has been started, False if it was already running :raise BundleException: A bundle failed to start
[ "Starts", "the", "framework" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1150-L1193
9,672
tcalmant/ipopo
pelix/framework.py
Framework.stop
def stop(self): # type: () -> bool """ Stops the framework :return: True if the framework stopped, False it wasn't running """ with self._lock: if self._state != Bundle.ACTIVE: # Invalid state return False # Hide all services (they will be deleted by bundle.stop()) for bundle in self.__bundles.values(): self._registry.hide_bundle_services(bundle) # Stopping... self._state = Bundle.STOPPING self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STOPPING, self) ) # Notify listeners that the bundle is stopping self._dispatcher.fire_framework_stopping() bid = self.__next_bundle_id - 1 while bid > 0: bundle = self.__bundles.get(bid) bid -= 1 if bundle is None or bundle.get_state() != Bundle.ACTIVE: # Ignore inactive bundle continue try: bundle.stop() except Exception as ex: # Just log exceptions _logger.exception( "Error stopping bundle %s: %s", bundle.get_symbolic_name(), ex, ) # Framework is now stopped self._state = Bundle.RESOLVED self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STOPPED, self) ) # All bundles have been stopped, release "wait_for_stop" self._fw_stop_event.set() # Force the registry clean up self._registry.clear() return True
python
def stop(self): # type: () -> bool with self._lock: if self._state != Bundle.ACTIVE: # Invalid state return False # Hide all services (they will be deleted by bundle.stop()) for bundle in self.__bundles.values(): self._registry.hide_bundle_services(bundle) # Stopping... self._state = Bundle.STOPPING self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STOPPING, self) ) # Notify listeners that the bundle is stopping self._dispatcher.fire_framework_stopping() bid = self.__next_bundle_id - 1 while bid > 0: bundle = self.__bundles.get(bid) bid -= 1 if bundle is None or bundle.get_state() != Bundle.ACTIVE: # Ignore inactive bundle continue try: bundle.stop() except Exception as ex: # Just log exceptions _logger.exception( "Error stopping bundle %s: %s", bundle.get_symbolic_name(), ex, ) # Framework is now stopped self._state = Bundle.RESOLVED self._dispatcher.fire_bundle_event( BundleEvent(BundleEvent.STOPPED, self) ) # All bundles have been stopped, release "wait_for_stop" self._fw_stop_event.set() # Force the registry clean up self._registry.clear() return True
[ "def", "stop", "(", "self", ")", ":", "# type: () -> bool", "with", "self", ".", "_lock", ":", "if", "self", ".", "_state", "!=", "Bundle", ".", "ACTIVE", ":", "# Invalid state", "return", "False", "# Hide all services (they will be deleted by bundle.stop())", "for"...
Stops the framework :return: True if the framework stopped, False it wasn't running
[ "Stops", "the", "framework" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1195-L1250
9,673
tcalmant/ipopo
pelix/framework.py
Framework.delete
def delete(self, force=False): """ Deletes the current framework :param force: If True, stops the framework before deleting it :return: True if the framework has been delete, False if is couldn't """ if not force and self._state not in ( Bundle.INSTALLED, Bundle.RESOLVED, Bundle.STOPPING, ): _logger.warning("Trying to delete an active framework") return False return FrameworkFactory.delete_framework(self)
python
def delete(self, force=False): if not force and self._state not in ( Bundle.INSTALLED, Bundle.RESOLVED, Bundle.STOPPING, ): _logger.warning("Trying to delete an active framework") return False return FrameworkFactory.delete_framework(self)
[ "def", "delete", "(", "self", ",", "force", "=", "False", ")", ":", "if", "not", "force", "and", "self", ".", "_state", "not", "in", "(", "Bundle", ".", "INSTALLED", ",", "Bundle", ".", "RESOLVED", ",", "Bundle", ".", "STOPPING", ",", ")", ":", "_l...
Deletes the current framework :param force: If True, stops the framework before deleting it :return: True if the framework has been delete, False if is couldn't
[ "Deletes", "the", "current", "framework" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1252-L1267
9,674
tcalmant/ipopo
pelix/framework.py
Framework.unregister_service
def unregister_service(self, registration): # type: (ServiceRegistration) -> bool """ Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference """ # Get the Service Reference reference = registration.get_reference() # Remove the service from the registry svc_instance = self._registry.unregister(reference) # Keep a track of the unregistering reference self.__unregistering_services[reference] = svc_instance # Call the listeners event = ServiceEvent(ServiceEvent.UNREGISTERING, reference) self._dispatcher.fire_service_event(event) # Update the bundle registration information bundle = reference.get_bundle() bundle._unregistered_service(registration) # Remove the unregistering reference del self.__unregistering_services[reference] return True
python
def unregister_service(self, registration): # type: (ServiceRegistration) -> bool # Get the Service Reference reference = registration.get_reference() # Remove the service from the registry svc_instance = self._registry.unregister(reference) # Keep a track of the unregistering reference self.__unregistering_services[reference] = svc_instance # Call the listeners event = ServiceEvent(ServiceEvent.UNREGISTERING, reference) self._dispatcher.fire_service_event(event) # Update the bundle registration information bundle = reference.get_bundle() bundle._unregistered_service(registration) # Remove the unregistering reference del self.__unregistering_services[reference] return True
[ "def", "unregister_service", "(", "self", ",", "registration", ")", ":", "# type: (ServiceRegistration) -> bool", "# Get the Service Reference", "reference", "=", "registration", ".", "get_reference", "(", ")", "# Remove the service from the registry", "svc_instance", "=", "s...
Unregisters the given service :param registration: A ServiceRegistration to the service to unregister :raise BundleException: Invalid reference
[ "Unregisters", "the", "given", "service" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1323-L1350
9,675
tcalmant/ipopo
pelix/framework.py
Framework.update
def update(self): """ Stops and starts the framework, if the framework is active. :raise BundleException: Something wrong occurred while stopping or starting the framework. """ with self._lock: if self._state == Bundle.ACTIVE: self.stop() self.start()
python
def update(self): with self._lock: if self._state == Bundle.ACTIVE: self.stop() self.start()
[ "def", "update", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_state", "==", "Bundle", ".", "ACTIVE", ":", "self", ".", "stop", "(", ")", "self", ".", "start", "(", ")" ]
Stops and starts the framework, if the framework is active. :raise BundleException: Something wrong occurred while stopping or starting the framework.
[ "Stops", "and", "starts", "the", "framework", "if", "the", "framework", "is", "active", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1371-L1381
9,676
tcalmant/ipopo
pelix/framework.py
Framework.wait_for_stop
def wait_for_stop(self, timeout=None): # type: (Optional[int]) -> bool """ Waits for the framework to stop. Does nothing if the framework bundle is not in ACTIVE state. Uses a threading.Condition object :param timeout: The maximum time to wait (in seconds) :return: True if the framework has stopped, False if the timeout raised """ if self._state != Bundle.ACTIVE: # Inactive framework, ignore the call return True self._fw_stop_event.wait(timeout) with self._lock: # If the timeout raised, we should be in another state return self._state == Bundle.RESOLVED
python
def wait_for_stop(self, timeout=None): # type: (Optional[int]) -> bool if self._state != Bundle.ACTIVE: # Inactive framework, ignore the call return True self._fw_stop_event.wait(timeout) with self._lock: # If the timeout raised, we should be in another state return self._state == Bundle.RESOLVED
[ "def", "wait_for_stop", "(", "self", ",", "timeout", "=", "None", ")", ":", "# type: (Optional[int]) -> bool", "if", "self", ".", "_state", "!=", "Bundle", ".", "ACTIVE", ":", "# Inactive framework, ignore the call", "return", "True", "self", ".", "_fw_stop_event", ...
Waits for the framework to stop. Does nothing if the framework bundle is not in ACTIVE state. Uses a threading.Condition object :param timeout: The maximum time to wait (in seconds) :return: True if the framework has stopped, False if the timeout raised
[ "Waits", "for", "the", "framework", "to", "stop", ".", "Does", "nothing", "if", "the", "framework", "bundle", "is", "not", "in", "ACTIVE", "state", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1383-L1402
9,677
tcalmant/ipopo
pelix/framework.py
ServiceObjects.unget_service
def unget_service(self, service): # type: (Any) -> bool """ Releases a service object for the associated service. :param service: An instance of a service returned by ``get_service()`` :return: True if the bundle usage has been removed """ return self.__registry.unget_service( self.__bundle, self.__reference, service )
python
def unget_service(self, service): # type: (Any) -> bool return self.__registry.unget_service( self.__bundle, self.__reference, service )
[ "def", "unget_service", "(", "self", ",", "service", ")", ":", "# type: (Any) -> bool", "return", "self", ".", "__registry", ".", "unget_service", "(", "self", ".", "__bundle", ",", "self", ".", "__reference", ",", "service", ")" ]
Releases a service object for the associated service. :param service: An instance of a service returned by ``get_service()`` :return: True if the bundle usage has been removed
[ "Releases", "a", "service", "object", "for", "the", "associated", "service", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1440-L1450
9,678
tcalmant/ipopo
pelix/framework.py
BundleContext.get_service_reference
def get_service_reference(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[ServiceReference] """ Returns a ServiceReference object for a service that implements and was registered under the specified class :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: A service reference, None if not found """ result = self.__framework.find_service_references( clazz, ldap_filter, True ) try: return result[0] except TypeError: return None
python
def get_service_reference(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[ServiceReference] result = self.__framework.find_service_references( clazz, ldap_filter, True ) try: return result[0] except TypeError: return None
[ "def", "get_service_reference", "(", "self", ",", "clazz", ",", "ldap_filter", "=", "None", ")", ":", "# type: (Optional[str], Optional[str]) -> Optional[ServiceReference]", "result", "=", "self", ".", "__framework", ".", "find_service_references", "(", "clazz", ",", "l...
Returns a ServiceReference object for a service that implements and was registered under the specified class :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: A service reference, None if not found
[ "Returns", "a", "ServiceReference", "object", "for", "a", "service", "that", "implements", "and", "was", "registered", "under", "the", "specified", "class" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1621-L1637
9,679
tcalmant/ipopo
pelix/framework.py
BundleContext.get_service_references
def get_service_references(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]] """ Returns the service references for services that were registered under the specified class by this bundle and matching the given filter :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: The list of references to the services registered by the calling bundle and matching the filters. """ refs = self.__framework.find_service_references(clazz, ldap_filter) if refs: for ref in refs: if ref.get_bundle() is not self.__bundle: refs.remove(ref) return refs
python
def get_service_references(self, clazz, ldap_filter=None): # type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]] refs = self.__framework.find_service_references(clazz, ldap_filter) if refs: for ref in refs: if ref.get_bundle() is not self.__bundle: refs.remove(ref) return refs
[ "def", "get_service_references", "(", "self", ",", "clazz", ",", "ldap_filter", "=", "None", ")", ":", "# type: (Optional[str], Optional[str]) -> Optional[List[ServiceReference]]", "refs", "=", "self", ".", "__framework", ".", "find_service_references", "(", "clazz", ",",...
Returns the service references for services that were registered under the specified class by this bundle and matching the given filter :param clazz: The class name with which the service was registered. :param ldap_filter: A filter on service properties :return: The list of references to the services registered by the calling bundle and matching the filters.
[ "Returns", "the", "service", "references", "for", "services", "that", "were", "registered", "under", "the", "specified", "class", "by", "this", "bundle", "and", "matching", "the", "given", "filter" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1639-L1656
9,680
tcalmant/ipopo
pelix/framework.py
BundleContext.register_service
def register_service( self, clazz, service, properties, send_event=True, factory=False, prototype=False, ): # type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration """ Registers a service :param clazz: Class or Classes (list) implemented by this service :param service: The service instance :param properties: The services properties (dictionary) :param send_event: If not, doesn't trigger a service registered event :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: A ServiceRegistration object :raise BundleException: An error occurred while registering the service """ return self.__framework.register_service( self.__bundle, clazz, service, properties, send_event, factory, prototype, )
python
def register_service( self, clazz, service, properties, send_event=True, factory=False, prototype=False, ): # type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration return self.__framework.register_service( self.__bundle, clazz, service, properties, send_event, factory, prototype, )
[ "def", "register_service", "(", "self", ",", "clazz", ",", "service", ",", "properties", ",", "send_event", "=", "True", ",", "factory", "=", "False", ",", "prototype", "=", "False", ",", ")", ":", "# type: (Union[List[Any], type, str], object, dict, bool, bool, boo...
Registers a service :param clazz: Class or Classes (list) implemented by this service :param service: The service instance :param properties: The services properties (dictionary) :param send_event: If not, doesn't trigger a service registered event :param factory: If True, the given service is a service factory :param prototype: If True, the given service is a prototype service factory (the factory argument is considered True) :return: A ServiceRegistration object :raise BundleException: An error occurred while registering the service
[ "Registers", "a", "service" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1723-L1754
9,681
tcalmant/ipopo
pelix/framework.py
BundleContext.unget_service
def unget_service(self, reference): # type: (ServiceReference) -> bool """ Disables a reference to the service :return: True if the bundle was using this reference, else False """ # Lose the dependency return self.__framework._registry.unget_service( self.__bundle, reference )
python
def unget_service(self, reference): # type: (ServiceReference) -> bool # Lose the dependency return self.__framework._registry.unget_service( self.__bundle, reference )
[ "def", "unget_service", "(", "self", ",", "reference", ")", ":", "# type: (ServiceReference) -> bool", "# Lose the dependency", "return", "self", ".", "__framework", ".", "_registry", ".", "unget_service", "(", "self", ".", "__bundle", ",", "reference", ")" ]
Disables a reference to the service :return: True if the bundle was using this reference, else False
[ "Disables", "a", "reference", "to", "the", "service" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1784-L1794
9,682
tcalmant/ipopo
pelix/framework.py
FrameworkFactory.get_framework
def get_framework(cls, properties=None): # type: (Optional[dict]) -> Framework """ If it doesn't exist yet, creates a framework with the given properties, else returns the current framework instance. :return: A Pelix instance """ if cls.__singleton is None: # Normalize sys.path normalize_path() cls.__singleton = Framework(properties) return cls.__singleton
python
def get_framework(cls, properties=None): # type: (Optional[dict]) -> Framework if cls.__singleton is None: # Normalize sys.path normalize_path() cls.__singleton = Framework(properties) return cls.__singleton
[ "def", "get_framework", "(", "cls", ",", "properties", "=", "None", ")", ":", "# type: (Optional[dict]) -> Framework", "if", "cls", ".", "__singleton", "is", "None", ":", "# Normalize sys.path", "normalize_path", "(", ")", "cls", ".", "__singleton", "=", "Framewor...
If it doesn't exist yet, creates a framework with the given properties, else returns the current framework instance. :return: A Pelix instance
[ "If", "it", "doesn", "t", "exist", "yet", "creates", "a", "framework", "with", "the", "given", "properties", "else", "returns", "the", "current", "framework", "instance", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1809-L1822
9,683
tcalmant/ipopo
pelix/framework.py
FrameworkFactory.delete_framework
def delete_framework(cls, framework=None): # type: (Optional[Framework]) -> bool # pylint: disable=W0212 """ Removes the framework singleton :return: True on success, else False """ if framework is None: framework = cls.__singleton if framework is cls.__singleton: # Stop the framework try: framework.stop() except: _logger.exception("Error stopping the framework") # Uninstall its bundles bundles = framework.get_bundles() for bundle in bundles: try: bundle.uninstall() except: _logger.exception( "Error uninstalling bundle %s", bundle.get_symbolic_name(), ) # Clear the event dispatcher framework._dispatcher.clear() # Clear the singleton cls.__singleton = None return True return False
python
def delete_framework(cls, framework=None): # type: (Optional[Framework]) -> bool # pylint: disable=W0212 if framework is None: framework = cls.__singleton if framework is cls.__singleton: # Stop the framework try: framework.stop() except: _logger.exception("Error stopping the framework") # Uninstall its bundles bundles = framework.get_bundles() for bundle in bundles: try: bundle.uninstall() except: _logger.exception( "Error uninstalling bundle %s", bundle.get_symbolic_name(), ) # Clear the event dispatcher framework._dispatcher.clear() # Clear the singleton cls.__singleton = None return True return False
[ "def", "delete_framework", "(", "cls", ",", "framework", "=", "None", ")", ":", "# type: (Optional[Framework]) -> bool", "# pylint: disable=W0212", "if", "framework", "is", "None", ":", "framework", "=", "cls", ".", "__singleton", "if", "framework", "is", "cls", "...
Removes the framework singleton :return: True on success, else False
[ "Removes", "the", "framework", "singleton" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/framework.py#L1841-L1877
9,684
tcalmant/ipopo
pelix/rsa/__init__.py
get_matching_interfaces
def get_matching_interfaces(object_class, exported_intfs): # type: (List[str], Optional[List[str]]) -> Optional[List[str]] """ Returns the list of interfaces matching the export property :param object_class: The specifications of the service :param exported_intfs: The declared exported interfaces :return: The list of declared exported interfaces """ if object_class is None or exported_intfs is None: return None if isinstance(exported_intfs, str) and exported_intfs == "*": return object_class # after this exported_intfs will be list exported_intfs = get_string_plus_property_value(exported_intfs) if len(exported_intfs) == 1 and exported_intfs[0] == "*": return object_class return exported_intfs
python
def get_matching_interfaces(object_class, exported_intfs): # type: (List[str], Optional[List[str]]) -> Optional[List[str]] if object_class is None or exported_intfs is None: return None if isinstance(exported_intfs, str) and exported_intfs == "*": return object_class # after this exported_intfs will be list exported_intfs = get_string_plus_property_value(exported_intfs) if len(exported_intfs) == 1 and exported_intfs[0] == "*": return object_class return exported_intfs
[ "def", "get_matching_interfaces", "(", "object_class", ",", "exported_intfs", ")", ":", "# type: (List[str], Optional[List[str]]) -> Optional[List[str]]", "if", "object_class", "is", "None", "or", "exported_intfs", "is", "None", ":", "return", "None", "if", "isinstance", ...
Returns the list of interfaces matching the export property :param object_class: The specifications of the service :param exported_intfs: The declared exported interfaces :return: The list of declared exported interfaces
[ "Returns", "the", "list", "of", "interfaces", "matching", "the", "export", "property" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1109-L1129
9,685
tcalmant/ipopo
pelix/rsa/__init__.py
get_prop_value
def get_prop_value(name, props, default=None): # type: (str, Dict[str, Any], Any) -> Any """ Returns the value of a property or the default one :param name: Name of a property :param props: Dictionary of properties :param default: Default value :return: The value of the property or the default one """ if not props: return default try: return props[name] except KeyError: return default
python
def get_prop_value(name, props, default=None): # type: (str, Dict[str, Any], Any) -> Any if not props: return default try: return props[name] except KeyError: return default
[ "def", "get_prop_value", "(", "name", ",", "props", ",", "default", "=", "None", ")", ":", "# type: (str, Dict[str, Any], Any) -> Any", "if", "not", "props", ":", "return", "default", "try", ":", "return", "props", "[", "name", "]", "except", "KeyError", ":", ...
Returns the value of a property or the default one :param name: Name of a property :param props: Dictionary of properties :param default: Default value :return: The value of the property or the default one
[ "Returns", "the", "value", "of", "a", "property", "or", "the", "default", "one" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1132-L1148
9,686
tcalmant/ipopo
pelix/rsa/__init__.py
set_prop_if_null
def set_prop_if_null(name, props, if_null): # type: (str, Dict[str, Any], Any) -> None """ Updates the value of a property if the previous one was None :param name: Name of the property :param props: Dictionary of properties :param if_null: Value to insert if the previous was None """ value = get_prop_value(name, props) if value is None: props[name] = if_null
python
def set_prop_if_null(name, props, if_null): # type: (str, Dict[str, Any], Any) -> None value = get_prop_value(name, props) if value is None: props[name] = if_null
[ "def", "set_prop_if_null", "(", "name", ",", "props", ",", "if_null", ")", ":", "# type: (str, Dict[str, Any], Any) -> None", "value", "=", "get_prop_value", "(", "name", ",", "props", ")", "if", "value", "is", "None", ":", "props", "[", "name", "]", "=", "i...
Updates the value of a property if the previous one was None :param name: Name of the property :param props: Dictionary of properties :param if_null: Value to insert if the previous was None
[ "Updates", "the", "value", "of", "a", "property", "if", "the", "previous", "one", "was", "None" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1151-L1162
9,687
tcalmant/ipopo
pelix/rsa/__init__.py
get_string_plus_property_value
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] """ Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None """ if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
python
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] if value: if isinstance(value, str): return [value] if isinstance(value, list): return value if isinstance(value, tuple): return list(value) return None
[ "def", "get_string_plus_property_value", "(", "value", ")", ":", "# type: (Any) -> Optional[List[str]]", "if", "value", ":", "if", "isinstance", "(", "value", ",", "str", ")", ":", "return", "[", "value", "]", "if", "isinstance", "(", "value", ",", "list", ")"...
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
[ "Converts", "a", "string", "or", "list", "of", "string", "into", "a", "list", "of", "strings" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1165-L1181
9,688
tcalmant/ipopo
pelix/rsa/__init__.py
get_string_plus_property
def get_string_plus_property(name, props, default=None): # type: (str, Dict[str, Any], Optional[Any]) -> Any """ Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one """ val = get_string_plus_property_value(get_prop_value(name, props, default)) return default if val is None else val
python
def get_string_plus_property(name, props, default=None): # type: (str, Dict[str, Any], Optional[Any]) -> Any val = get_string_plus_property_value(get_prop_value(name, props, default)) return default if val is None else val
[ "def", "get_string_plus_property", "(", "name", ",", "props", ",", "default", "=", "None", ")", ":", "# type: (str, Dict[str, Any], Optional[Any]) -> Any", "val", "=", "get_string_plus_property_value", "(", "get_prop_value", "(", "name", ",", "props", ",", "default", ...
Returns the value of the given property or the default value :param name: A property name :param props: A dictionary of properties :param default: Value to return if the property doesn't exist :return: The property value or the default one
[ "Returns", "the", "value", "of", "the", "given", "property", "or", "the", "default", "value" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1211-L1222
9,689
tcalmant/ipopo
pelix/rsa/__init__.py
get_exported_interfaces
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] """ Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The list of exported interfaces """ # first check overriding_props for service.exported.interfaces exported_intfs = get_prop_value( SERVICE_EXPORTED_INTERFACES, overriding_props ) # then check svc_ref property if not exported_intfs: exported_intfs = svc_ref.get_property(SERVICE_EXPORTED_INTERFACES) if not exported_intfs: return None return get_matching_interfaces( svc_ref.get_property(constants.OBJECTCLASS), exported_intfs )
python
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] # first check overriding_props for service.exported.interfaces exported_intfs = get_prop_value( SERVICE_EXPORTED_INTERFACES, overriding_props ) # then check svc_ref property if not exported_intfs: exported_intfs = svc_ref.get_property(SERVICE_EXPORTED_INTERFACES) if not exported_intfs: return None return get_matching_interfaces( svc_ref.get_property(constants.OBJECTCLASS), exported_intfs )
[ "def", "get_exported_interfaces", "(", "svc_ref", ",", "overriding_props", "=", "None", ")", ":", "# type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]]", "# first check overriding_props for service.exported.interfaces", "exported_intfs", "=", "get_prop_value", "(...
Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The list of exported interfaces
[ "Looks", "for", "the", "interfaces", "exported", "by", "a", "service" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1235-L1257
9,690
tcalmant/ipopo
pelix/rsa/__init__.py
validate_exported_interfaces
def validate_exported_interfaces(object_class, exported_intfs): # type: (List[str], List[str]) -> bool """ Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True if the exported specifications are all provided by the service """ if ( not exported_intfs or not isinstance(exported_intfs, list) or not exported_intfs ): return False else: for exintf in exported_intfs: if exintf not in object_class: return False return True
python
def validate_exported_interfaces(object_class, exported_intfs): # type: (List[str], List[str]) -> bool if ( not exported_intfs or not isinstance(exported_intfs, list) or not exported_intfs ): return False else: for exintf in exported_intfs: if exintf not in object_class: return False return True
[ "def", "validate_exported_interfaces", "(", "object_class", ",", "exported_intfs", ")", ":", "# type: (List[str], List[str]) -> bool", "if", "(", "not", "exported_intfs", "or", "not", "isinstance", "(", "exported_intfs", ",", "list", ")", "or", "not", "exported_intfs", ...
Validates that the exported interfaces are all provided by the service :param object_class: The specifications of a service :param exported_intfs: The exported specifications :return: True if the exported specifications are all provided by the service
[ "Validates", "that", "the", "exported", "interfaces", "are", "all", "provided", "by", "the", "service" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1260-L1279
9,691
tcalmant/ipopo
pelix/rsa/__init__.py
get_package_versions
def get_package_versions(intfs, props): # type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]] """ Gets the package version of interfaces :param intfs: A list of interfaces :param props: A dictionary containing endpoint package versions :return: A list of tuples (package name, version) """ result = [] for intf in intfs: pkg_name = get_package_from_classname(intf) if pkg_name: key = ENDPOINT_PACKAGE_VERSION_ + pkg_name val = props.get(key, None) if val: result.append((key, val)) return result
python
def get_package_versions(intfs, props): # type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]] result = [] for intf in intfs: pkg_name = get_package_from_classname(intf) if pkg_name: key = ENDPOINT_PACKAGE_VERSION_ + pkg_name val = props.get(key, None) if val: result.append((key, val)) return result
[ "def", "get_package_versions", "(", "intfs", ",", "props", ")", ":", "# type: (List[str], Dict[str, Any]) -> List[Tuple[str, str]]", "result", "=", "[", "]", "for", "intf", "in", "intfs", ":", "pkg_name", "=", "get_package_from_classname", "(", "intf", ")", "if", "p...
Gets the package version of interfaces :param intfs: A list of interfaces :param props: A dictionary containing endpoint package versions :return: A list of tuples (package name, version)
[ "Gets", "the", "package", "version", "of", "interfaces" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1296-L1313
9,692
tcalmant/ipopo
pelix/rsa/__init__.py
get_rsa_props
def get_rsa_props( object_class, exported_cfgs, remote_intents=None, ep_svc_id=None, fw_id=None, pkg_vers=None, service_intents=None, ): """ Constructs a dictionary of RSA properties from the given arguments :param object_class: Service specifications :param exported_cfgs: Export configurations :param remote_intents: Supported remote intents :param ep_svc_id: Endpoint service ID :param fw_id: Remote Framework ID :param pkg_vers: Version number of the specification package :param service_intents: Service intents :return: A dictionary of properties """ results = {} if not object_class: raise ArgumentError( "object_class", "object_class must be an [] of Strings" ) results["objectClass"] = object_class if not exported_cfgs: raise ArgumentError( "exported_cfgs", "exported_cfgs must be an array of Strings" ) results[REMOTE_CONFIGS_SUPPORTED] = exported_cfgs results[SERVICE_IMPORTED_CONFIGS] = exported_cfgs if remote_intents: results[REMOTE_INTENTS_SUPPORTED] = remote_intents if service_intents: results[SERVICE_INTENTS] = service_intents if not ep_svc_id: ep_svc_id = get_next_rsid() results[ENDPOINT_SERVICE_ID] = ep_svc_id results[SERVICE_ID] = ep_svc_id if not fw_id: # No framework ID means an error fw_id = "endpoint-in-error" results[ENDPOINT_FRAMEWORK_UUID] = fw_id if pkg_vers: if isinstance(pkg_vers, type(tuple())): pkg_vers = [pkg_vers] for pkg_ver in pkg_vers: results[pkg_ver[0]] = pkg_ver[1] results[ENDPOINT_ID] = create_uuid() results[SERVICE_IMPORTED] = "true" return results
python
def get_rsa_props( object_class, exported_cfgs, remote_intents=None, ep_svc_id=None, fw_id=None, pkg_vers=None, service_intents=None, ): results = {} if not object_class: raise ArgumentError( "object_class", "object_class must be an [] of Strings" ) results["objectClass"] = object_class if not exported_cfgs: raise ArgumentError( "exported_cfgs", "exported_cfgs must be an array of Strings" ) results[REMOTE_CONFIGS_SUPPORTED] = exported_cfgs results[SERVICE_IMPORTED_CONFIGS] = exported_cfgs if remote_intents: results[REMOTE_INTENTS_SUPPORTED] = remote_intents if service_intents: results[SERVICE_INTENTS] = service_intents if not ep_svc_id: ep_svc_id = get_next_rsid() results[ENDPOINT_SERVICE_ID] = ep_svc_id results[SERVICE_ID] = ep_svc_id if not fw_id: # No framework ID means an error fw_id = "endpoint-in-error" results[ENDPOINT_FRAMEWORK_UUID] = fw_id if pkg_vers: if isinstance(pkg_vers, type(tuple())): pkg_vers = [pkg_vers] for pkg_ver in pkg_vers: results[pkg_ver[0]] = pkg_ver[1] results[ENDPOINT_ID] = create_uuid() results[SERVICE_IMPORTED] = "true" return results
[ "def", "get_rsa_props", "(", "object_class", ",", "exported_cfgs", ",", "remote_intents", "=", "None", ",", "ep_svc_id", "=", "None", ",", "fw_id", "=", "None", ",", "pkg_vers", "=", "None", ",", "service_intents", "=", "None", ",", ")", ":", "results", "=...
Constructs a dictionary of RSA properties from the given arguments :param object_class: Service specifications :param exported_cfgs: Export configurations :param remote_intents: Supported remote intents :param ep_svc_id: Endpoint service ID :param fw_id: Remote Framework ID :param pkg_vers: Version number of the specification package :param service_intents: Service intents :return: A dictionary of properties
[ "Constructs", "a", "dictionary", "of", "RSA", "properties", "from", "the", "given", "arguments" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1369-L1421
9,693
tcalmant/ipopo
pelix/rsa/__init__.py
get_ecf_props
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None): """ Prepares the ECF properties :param ep_id: Endpoint ID :param ep_id_ns: Namespace of the Endpoint ID :param rsvc_id: Remote service ID :param ep_ts: Timestamp of the endpoint :return: A dictionary of ECF properties """ results = {} if not ep_id: raise ArgumentError("ep_id", "ep_id must be a valid endpoint id") results[ECF_ENDPOINT_ID] = ep_id if not ep_id_ns: raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace") results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns if not rsvc_id: rsvc_id = get_next_rsid() results[ECF_RSVC_ID] = rsvc_id if not ep_ts: ep_ts = time_since_epoch() results[ECF_ENDPOINT_TIMESTAMP] = ep_ts return results
python
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None): results = {} if not ep_id: raise ArgumentError("ep_id", "ep_id must be a valid endpoint id") results[ECF_ENDPOINT_ID] = ep_id if not ep_id_ns: raise ArgumentError("ep_id_ns", "ep_id_ns must be a valid namespace") results[ECF_ENDPOINT_CONTAINERID_NAMESPACE] = ep_id_ns if not rsvc_id: rsvc_id = get_next_rsid() results[ECF_RSVC_ID] = rsvc_id if not ep_ts: ep_ts = time_since_epoch() results[ECF_ENDPOINT_TIMESTAMP] = ep_ts return results
[ "def", "get_ecf_props", "(", "ep_id", ",", "ep_id_ns", ",", "rsvc_id", "=", "None", ",", "ep_ts", "=", "None", ")", ":", "results", "=", "{", "}", "if", "not", "ep_id", ":", "raise", "ArgumentError", "(", "\"ep_id\"", ",", "\"ep_id must be a valid endpoint i...
Prepares the ECF properties :param ep_id: Endpoint ID :param ep_id_ns: Namespace of the Endpoint ID :param rsvc_id: Remote service ID :param ep_ts: Timestamp of the endpoint :return: A dictionary of ECF properties
[ "Prepares", "the", "ECF", "properties" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1424-L1447
9,694
tcalmant/ipopo
pelix/rsa/__init__.py
get_edef_props
def get_edef_props( object_class, exported_cfgs, ep_namespace, ep_id, ecf_ep_id, ep_rsvc_id, ep_ts, remote_intents=None, fw_id=None, pkg_ver=None, service_intents=None, ): """ Prepares the EDEF properties of an endpoint, merge of RSA and ECF properties """ osgi_props = get_rsa_props( object_class, exported_cfgs, remote_intents, ep_rsvc_id, fw_id, pkg_ver, service_intents, ) ecf_props = get_ecf_props(ecf_ep_id, ep_namespace, ep_rsvc_id, ep_ts) return merge_dicts(osgi_props, ecf_props)
python
def get_edef_props( object_class, exported_cfgs, ep_namespace, ep_id, ecf_ep_id, ep_rsvc_id, ep_ts, remote_intents=None, fw_id=None, pkg_ver=None, service_intents=None, ): osgi_props = get_rsa_props( object_class, exported_cfgs, remote_intents, ep_rsvc_id, fw_id, pkg_ver, service_intents, ) ecf_props = get_ecf_props(ecf_ep_id, ep_namespace, ep_rsvc_id, ep_ts) return merge_dicts(osgi_props, ecf_props)
[ "def", "get_edef_props", "(", "object_class", ",", "exported_cfgs", ",", "ep_namespace", ",", "ep_id", ",", "ecf_ep_id", ",", "ep_rsvc_id", ",", "ep_ts", ",", "remote_intents", "=", "None", ",", "fw_id", "=", "None", ",", "pkg_ver", "=", "None", ",", "servic...
Prepares the EDEF properties of an endpoint, merge of RSA and ECF properties
[ "Prepares", "the", "EDEF", "properties", "of", "an", "endpoint", "merge", "of", "RSA", "and", "ECF", "properties" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1467-L1494
9,695
tcalmant/ipopo
pelix/rsa/__init__.py
get_dot_properties
def get_dot_properties(prefix, props, remove_prefix): # type: (str, Dict[str, Any], bool) -> Dict[str, Any] """ Gets the properties starting with the given prefix """ result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot_keys: if remove_prefix: new_key = dot_key[len(prefix) + 1 :] else: new_key = dot_key result_props[new_key] = props.get(dot_key) return result_props
python
def get_dot_properties(prefix, props, remove_prefix): # type: (str, Dict[str, Any], bool) -> Dict[str, Any] result_props = {} if props: dot_keys = [x for x in props.keys() if x.startswith(prefix + ".")] for dot_key in dot_keys: if remove_prefix: new_key = dot_key[len(prefix) + 1 :] else: new_key = dot_key result_props[new_key] = props.get(dot_key) return result_props
[ "def", "get_dot_properties", "(", "prefix", ",", "props", ",", "remove_prefix", ")", ":", "# type: (str, Dict[str, Any], bool) -> Dict[str, Any]", "result_props", "=", "{", "}", "if", "props", ":", "dot_keys", "=", "[", "x", "for", "x", "in", "props", ".", "keys...
Gets the properties starting with the given prefix
[ "Gets", "the", "properties", "starting", "with", "the", "given", "prefix" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1513-L1527
9,696
tcalmant/ipopo
pelix/rsa/__init__.py
copy_non_reserved
def copy_non_reserved(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary """ target.update( { key: value for key, value in props.items() if not is_reserved_property(key) } ) return target
python
def copy_non_reserved(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] target.update( { key: value for key, value in props.items() if not is_reserved_property(key) } ) return target
[ "def", "copy_non_reserved", "(", "props", ",", "target", ")", ":", "# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]", "target", ".", "update", "(", "{", "key", ":", "value", "for", "key", ",", "value", "in", "props", ".", "items", "(", ")", "if", "n...
Copies all properties with non-reserved names from ``props`` to ``target`` :param props: A dictionary of properties :param target: Another dictionary :return: The target dictionary
[ "Copies", "all", "properties", "with", "non", "-", "reserved", "names", "from", "props", "to", "target" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1563-L1579
9,697
tcalmant/ipopo
pelix/rsa/__init__.py
copy_non_ecf
def copy_non_ecf(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] """ Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary """ target.update( {key: value for key, value in props.items() if key not in ECFPROPNAMES} ) return target
python
def copy_non_ecf(props, target): # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] target.update( {key: value for key, value in props.items() if key not in ECFPROPNAMES} ) return target
[ "def", "copy_non_ecf", "(", "props", ",", "target", ")", ":", "# type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any]", "target", ".", "update", "(", "{", "key", ":", "value", "for", "key", ",", "value", "in", "props", ".", "items", "(", ")", "if", "key", ...
Copies non-ECF properties from ``props`` to ``target`` :param props: An input dictionary :param target: The dictionary to copy non-ECF properties to :return: The ``target`` dictionary
[ "Copies", "non", "-", "ECF", "properties", "from", "props", "to", "target" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1582-L1594
9,698
tcalmant/ipopo
pelix/rsa/__init__.py
set_append
def set_append(input_set, item): # type: (set, Any) -> set """ Appends in-place the given item to the set. If the item is a list, all elements are added to the set. :param input_set: An existing set :param item: The item or list of items to add :return: The given set """ if item: if isinstance(item, (list, tuple)): input_set.update(item) else: input_set.add(item) return input_set
python
def set_append(input_set, item): # type: (set, Any) -> set if item: if isinstance(item, (list, tuple)): input_set.update(item) else: input_set.add(item) return input_set
[ "def", "set_append", "(", "input_set", ",", "item", ")", ":", "# type: (set, Any) -> set", "if", "item", ":", "if", "isinstance", "(", "item", ",", "(", "list", ",", "tuple", ")", ")", ":", "input_set", ".", "update", "(", "item", ")", "else", ":", "in...
Appends in-place the given item to the set. If the item is a list, all elements are added to the set. :param input_set: An existing set :param item: The item or list of items to add :return: The given set
[ "Appends", "in", "-", "place", "the", "given", "item", "to", "the", "set", ".", "If", "the", "item", "is", "a", "list", "all", "elements", "are", "added", "to", "the", "set", "." ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L1597-L1612
9,699
tcalmant/ipopo
pelix/rsa/__init__.py
RemoteServiceAdminEvent.fromimportreg
def fromimportreg(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent """ Creates a RemoteServiceAdminEvent object from an ImportRegistration """ exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_REGISTRATION, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
python
def fromimportreg(cls, bundle, import_reg): # type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent exc = import_reg.get_exception() if exc: return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_ERROR, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), None, None, exc, import_reg.get_description(), ) return RemoteServiceAdminEvent( RemoteServiceAdminEvent.IMPORT_REGISTRATION, bundle, import_reg.get_import_container_id(), import_reg.get_remoteservice_id(), import_reg.get_import_reference(), None, None, import_reg.get_description(), )
[ "def", "fromimportreg", "(", "cls", ",", "bundle", ",", "import_reg", ")", ":", "# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent", "exc", "=", "import_reg", ".", "get_exception", "(", ")", "if", "exc", ":", "return", "RemoteServiceAdminEvent", "(", "Re...
Creates a RemoteServiceAdminEvent object from an ImportRegistration
[ "Creates", "a", "RemoteServiceAdminEvent", "object", "from", "an", "ImportRegistration" ]
2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/__init__.py#L769-L796