repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
tcalmant/ipopo
samples/handler/logger_minimal.py
_LoggerHandlerFactory.get_handlers
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component (never None) """ # Extract information from the context logger_field = component_context.get_handler(constants.HANDLER_LOGGER) if not logger_field: # Error: log it and either raise an exception # or ignore this handler _logger.warning("Logger iPOPO handler can't find its configuration") else: # Create the logger for this component instance logger = logging.getLogger(component_context.name) # Inject it setattr(instance, logger_field, logger) logger.debug("Logger has been injected") # No need to have an instance handler return []
python
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component (never None) """ # Extract information from the context logger_field = component_context.get_handler(constants.HANDLER_LOGGER) if not logger_field: # Error: log it and either raise an exception # or ignore this handler _logger.warning("Logger iPOPO handler can't find its configuration") else: # Create the logger for this component instance logger = logging.getLogger(component_context.name) # Inject it setattr(instance, logger_field, logger) logger.debug("Logger has been injected") # No need to have an instance handler return []
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component (never None)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/samples/handler/logger_minimal.py#L100-L125
tcalmant/ipopo
pelix/shell/console.py
_resolve_file
def _resolve_file(file_name): """ Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None """ if not file_name: return None path = os.path.realpath(file_name) if os.path.isfile(path): return path return None
python
def _resolve_file(file_name): """ Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None """ if not file_name: return None path = os.path.realpath(file_name) if os.path.isfile(path): return path return None
Checks if the file exists. If the file exists, the method returns its absolute path. Else, it returns None :param file_name: The name of the file to check :return: An absolute path, or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L497-L514
tcalmant/ipopo
pelix/shell/console.py
make_common_parser
def make_common_parser(): """ Creates an argument parser (argparse module) with the options that should be common to all shells. The result can be used as a parent parser (``parents`` argument in ``argparse.ArgumentParser``) :return: An ArgumentParser object """ parser = argparse.ArgumentParser(add_help=False) # Version number parser.add_argument( "--version", action="version", version="Pelix {0} from {1}".format(pelix.__version__, pelix.__file__), ) # Framework options group = parser.add_argument_group("Framework options") group.add_argument( "-D", nargs="+", dest="properties", metavar="KEY=VALUE", help="Sets framework properties", ) group.add_argument( "-v", "--verbose", action="store_true", help="Set loggers to DEBUG level", ) # Initial configuration group = parser.add_argument_group("Initial configuration") group.add_argument( "-c", "--conf", dest="init_conf", metavar="FILE", help="Name of an initial configuration file to use " "(default configuration is also loaded)", ) group.add_argument( "-C", "--exclusive-conf", dest="init_conf_exclusive", metavar="FILE", help="Name of an initial configuration file to use " "(without the default configuration)", ) group.add_argument( "-e", "--empty-conf", dest="init_empty", action="store_true", help="Don't load any initial configuration", ) # Initial script group = parser.add_argument_group("Script execution arguments") group.add_argument( "--init", action="store", dest="init_script", metavar="SCRIPT", help="Runs the given shell script before starting the console", ) group.add_argument( "--run", action="store", dest="run_script", metavar="SCRIPT", help="Runs the given shell script then stops the framework", ) return parser
python
def make_common_parser(): """ Creates an argument parser (argparse module) with the options that should be common to all shells. The result can be used as a parent parser (``parents`` argument in ``argparse.ArgumentParser``) :return: An ArgumentParser object """ parser = argparse.ArgumentParser(add_help=False) # Version number parser.add_argument( "--version", action="version", version="Pelix {0} from {1}".format(pelix.__version__, pelix.__file__), ) # Framework options group = parser.add_argument_group("Framework options") group.add_argument( "-D", nargs="+", dest="properties", metavar="KEY=VALUE", help="Sets framework properties", ) group.add_argument( "-v", "--verbose", action="store_true", help="Set loggers to DEBUG level", ) # Initial configuration group = parser.add_argument_group("Initial configuration") group.add_argument( "-c", "--conf", dest="init_conf", metavar="FILE", help="Name of an initial configuration file to use " "(default configuration is also loaded)", ) group.add_argument( "-C", "--exclusive-conf", dest="init_conf_exclusive", metavar="FILE", help="Name of an initial configuration file to use " "(without the default configuration)", ) group.add_argument( "-e", "--empty-conf", dest="init_empty", action="store_true", help="Don't load any initial configuration", ) # Initial script group = parser.add_argument_group("Script execution arguments") group.add_argument( "--init", action="store", dest="init_script", metavar="SCRIPT", help="Runs the given shell script before starting the console", ) group.add_argument( "--run", action="store", dest="run_script", metavar="SCRIPT", help="Runs the given shell script then stops the framework", ) return parser
Creates an argument parser (argparse module) with the options that should be common to all shells. The result can be used as a parent parser (``parents`` argument in ``argparse.ArgumentParser``) :return: An ArgumentParser object
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L517-L594
tcalmant/ipopo
pelix/shell/console.py
handle_common_arguments
def handle_common_arguments(parsed_args): """ Handles the arguments defined by :meth:`~make_common_parser` :param parsed_args: Argument parsed with ``argparse`` (``Namespace``) :return: An :class:`~InitFileHandler` object :raise IOError: Initial or run script not found """ # Setup the logger logging.basicConfig( level=logging.DEBUG if parsed_args.verbose else logging.WARNING ) # Framework properties dictionary props = {} # Read the initial configuration script init = InitFileHandler() if not parsed_args.init_empty: if not parsed_args.init_conf_exclusive: # Load default configuration init.load() # Load the given configuration file conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf if conf_file: init.load(conf_file) # Normalize configuration init.normalize() # Set initial framework properties props.update(init.properties) # Compute framework properties for prop_def in parsed_args.properties or []: key, value = prop_def.split("=", 1) props[key] = value # Check initial run script(s) if parsed_args.init_script: path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script) if not path: raise IOError( "Initial script file not found: {0}".format( parsed_args.init_script ) ) if parsed_args.run_script: # Find the file path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script) if not path: raise IOError( "Script file not found: {0}".format(parsed_args.run_script) ) # Update the stored configuration init.properties.update(props) return init
python
def handle_common_arguments(parsed_args): """ Handles the arguments defined by :meth:`~make_common_parser` :param parsed_args: Argument parsed with ``argparse`` (``Namespace``) :return: An :class:`~InitFileHandler` object :raise IOError: Initial or run script not found """ # Setup the logger logging.basicConfig( level=logging.DEBUG if parsed_args.verbose else logging.WARNING ) # Framework properties dictionary props = {} # Read the initial configuration script init = InitFileHandler() if not parsed_args.init_empty: if not parsed_args.init_conf_exclusive: # Load default configuration init.load() # Load the given configuration file conf_file = parsed_args.init_conf_exclusive or parsed_args.init_conf if conf_file: init.load(conf_file) # Normalize configuration init.normalize() # Set initial framework properties props.update(init.properties) # Compute framework properties for prop_def in parsed_args.properties or []: key, value = prop_def.split("=", 1) props[key] = value # Check initial run script(s) if parsed_args.init_script: path = props[PROP_INIT_FILE] = _resolve_file(parsed_args.init_script) if not path: raise IOError( "Initial script file not found: {0}".format( parsed_args.init_script ) ) if parsed_args.run_script: # Find the file path = props[PROP_RUN_FILE] = _resolve_file(parsed_args.run_script) if not path: raise IOError( "Script file not found: {0}".format(parsed_args.run_script) ) # Update the stored configuration init.properties.update(props) return init
Handles the arguments defined by :meth:`~make_common_parser` :param parsed_args: Argument parsed with ``argparse`` (``Namespace``) :return: An :class:`~InitFileHandler` object :raise IOError: Initial or run script not found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L597-L656
tcalmant/ipopo
pelix/shell/console.py
main
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Parse arguments parser = argparse.ArgumentParser( prog="pelix.shell.console", parents=[make_common_parser()], description="Pelix Shell Console", ) # Parse arguments args = parser.parse_args(argv) # Handle arguments init = handle_common_arguments(args) # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.completion.pelix", "pelix.shell.completion.ipopo", "pelix.shell.console", ] bundles.extend(init.bundles) # Use the utility method to create, run and delete the framework framework = pelix.create_framework( remove_duplicates(bundles), init.properties ) framework.start() # Instantiate components init.instantiate_components(framework.get_bundle_context()) try: framework.wait_for_stop() except KeyboardInterrupt: framework.stop()
python
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Parse arguments parser = argparse.ArgumentParser( prog="pelix.shell.console", parents=[make_common_parser()], description="Pelix Shell Console", ) # Parse arguments args = parser.parse_args(argv) # Handle arguments init = handle_common_arguments(args) # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.completion.pelix", "pelix.shell.completion.ipopo", "pelix.shell.console", ] bundles.extend(init.bundles) # Use the utility method to create, run and delete the framework framework = pelix.create_framework( remove_duplicates(bundles), init.properties ) framework.start() # Instantiate components init.instantiate_components(framework.get_bundle_context()) try: framework.wait_for_stop() except KeyboardInterrupt: framework.stop()
Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L659-L702
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell._normal_prompt
def _normal_prompt(self): """ Flushes the prompt before requesting the input :return: The command line """ sys.stdout.write(self.__get_ps1()) sys.stdout.flush() return safe_input()
python
def _normal_prompt(self): """ Flushes the prompt before requesting the input :return: The command line """ sys.stdout.write(self.__get_ps1()) sys.stdout.flush() return safe_input()
Flushes the prompt before requesting the input :return: The command line
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L137-L145
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.loop_input
def loop_input(self, on_quit=None): """ Reads the standard input until the shell session is stopped :param on_quit: A call back method, called without argument when the shell session has ended """ # Start the init script self._run_script( self.__session, self._context.get_property(PROP_INIT_FILE) ) # Run the script script_file = self._context.get_property(PROP_RUN_FILE) if script_file: self._run_script(self.__session, script_file) else: # No script: run the main loop (blocking) self._run_loop(self.__session) # Nothing more to do self._stop_event.set() sys.stdout.write("Bye !\n") sys.stdout.flush() if on_quit is not None: # Call a handler if needed on_quit()
python
def loop_input(self, on_quit=None): """ Reads the standard input until the shell session is stopped :param on_quit: A call back method, called without argument when the shell session has ended """ # Start the init script self._run_script( self.__session, self._context.get_property(PROP_INIT_FILE) ) # Run the script script_file = self._context.get_property(PROP_RUN_FILE) if script_file: self._run_script(self.__session, script_file) else: # No script: run the main loop (blocking) self._run_loop(self.__session) # Nothing more to do self._stop_event.set() sys.stdout.write("Bye !\n") sys.stdout.flush() if on_quit is not None: # Call a handler if needed on_quit()
Reads the standard input until the shell session is stopped :param on_quit: A call back method, called without argument when the shell session has ended
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L147-L173
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell._run_script
def _run_script(self, session, file_path): """ Runs the given script file :param session: Current shell session :param file_path: Path to the file to execute :return: True if a file has been execute """ if file_path: # The 'run' command returns False in case of error # The 'execute' method returns False if the run command fails return self._shell.execute('run "{0}"'.format(file_path), session) return None
python
def _run_script(self, session, file_path): """ Runs the given script file :param session: Current shell session :param file_path: Path to the file to execute :return: True if a file has been execute """ if file_path: # The 'run' command returns False in case of error # The 'execute' method returns False if the run command fails return self._shell.execute('run "{0}"'.format(file_path), session) return None
Runs the given script file :param session: Current shell session :param file_path: Path to the file to execute :return: True if a file has been execute
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L175-L188
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell._run_loop
def _run_loop(self, session): """ Runs the main input loop :param session: Current shell session """ try: first_prompt = True # Set up the prompt prompt = ( self._readline_prompt if readline is not None else self._normal_prompt ) while not self._stop_event.is_set(): # Wait for the shell to be there # Before Python 2.7, wait() doesn't return a result if self._shell_event.wait(.2) or self._shell_event.is_set(): # Shell present if first_prompt: # Show the banner on first prompt sys.stdout.write(self._shell.get_banner()) first_prompt = False # Read the next line line = prompt() with self._lock: if self._shell_event.is_set(): # Execute it self._shell.execute(line, session) elif not self._stop_event.is_set(): # Shell service lost while not stopping sys.stdout.write("Shell service lost.") sys.stdout.flush() except (EOFError, KeyboardInterrupt, SystemExit): # Input closed or keyboard interruption pass
python
def _run_loop(self, session): """ Runs the main input loop :param session: Current shell session """ try: first_prompt = True # Set up the prompt prompt = ( self._readline_prompt if readline is not None else self._normal_prompt ) while not self._stop_event.is_set(): # Wait for the shell to be there # Before Python 2.7, wait() doesn't return a result if self._shell_event.wait(.2) or self._shell_event.is_set(): # Shell present if first_prompt: # Show the banner on first prompt sys.stdout.write(self._shell.get_banner()) first_prompt = False # Read the next line line = prompt() with self._lock: if self._shell_event.is_set(): # Execute it self._shell.execute(line, session) elif not self._stop_event.is_set(): # Shell service lost while not stopping sys.stdout.write("Shell service lost.") sys.stdout.flush() except (EOFError, KeyboardInterrupt, SystemExit): # Input closed or keyboard interruption pass
Runs the main input loop :param session: Current shell session
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L190-L230
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.readline_completer
def readline_completer(self, text, state): """ A completer for the readline library """ if state == 0: # New completion, reset the list of matches and the display hook self._readline_matches = [] try: readline.set_completion_display_matches_hook(None) except AttributeError: pass # Get the full line full_line = readline.get_line_buffer() begin_idx = readline.get_begidx() # Parse arguments as best as we can try: arguments = shlex.split(full_line) except ValueError: arguments = full_line.split() # Extract the command (maybe with its namespace) command = arguments.pop(0) if begin_idx > 0: # We're completing after the command (and maybe some args) try: # Find the command ns, command = self._shell.get_ns_command(command) except ValueError: # Ambiguous command: ignore return None # Use the completer associated to the command, if any try: configuration = self._shell.get_command_completers( ns, command ) if configuration is not None: self._readline_matches = completion_hints( configuration, self.__get_ps1(), self.__session, self._context, text, arguments, ) except KeyError: # Unknown command pass elif "." in command: # Completing the command, and a name space is given namespace, prefix = text.split(".", 2) commands = self._shell.get_commands(namespace) # Filter methods according to the prefix self._readline_matches = [ "{0}.{1}".format(namespace, command) for command in commands if command.startswith(prefix) ] else: # Completing a command or namespace prefix = command # Default commands goes first... possibilities = [ "{0} ".format(command) for command in self._shell.get_commands(None) if command.startswith(prefix) ] # ... then name spaces namespaces = self._shell.get_namespaces() possibilities.extend( "{0}.".format(namespace) for namespace in namespaces if namespace.startswith(prefix) ) # ... then commands in those name spaces possibilities.extend( "{0} ".format(command) for namespace in namespaces if namespace is not None for command in self._shell.get_commands(namespace) if command.startswith(prefix) ) # Filter methods according to the prefix self._readline_matches = possibilities if not self._readline_matches: return None # Return the first possibility return self._readline_matches[0] elif state < len(self._readline_matches): # Next try return self._readline_matches[state] return None
python
def readline_completer(self, text, state): """ A completer for the readline library """ if state == 0: # New completion, reset the list of matches and the display hook self._readline_matches = [] try: readline.set_completion_display_matches_hook(None) except AttributeError: pass # Get the full line full_line = readline.get_line_buffer() begin_idx = readline.get_begidx() # Parse arguments as best as we can try: arguments = shlex.split(full_line) except ValueError: arguments = full_line.split() # Extract the command (maybe with its namespace) command = arguments.pop(0) if begin_idx > 0: # We're completing after the command (and maybe some args) try: # Find the command ns, command = self._shell.get_ns_command(command) except ValueError: # Ambiguous command: ignore return None # Use the completer associated to the command, if any try: configuration = self._shell.get_command_completers( ns, command ) if configuration is not None: self._readline_matches = completion_hints( configuration, self.__get_ps1(), self.__session, self._context, text, arguments, ) except KeyError: # Unknown command pass elif "." in command: # Completing the command, and a name space is given namespace, prefix = text.split(".", 2) commands = self._shell.get_commands(namespace) # Filter methods according to the prefix self._readline_matches = [ "{0}.{1}".format(namespace, command) for command in commands if command.startswith(prefix) ] else: # Completing a command or namespace prefix = command # Default commands goes first... possibilities = [ "{0} ".format(command) for command in self._shell.get_commands(None) if command.startswith(prefix) ] # ... then name spaces namespaces = self._shell.get_namespaces() possibilities.extend( "{0}.".format(namespace) for namespace in namespaces if namespace.startswith(prefix) ) # ... then commands in those name spaces possibilities.extend( "{0} ".format(command) for namespace in namespaces if namespace is not None for command in self._shell.get_commands(namespace) if command.startswith(prefix) ) # Filter methods according to the prefix self._readline_matches = possibilities if not self._readline_matches: return None # Return the first possibility return self._readline_matches[0] elif state < len(self._readline_matches): # Next try return self._readline_matches[state] return None
A completer for the readline library
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L232-L336
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.search_shell
def search_shell(self): """ Looks for a shell service """ with self._lock: if self._shell is not None: # A shell is already there return reference = self._context.get_service_reference(SERVICE_SHELL) if reference is not None: self.set_shell(reference)
python
def search_shell(self): """ Looks for a shell service """ with self._lock: if self._shell is not None: # A shell is already there return reference = self._context.get_service_reference(SERVICE_SHELL) if reference is not None: self.set_shell(reference)
Looks for a shell service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L338-L349
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.service_changed
def service_changed(self, event): """ Called by Pelix when an events changes """ kind = event.get_kind() reference = event.get_service_reference() if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED): # A service matches our filter self.set_shell(reference) else: with self._lock: # Service is not matching our filter anymore self.clear_shell() # Request for a new binding self.search_shell()
python
def service_changed(self, event): """ Called by Pelix when an events changes """ kind = event.get_kind() reference = event.get_service_reference() if kind in (pelix.ServiceEvent.REGISTERED, pelix.ServiceEvent.MODIFIED): # A service matches our filter self.set_shell(reference) else: with self._lock: # Service is not matching our filter anymore self.clear_shell() # Request for a new binding self.search_shell()
Called by Pelix when an events changes
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L351-L368
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.set_shell
def set_shell(self, svc_ref): """ Binds the given shell service. :param svc_ref: A service reference """ if svc_ref is None: return with self._lock: # Get the service self._shell_ref = svc_ref self._shell = self._context.get_service(self._shell_ref) # Set the readline completer if readline is not None: readline.set_completer(self.readline_completer) # Set the flag self._shell_event.set()
python
def set_shell(self, svc_ref): """ Binds the given shell service. :param svc_ref: A service reference """ if svc_ref is None: return with self._lock: # Get the service self._shell_ref = svc_ref self._shell = self._context.get_service(self._shell_ref) # Set the readline completer if readline is not None: readline.set_completer(self.readline_completer) # Set the flag self._shell_event.set()
Binds the given shell service. :param svc_ref: A service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L370-L389
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.clear_shell
def clear_shell(self): """ Unbinds the active shell service """ with self._lock: # Clear the flag self._shell_event.clear() # Clear the readline completer if readline is not None: readline.set_completer(None) del self._readline_matches[:] if self._shell_ref is not None: # Release the service self._context.unget_service(self._shell_ref) self._shell_ref = None self._shell = None
python
def clear_shell(self): """ Unbinds the active shell service """ with self._lock: # Clear the flag self._shell_event.clear() # Clear the readline completer if readline is not None: readline.set_completer(None) del self._readline_matches[:] if self._shell_ref is not None: # Release the service self._context.unget_service(self._shell_ref) self._shell_ref = None self._shell = None
Unbinds the active shell service
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L391-L409
tcalmant/ipopo
pelix/shell/console.py
InteractiveShell.stop
def stop(self): """ Clears all members """ # Exit the loop with self._lock: self._stop_event.set() self._shell_event.clear() if self._context is not None: # Unregister from events self._context.remove_service_listener(self) # Release the shell self.clear_shell() self._context = None
python
def stop(self): """ Clears all members """ # Exit the loop with self._lock: self._stop_event.set() self._shell_event.clear() if self._context is not None: # Unregister from events self._context.remove_service_listener(self) # Release the shell self.clear_shell() self._context = None
Clears all members
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/console.py#L411-L426
tcalmant/ipopo
pelix/remote/json_rpc.py
_JsonRpcServlet.do_POST
def do_POST(self, request, response): # pylint: disable=C0103 """ Handles a HTTP POST request :param request: The HTTP request bean :param response: The HTTP response handler """ try: # Get the request content data = to_str(request.read_data()) # Dispatch result = self._marshaled_dispatch(data, self._simple_dispatch) # Send the result response.send_content(200, result, "application/json-rpc") except Exception as ex: response.send_content( 500, "Internal error:\n{0}\n".format(ex), "text/plain" )
python
def do_POST(self, request, response): # pylint: disable=C0103 """ Handles a HTTP POST request :param request: The HTTP request bean :param response: The HTTP response handler """ try: # Get the request content data = to_str(request.read_data()) # Dispatch result = self._marshaled_dispatch(data, self._simple_dispatch) # Send the result response.send_content(200, result, "application/json-rpc") except Exception as ex: response.send_content( 500, "Internal error:\n{0}\n".format(ex), "text/plain" )
Handles a HTTP POST request :param request: The HTTP request bean :param response: The HTTP response handler
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/remote/json_rpc.py#L115-L135
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_HandlerFactory._prepare_requirements
def _prepare_requirements(requirements, requires_filters): """ Overrides the filters specified in the decorator with the given ones :param requirements: Dictionary of requirements (field → Requirement) :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new requirements """ if not requires_filters or not isinstance(requires_filters, dict): # No explicit filter configured return requirements # We need to change a part of the requirements new_requirements = {} for field, requirement in requirements.items(): try: explicit_filter = requires_filters[field] # Store an updated copy of the requirement requirement_copy = requirement.copy() requirement_copy.set_filter(explicit_filter) new_requirements[field] = requirement_copy except (KeyError, TypeError, ValueError): # No information for this one, or invalid filter: # keep the factory requirement new_requirements[field] = requirement return new_requirements
python
def _prepare_requirements(requirements, requires_filters): """ Overrides the filters specified in the decorator with the given ones :param requirements: Dictionary of requirements (field → Requirement) :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new requirements """ if not requires_filters or not isinstance(requires_filters, dict): # No explicit filter configured return requirements # We need to change a part of the requirements new_requirements = {} for field, requirement in requirements.items(): try: explicit_filter = requires_filters[field] # Store an updated copy of the requirement requirement_copy = requirement.copy() requirement_copy.set_filter(explicit_filter) new_requirements[field] = requirement_copy except (KeyError, TypeError, ValueError): # No information for this one, or invalid filter: # keep the factory requirement new_requirements[field] = requirement return new_requirements
Overrides the filters specified in the decorator with the given ones :param requirements: Dictionary of requirements (field → Requirement) :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new requirements
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L59-L88
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_HandlerFactory.get_handlers
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Extract information from the context requirements = component_context.get_handler( ipopo_constants.HANDLER_REQUIRES ) requires_filters = component_context.properties.get( ipopo_constants.IPOPO_REQUIRES_FILTERS, None ) # Prepare requirements requirements = self._prepare_requirements( requirements, requires_filters ) # Set up the runtime dependency handlers handlers = [] for field, requirement in requirements.items(): # Construct the handler if requirement.aggregate: handlers.append(AggregateDependency(field, requirement)) else: handlers.append(SimpleDependency(field, requirement)) return handlers
python
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Extract information from the context requirements = component_context.get_handler( ipopo_constants.HANDLER_REQUIRES ) requires_filters = component_context.properties.get( ipopo_constants.IPOPO_REQUIRES_FILTERS, None ) # Prepare requirements requirements = self._prepare_requirements( requirements, requires_filters ) # Set up the runtime dependency handlers handlers = [] for field, requirement in requirements.items(): # Construct the handler if requirement.aggregate: handlers.append(AggregateDependency(field, requirement)) else: handlers.append(SimpleDependency(field, requirement)) return handlers
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L90-L120
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_RuntimeDependency.manipulate
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instance = stored_instance # ... and the bundle context self._context = stored_instance.bundle_context
python
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instance = stored_instance # ... and the bundle context self._context = stored_instance.bundle_context
Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L193-L204
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_RuntimeDependency.clear
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self._lock = None self._ipopo_instance = None self._context = None self.requirement = None self._value = None self._field = None
python
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self._lock = None self._ipopo_instance = None self._context = None self.requirement = None self._value = None self._field = None
Cleans up the manager. The manager can't be used after this method has been called
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L206-L216
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_RuntimeDependency.service_changed
def service_changed(self, event): """ Called by the framework when a service event occurs """ if ( self._ipopo_instance is None or not self._ipopo_instance.check_event(event) ): # stop() and clean() may have been called after we have been put # inside a listener list copy... # or we've been told to ignore this event return # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming self.on_service_arrival(svc_ref) elif kind in ( ServiceEvent.UNREGISTERING, ServiceEvent.MODIFIED_ENDMATCH, ): # Service gone or not matching anymore self.on_service_departure(svc_ref) elif kind == ServiceEvent.MODIFIED: # Modified properties (can be a new injection) self.on_service_modify(svc_ref, event.get_previous_properties())
python
def service_changed(self, event): """ Called by the framework when a service event occurs """ if ( self._ipopo_instance is None or not self._ipopo_instance.check_event(event) ): # stop() and clean() may have been called after we have been put # inside a listener list copy... # or we've been told to ignore this event return # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming self.on_service_arrival(svc_ref) elif kind in ( ServiceEvent.UNREGISTERING, ServiceEvent.MODIFIED_ENDMATCH, ): # Service gone or not matching anymore self.on_service_departure(svc_ref) elif kind == ServiceEvent.MODIFIED: # Modified properties (can be a new injection) self.on_service_modify(svc_ref, event.get_previous_properties())
Called by the framework when a service event occurs
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L282-L312
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
_RuntimeDependency.start
def start(self): """ Starts the dependency manager """ self._context.add_service_listener( self, self.requirement.filter, self.requirement.specification )
python
def start(self): """ Starts the dependency manager """ self._context.add_service_listener( self, self.requirement.filter, self.requirement.specification )
Starts the dependency manager
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L314-L320
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.clear
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.reference = None self._pending_ref = None super(SimpleDependency, self).clear()
python
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.reference = None self._pending_ref = None super(SimpleDependency, self).clear()
Cleans up the manager. The manager can't be used after this method has been called
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L348-L355
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.on_service_arrival
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if self._value is None: # Inject the service self.reference = svc_ref self._value = self._context.get_service(svc_ref) self._ipopo_instance.bind(self, self._value, self.reference) return True return None
python
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if self._value is None: # Inject the service self.reference = svc_ref self._value = self._context.get_service(svc_ref) self._ipopo_instance.bind(self, self._value, self.reference) return True return None
Called when a service has been registered in the framework :param svc_ref: A service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L369-L384
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.on_service_modify
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values """ with self._lock: if self.reference is None: # A previously registered service now matches our filter self.on_service_arrival(svc_ref) elif svc_ref is self.reference: # Notify the property modification self._ipopo_instance.update( self, self._value, svc_ref, old_properties )
python
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values """ with self._lock: if self.reference is None: # A previously registered service now matches our filter self.on_service_arrival(svc_ref) elif svc_ref is self.reference: # Notify the property modification self._ipopo_instance.update( self, self._value, svc_ref, old_properties )
Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L411-L426
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.stop
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ super(SimpleDependency, self).stop() if self.reference is not None: # Return a tuple of tuple return ((self._value, self.reference),) return None
python
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ super(SimpleDependency, self).stop() if self.reference is not None: # Return a tuple of tuple return ((self._value, self.reference),) return None
Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L428-L439
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.is_valid
def is_valid(self): """ Tests if the dependency is in a valid state """ return super(SimpleDependency, self).is_valid() or ( self.requirement.immediate_rebind and self._pending_ref is not None )
python
def is_valid(self): """ Tests if the dependency is in a valid state """ return super(SimpleDependency, self).is_valid() or ( self.requirement.immediate_rebind and self._pending_ref is not None )
Tests if the dependency is in a valid state
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L441-L447
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
SimpleDependency.try_binding
def try_binding(self): """ Searches for the required service if needed :raise BundleException: Invalid ServiceReference found """ with self._lock: if self.reference is not None: # Already bound return if self._pending_ref is not None: # Get the reference we chose to keep this component valid ref = self._pending_ref self._pending_ref = None else: # Get the first matching service ref = self._context.get_service_reference( self.requirement.specification, self.requirement.filter ) if ref is not None: # Found a service self.on_service_arrival(ref)
python
def try_binding(self): """ Searches for the required service if needed :raise BundleException: Invalid ServiceReference found """ with self._lock: if self.reference is not None: # Already bound return if self._pending_ref is not None: # Get the reference we chose to keep this component valid ref = self._pending_ref self._pending_ref = None else: # Get the first matching service ref = self._context.get_service_reference( self.requirement.specification, self.requirement.filter ) if ref is not None: # Found a service self.on_service_arrival(ref)
Searches for the required service if needed :raise BundleException: Invalid ServiceReference found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L449-L472
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
AggregateDependency.clear
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.services.clear() self.services = None self._future_value = None super(AggregateDependency, self).clear()
python
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.services.clear() self.services = None self._future_value = None super(AggregateDependency, self).clear()
Cleans up the manager. The manager can't be used after this method has been called
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L492-L500
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
AggregateDependency.on_service_arrival
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if svc_ref not in self.services: # Get the new service service = self._context.get_service(svc_ref) if self._future_value is None: # First value self._future_value = [] # Store the information self._future_value.append(service) self.services[svc_ref] = service self._ipopo_instance.bind(self, service, svc_ref) return True return None
python
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if svc_ref not in self.services: # Get the new service service = self._context.get_service(svc_ref) if self._future_value is None: # First value self._future_value = [] # Store the information self._future_value.append(service) self.services[svc_ref] = service self._ipopo_instance.bind(self, service, svc_ref) return True return None
Called when a service has been registered in the framework :param svc_ref: A service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L532-L554
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
AggregateDependency.on_service_departure
def on_service_departure(self, svc_ref): """ Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None """ with self._lock: try: # Get the service instance service = self.services.pop(svc_ref) except KeyError: # Not a known service reference: ignore pass else: # Clean the instance values self._future_value.remove(service) # Nullify the value if needed if not self._future_value: self._future_value = None self._ipopo_instance.unbind(self, service, svc_ref) return True return None
python
def on_service_departure(self, svc_ref): """ Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None """ with self._lock: try: # Get the service instance service = self.services.pop(svc_ref) except KeyError: # Not a known service reference: ignore pass else: # Clean the instance values self._future_value.remove(service) # Nullify the value if needed if not self._future_value: self._future_value = None self._ipopo_instance.unbind(self, service, svc_ref) return True return None
Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L556-L582
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
AggregateDependency.on_service_modify
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None """ with self._lock: try: # Look for the service service = self.services[svc_ref] except KeyError: # A previously registered service now matches our filter return self.on_service_arrival(svc_ref) else: # Notify the property modification self._ipopo_instance.update( self, service, svc_ref, old_properties ) return None
python
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None """ with self._lock: try: # Look for the service service = self.services[svc_ref] except KeyError: # A previously registered service now matches our filter return self.on_service_arrival(svc_ref) else: # Notify the property modification self._ipopo_instance.update( self, service, svc_ref, old_properties ) return None
Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L584-L606
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
AggregateDependency.stop
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ super(AggregateDependency, self).stop() if self.services: return [ (service, reference) for reference, service in self.services.items() ] return None
python
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ super(AggregateDependency, self).stop() if self.services: return [ (service, reference) for reference, service in self.services.items() ] return None
Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L608-L622
tcalmant/ipopo
pelix/misc/log.py
LogReaderService._store_entry
def _store_entry(self, entry): """ Stores a new log entry and notifies listeners :param entry: A LogEntry object """ # Get the logger and log the message self.__logs.append(entry) # Notify listeners for listener in self.__listeners.copy(): try: listener.logged(entry) except Exception as ex: # Create a new log entry, without using logging nor notifying # listener (to avoid a recursion) err_entry = LogEntry( logging.WARNING, "Error notifying logging listener {0}: {1}".format( listener, ex ), sys.exc_info(), self._context.get_bundle(), None, ) # Insert the new entry before the real one self.__logs.pop() self.__logs.append(err_entry) self.__logs.append(entry)
python
def _store_entry(self, entry): """ Stores a new log entry and notifies listeners :param entry: A LogEntry object """ # Get the logger and log the message self.__logs.append(entry) # Notify listeners for listener in self.__listeners.copy(): try: listener.logged(entry) except Exception as ex: # Create a new log entry, without using logging nor notifying # listener (to avoid a recursion) err_entry = LogEntry( logging.WARNING, "Error notifying logging listener {0}: {1}".format( listener, ex ), sys.exc_info(), self._context.get_bundle(), None, ) # Insert the new entry before the real one self.__logs.pop() self.__logs.append(err_entry) self.__logs.append(entry)
Stores a new log entry and notifies listeners :param entry: A LogEntry object
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L241-L270
tcalmant/ipopo
pelix/misc/log.py
LogServiceInstance.log
def log(self, level, message, exc_info=None, reference=None): # pylint: disable=W0212 """ Logs a message, possibly with an exception :param level: Severity of the message (Python logging level) :param message: Human readable message :param exc_info: The exception context (sys.exc_info()), if any :param reference: The ServiceReference associated to the log """ if not isinstance(reference, pelix.framework.ServiceReference): # Ensure we have a clean Service Reference reference = None if exc_info is not None: # Format the exception to avoid memory leaks try: exception_str = "\n".join(traceback.format_exception(*exc_info)) except (TypeError, ValueError, AttributeError): exception_str = "<Invalid exc_info>" else: exception_str = None # Store the LogEntry entry = LogEntry( level, message, exception_str, self.__bundle, reference ) self.__reader._store_entry(entry)
python
def log(self, level, message, exc_info=None, reference=None): # pylint: disable=W0212 """ Logs a message, possibly with an exception :param level: Severity of the message (Python logging level) :param message: Human readable message :param exc_info: The exception context (sys.exc_info()), if any :param reference: The ServiceReference associated to the log """ if not isinstance(reference, pelix.framework.ServiceReference): # Ensure we have a clean Service Reference reference = None if exc_info is not None: # Format the exception to avoid memory leaks try: exception_str = "\n".join(traceback.format_exception(*exc_info)) except (TypeError, ValueError, AttributeError): exception_str = "<Invalid exc_info>" else: exception_str = None # Store the LogEntry entry = LogEntry( level, message, exception_str, self.__bundle, reference ) self.__reader._store_entry(entry)
Logs a message, possibly with an exception :param level: Severity of the message (Python logging level) :param message: Human readable message :param exc_info: The exception context (sys.exc_info()), if any :param reference: The ServiceReference associated to the log
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L289-L316
tcalmant/ipopo
pelix/misc/log.py
LogServiceFactory._bundle_from_module
def _bundle_from_module(self, module_object): """ Find the bundle associated to a module :param module_object: A Python module object :return: The Bundle object associated to the module, or None """ try: # Get the module name module_object = module_object.__name__ except AttributeError: # We got a string pass return self._framework.get_bundle_by_name(module_object)
python
def _bundle_from_module(self, module_object): """ Find the bundle associated to a module :param module_object: A Python module object :return: The Bundle object associated to the module, or None """ try: # Get the module name module_object = module_object.__name__ except AttributeError: # We got a string pass return self._framework.get_bundle_by_name(module_object)
Find the bundle associated to a module :param module_object: A Python module object :return: The Bundle object associated to the module, or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L334-L348
tcalmant/ipopo
pelix/misc/log.py
LogServiceFactory.emit
def emit(self, record): # pylint: disable=W0212 """ Handle a message logged with the logger :param record: A log record """ # Get the bundle bundle = self._bundle_from_module(record.module) # Convert to a LogEntry entry = LogEntry( record.levelno, record.getMessage(), None, bundle, None ) self._reader._store_entry(entry)
python
def emit(self, record): # pylint: disable=W0212 """ Handle a message logged with the logger :param record: A log record """ # Get the bundle bundle = self._bundle_from_module(record.module) # Convert to a LogEntry entry = LogEntry( record.levelno, record.getMessage(), None, bundle, None ) self._reader._store_entry(entry)
Handle a message logged with the logger :param record: A log record
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/misc/log.py#L350-L364
tcalmant/ipopo
pelix/services/mqtt.py
_MqttConnection.publish
def publish(self, topic, payload, qos=0, retain=False): """ Publishes an MQTT message """ # TODO: check (full transmission) success return self._client.publish(topic, payload, qos, retain)
python
def publish(self, topic, payload, qos=0, retain=False): """ Publishes an MQTT message """ # TODO: check (full transmission) success return self._client.publish(topic, payload, qos, retain)
Publishes an MQTT message
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/services/mqtt.py#L487-L492
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_HandlerFactory._prepare_requirements
def _prepare_requirements(configs, requires_filters): """ Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new configuration dictionary """ if not requires_filters or not isinstance(requires_filters, dict): # No explicit filter configured return configs # We need to change a part of the requirements new_requirements = {} for field, config in configs.items(): # Extract values from tuple requirement, key, allow_none = config try: explicit_filter = requires_filters[field] # Store an updated copy of the requirement requirement_copy = requirement.copy() requirement_copy.set_filter(explicit_filter) new_requirements[field] = (requirement_copy, key, allow_none) except (KeyError, TypeError, ValueError): # No information for this one, or invalid filter: # keep the factory requirement new_requirements[field] = config return new_requirements
python
def _prepare_requirements(configs, requires_filters): """ Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new configuration dictionary """ if not requires_filters or not isinstance(requires_filters, dict): # No explicit filter configured return configs # We need to change a part of the requirements new_requirements = {} for field, config in configs.items(): # Extract values from tuple requirement, key, allow_none = config try: explicit_filter = requires_filters[field] # Store an updated copy of the requirement requirement_copy = requirement.copy() requirement_copy.set_filter(explicit_filter) new_requirements[field] = (requirement_copy, key, allow_none) except (KeyError, TypeError, ValueError): # No information for this one, or invalid filter: # keep the factory requirement new_requirements[field] = config return new_requirements
Overrides the filters specified in the decorator with the given ones :param configs: Field → (Requirement, key, allow_none) dictionary :param requires_filters: Content of the 'requires.filter' component property (field → string) :return: The new configuration dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L60-L92
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_HandlerFactory.get_handlers
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Extract information from the context configs = component_context.get_handler( ipopo_constants.HANDLER_REQUIRES_MAP ) requires_filters = component_context.properties.get( ipopo_constants.IPOPO_REQUIRES_FILTERS, None ) # Prepare requirements configs = self._prepare_requirements(configs, requires_filters) # Set up the runtime dependency handlers handlers = [] for field, config in configs.items(): # Extract values from tuple requirement, key, allow_none = config # Construct the handler if requirement.aggregate: handlers.append( AggregateDependency(field, requirement, key, allow_none) ) else: handlers.append( SimpleDependency(field, requirement, key, allow_none) ) return handlers
python
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Extract information from the context configs = component_context.get_handler( ipopo_constants.HANDLER_REQUIRES_MAP ) requires_filters = component_context.properties.get( ipopo_constants.IPOPO_REQUIRES_FILTERS, None ) # Prepare requirements configs = self._prepare_requirements(configs, requires_filters) # Set up the runtime dependency handlers handlers = [] for field, config in configs.items(): # Extract values from tuple requirement, key, allow_none = config # Construct the handler if requirement.aggregate: handlers.append( AggregateDependency(field, requirement, key, allow_none) ) else: handlers.append( SimpleDependency(field, requirement, key, allow_none) ) return handlers
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L94-L129
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_RuntimeDependency.manipulate
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instance = stored_instance # ... and the bundle context self._context = stored_instance.bundle_context # Set the default value for the field: an empty dictionary setattr(component_instance, self._field, {})
python
def manipulate(self, stored_instance, component_instance): """ Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance... self._ipopo_instance = stored_instance # ... and the bundle context self._context = stored_instance.bundle_context # Set the default value for the field: an empty dictionary setattr(component_instance, self._field, {})
Stores the given StoredInstance bean. :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L213-L227
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_RuntimeDependency.clear
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.services.clear() self._future_value.clear() self.services = None self._lock = None self._ipopo_instance = None self._context = None self.requirement = None self._key = None self._allow_none = None self._future_value = None self._field = None
python
def clear(self): """ Cleans up the manager. The manager can't be used after this method has been called """ self.services.clear() self._future_value.clear() self.services = None self._lock = None self._ipopo_instance = None self._context = None self.requirement = None self._key = None self._allow_none = None self._future_value = None self._field = None
Cleans up the manager. The manager can't be used after this method has been called
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L229-L245
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_RuntimeDependency.is_valid
def is_valid(self): """ Tests if the dependency is in a valid state """ return ( self.requirement is not None and self.requirement.optional ) or bool(self._future_value)
python
def is_valid(self): """ Tests if the dependency is in a valid state """ return ( self.requirement is not None and self.requirement.optional ) or bool(self._future_value)
Tests if the dependency is in a valid state
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L281-L287
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_RuntimeDependency.stop
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ self._context.remove_service_listener(self) if self.services: return [ (service, reference) for reference, service in self.services.items() ] return None
python
def stop(self): """ Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None """ self._context.remove_service_listener(self) if self.services: return [ (service, reference) for reference, service in self.services.items() ] return None
Stops the dependency manager (must be called before clear()) :return: The removed bindings (list) or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L354-L367
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
_RuntimeDependency.try_binding
def try_binding(self): """ Searches for the required service if needed :raise BundleException: Invalid ServiceReference found """ with self._lock: if self.services: # We already are alive (not our first call) # => we are updated through service events return # Get all matching services refs = self._context.get_all_service_references( self.requirement.specification, self.requirement.filter ) if not refs: # No match found return results = [] try: # Bind all new reference for reference in refs: added = self.on_service_arrival(reference) if added: results.append(reference) except BundleException as ex: # Get the logger for this instance logger = logging.getLogger( "-".join((self._ipopo_instance.name, "RequiresMap-Runtime")) ) logger.debug("Error binding multiple references: %s", ex) # Undo what has just been done, ignoring errors for reference in results: try: self.on_service_departure(reference) except BundleException as ex2: logger.debug("Error cleaning up: %s", ex2) del results[:] raise
python
def try_binding(self): """ Searches for the required service if needed :raise BundleException: Invalid ServiceReference found """ with self._lock: if self.services: # We already are alive (not our first call) # => we are updated through service events return # Get all matching services refs = self._context.get_all_service_references( self.requirement.specification, self.requirement.filter ) if not refs: # No match found return results = [] try: # Bind all new reference for reference in refs: added = self.on_service_arrival(reference) if added: results.append(reference) except BundleException as ex: # Get the logger for this instance logger = logging.getLogger( "-".join((self._ipopo_instance.name, "RequiresMap-Runtime")) ) logger.debug("Error binding multiple references: %s", ex) # Undo what has just been done, ignoring errors for reference in results: try: self.on_service_departure(reference) except BundleException as ex2: logger.debug("Error cleaning up: %s", ex2) del results[:] raise
Searches for the required service if needed :raise BundleException: Invalid ServiceReference found
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L369-L412
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
SimpleDependency.on_service_arrival
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if svc_ref not in self.services: # Get the key property prop_value = svc_ref.get_property(self._key) if ( prop_value not in self._future_value and prop_value is not None or self._allow_none ): # Matching new property value service = self._context.get_service(svc_ref) # Store the information self._future_value[prop_value] = service self.services[svc_ref] = service # Call back iPOPO self._ipopo_instance.bind(self, service, svc_ref) return True return None
python
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if svc_ref not in self.services: # Get the key property prop_value = svc_ref.get_property(self._key) if ( prop_value not in self._future_value and prop_value is not None or self._allow_none ): # Matching new property value service = self._context.get_service(svc_ref) # Store the information self._future_value[prop_value] = service self.services[svc_ref] = service # Call back iPOPO self._ipopo_instance.bind(self, service, svc_ref) return True return None
Called when a service has been registered in the framework :param svc_ref: A service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L420-L446
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
AggregateDependency.__store_service
def __store_service(self, key, service): """ Stores the given service in the dictionary :param key: Dictionary key :param service: Service to add to the dictionary """ self._future_value.setdefault(key, []).append(service)
python
def __store_service(self, key, service): """ Stores the given service in the dictionary :param key: Dictionary key :param service: Service to add to the dictionary """ self._future_value.setdefault(key, []).append(service)
Stores the given service in the dictionary :param key: Dictionary key :param service: Service to add to the dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L521-L528
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
AggregateDependency.__remove_service
def __remove_service(self, key, service): """ Removes the given service from the future dictionary :param key: Dictionary key :param service: Service to remove from the dictionary """ try: # Remove the injected service prop_services = self._future_value[key] prop_services.remove(service) # Clean up if not prop_services: del self._future_value[key] except KeyError: # Ignore: can occur when removing a service with a None property, # if allow_none is False pass
python
def __remove_service(self, key, service): """ Removes the given service from the future dictionary :param key: Dictionary key :param service: Service to remove from the dictionary """ try: # Remove the injected service prop_services = self._future_value[key] prop_services.remove(service) # Clean up if not prop_services: del self._future_value[key] except KeyError: # Ignore: can occur when removing a service with a None property, # if allow_none is False pass
Removes the given service from the future dictionary :param key: Dictionary key :param service: Service to remove from the dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L530-L549
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
AggregateDependency.get_value
def get_value(self): """ Retrieves the value to inject in the component :return: The value to inject """ with self._lock: # The value field must be a deep copy of our dictionary if self._future_value is not None: return { key: value[:] for key, value in self._future_value.items() } return None
python
def get_value(self): """ Retrieves the value to inject in the component :return: The value to inject """ with self._lock: # The value field must be a deep copy of our dictionary if self._future_value is not None: return { key: value[:] for key, value in self._future_value.items() } return None
Retrieves the value to inject in the component :return: The value to inject
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L551-L564
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
AggregateDependency.on_service_departure
def on_service_departure(self, svc_ref): """ Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None """ with self._lock: if svc_ref in self.services: # Get the service instance service = self.services.pop(svc_ref) # Get the key property prop_value = svc_ref.get_property(self._key) # Remove the injected service self.__remove_service(prop_value, service) self._ipopo_instance.unbind(self, service, svc_ref) return True return None
python
def on_service_departure(self, svc_ref): """ Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None """ with self._lock: if svc_ref in self.services: # Get the service instance service = self.services.pop(svc_ref) # Get the key property prop_value = svc_ref.get_property(self._key) # Remove the injected service self.__remove_service(prop_value, service) self._ipopo_instance.unbind(self, service, svc_ref) return True return None
Called when a service has been unregistered from the framework :param svc_ref: A service reference :return: A tuple (service, reference) if the service has been lost, else None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L590-L612
tcalmant/ipopo
pelix/ipopo/handlers/requiresmap.py
AggregateDependency.on_service_modify
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None """ with self._lock: if svc_ref not in self.services: # A previously registered service now matches our filter return self.on_service_arrival(svc_ref) else: # Get the property values service = self.services[svc_ref] old_value = old_properties.get(self._key) prop_value = svc_ref.get_property(self._key) if old_value != prop_value: # Key changed if prop_value is not None or self._allow_none: # New property accepted if old_value is not None or self._allow_none: self.__remove_service(old_value, service) self.__store_service(prop_value, service) # Notify the property modification, with a value change self._ipopo_instance.update( self, service, svc_ref, old_properties, True ) else: # Consider the service as gone self.__remove_service(old_value, service) del self.services[svc_ref] self._ipopo_instance.unbind(self, service, svc_ref) else: # Simple property update self._ipopo_instance.update( self, service, svc_ref, old_properties, False ) return None
python
def on_service_modify(self, svc_ref, old_properties): """ Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None """ with self._lock: if svc_ref not in self.services: # A previously registered service now matches our filter return self.on_service_arrival(svc_ref) else: # Get the property values service = self.services[svc_ref] old_value = old_properties.get(self._key) prop_value = svc_ref.get_property(self._key) if old_value != prop_value: # Key changed if prop_value is not None or self._allow_none: # New property accepted if old_value is not None or self._allow_none: self.__remove_service(old_value, service) self.__store_service(prop_value, service) # Notify the property modification, with a value change self._ipopo_instance.update( self, service, svc_ref, old_properties, True ) else: # Consider the service as gone self.__remove_service(old_value, service) del self.services[svc_ref] self._ipopo_instance.unbind(self, service, svc_ref) else: # Simple property update self._ipopo_instance.update( self, service, svc_ref, old_properties, False ) return None
Called when a service has been modified in the framework :param svc_ref: A service reference :param old_properties: Previous properties values :return: A tuple (added, (service, reference)) if the dependency has been changed, else None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requiresmap.py#L614-L657
tcalmant/ipopo
pelix/rsa/remoteserviceadmin.py
ExportRegistrationImpl.match_sr
def match_sr(self, svc_ref, cid=None): # type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool """ Checks if this export registration matches the given service reference :param svc_ref: A service reference :param cid: A container ID :return: True if the service matches this export registration """ with self.__lock: our_sr = self.get_reference() if our_sr is None: return False sr_compare = our_sr == svc_ref if cid is None: return sr_compare our_cid = self.get_export_container_id() if our_cid is None: return False return sr_compare and our_cid == cid
python
def match_sr(self, svc_ref, cid=None): # type: (ServiceReference, Optional[Tuple[str, str]] ) -> bool """ Checks if this export registration matches the given service reference :param svc_ref: A service reference :param cid: A container ID :return: True if the service matches this export registration """ with self.__lock: our_sr = self.get_reference() if our_sr is None: return False sr_compare = our_sr == svc_ref if cid is None: return sr_compare our_cid = self.get_export_container_id() if our_cid is None: return False return sr_compare and our_cid == cid
Checks if this export registration matches the given service reference :param svc_ref: A service reference :param cid: A container ID :return: True if the service matches this export registration
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L886-L908
tcalmant/ipopo
pelix/rsa/remoteserviceadmin.py
ExportRegistrationImpl.get_exception
def get_exception(self): # type: () -> Optional[Tuple[Any, Any, Any]] """ Returns the exception associated to the export :return: An exception tuple, if any """ with self.__lock: return ( self.__updateexception if self.__updateexception or self.__closed else self.__exportref.get_exception() )
python
def get_exception(self): # type: () -> Optional[Tuple[Any, Any, Any]] """ Returns the exception associated to the export :return: An exception tuple, if any """ with self.__lock: return ( self.__updateexception if self.__updateexception or self.__closed else self.__exportref.get_exception() )
Returns the exception associated to the export :return: An exception tuple, if any
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L970-L982
tcalmant/ipopo
pelix/rsa/remoteserviceadmin.py
ExportRegistrationImpl.close
def close(self): """ Cleans up the export endpoint """ publish = False exporterid = rsid = exception = export_ref = ed = None with self.__lock: if not self.__closed: exporterid = self.__exportref.get_export_container_id() export_ref = self.__exportref rsid = self.__exportref.get_remoteservice_id() ed = self.__exportref.get_description() exception = self.__exportref.get_exception() self.__closed = True publish = self.__exportref.close(self) self.__exportref = None # pylint: disable=W0212 if publish and export_ref and self.__rsa: self.__rsa._publish_event( RemoteServiceAdminEvent.fromexportunreg( self.__rsa._get_bundle(), exporterid, rsid, export_ref, exception, ed, ) ) self.__rsa = None
python
def close(self): """ Cleans up the export endpoint """ publish = False exporterid = rsid = exception = export_ref = ed = None with self.__lock: if not self.__closed: exporterid = self.__exportref.get_export_container_id() export_ref = self.__exportref rsid = self.__exportref.get_remoteservice_id() ed = self.__exportref.get_description() exception = self.__exportref.get_exception() self.__closed = True publish = self.__exportref.close(self) self.__exportref = None # pylint: disable=W0212 if publish and export_ref and self.__rsa: self.__rsa._publish_event( RemoteServiceAdminEvent.fromexportunreg( self.__rsa._get_bundle(), exporterid, rsid, export_ref, exception, ed, ) ) self.__rsa = None
Cleans up the export endpoint
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/remoteserviceadmin.py#L1026-L1055
tcalmant/ipopo
pelix/rsa/providers/discovery/__init__.py
EndpointAdvertiser.advertise_endpoint
def advertise_endpoint(self, endpoint_description): """ Advertise and endpoint_description for remote discovery. If it hasn't already been a endpoint_description will be advertised via a some protocol. :param endpoint_description: an instance of EndpointDescription to advertise. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised) """ endpoint_id = endpoint_description.get_id() with self._published_endpoints_lock: if self.get_advertised_endpoint(endpoint_id) is not None: return False advertise_result = self._advertise(endpoint_description) if advertise_result: self._add_advertised(endpoint_description, advertise_result) return True return False
python
def advertise_endpoint(self, endpoint_description): """ Advertise and endpoint_description for remote discovery. If it hasn't already been a endpoint_description will be advertised via a some protocol. :param endpoint_description: an instance of EndpointDescription to advertise. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised) """ endpoint_id = endpoint_description.get_id() with self._published_endpoints_lock: if self.get_advertised_endpoint(endpoint_id) is not None: return False advertise_result = self._advertise(endpoint_description) if advertise_result: self._add_advertised(endpoint_description, advertise_result) return True return False
Advertise and endpoint_description for remote discovery. If it hasn't already been a endpoint_description will be advertised via a some protocol. :param endpoint_description: an instance of EndpointDescription to advertise. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/discovery/__init__.py#L77-L98
tcalmant/ipopo
pelix/rsa/providers/discovery/__init__.py
EndpointAdvertiser.update_endpoint
def update_endpoint(self, updated_ed): """ Update a previously advertised endpoint_description. :param endpoint_description: an instance of EndpointDescription to update. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised) """ endpoint_id = updated_ed.get_id() with self._published_endpoints_lock: if self.get_advertised_endpoint(endpoint_id) is None: return False advertise_result = self._update(updated_ed) if advertise_result: self._remove_advertised(endpoint_id) self._add_advertised(updated_ed, advertise_result) return True return False
python
def update_endpoint(self, updated_ed): """ Update a previously advertised endpoint_description. :param endpoint_description: an instance of EndpointDescription to update. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised) """ endpoint_id = updated_ed.get_id() with self._published_endpoints_lock: if self.get_advertised_endpoint(endpoint_id) is None: return False advertise_result = self._update(updated_ed) if advertise_result: self._remove_advertised(endpoint_id) self._add_advertised(updated_ed, advertise_result) return True return False
Update a previously advertised endpoint_description. :param endpoint_description: an instance of EndpointDescription to update. Must not be None. :return: True if advertised, False if not (e.g. it's already been advertised)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/discovery/__init__.py#L100-L120
tcalmant/ipopo
pelix/rsa/providers/discovery/__init__.py
EndpointAdvertiser.unadvertise_endpoint
def unadvertise_endpoint(self, endpointid): """ Unadvertise a previously-advertised endpointid (string). :param endpointid. The string returned from ed.get_id() or the value of property endpoint.id. Should not be None :return True if removed, False if not removed (hasn't been previously advertised by this advertiser """ with self._published_endpoints_lock: with self._published_endpoints_lock: advertised = self.get_advertised_endpoint(endpointid) if not advertised: return None unadvertise_result = self._unadvertise(advertised) if unadvertise_result: self._remove_advertised(endpointid) return None
python
def unadvertise_endpoint(self, endpointid): """ Unadvertise a previously-advertised endpointid (string). :param endpointid. The string returned from ed.get_id() or the value of property endpoint.id. Should not be None :return True if removed, False if not removed (hasn't been previously advertised by this advertiser """ with self._published_endpoints_lock: with self._published_endpoints_lock: advertised = self.get_advertised_endpoint(endpointid) if not advertised: return None unadvertise_result = self._unadvertise(advertised) if unadvertise_result: self._remove_advertised(endpointid) return None
Unadvertise a previously-advertised endpointid (string). :param endpointid. The string returned from ed.get_id() or the value of property endpoint.id. Should not be None :return True if removed, False if not removed (hasn't been previously advertised by this advertiser
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/discovery/__init__.py#L122-L142
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
_HandlerFactory.get_handlers
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Retrieve the handler configuration provides = component_context.get_handler( ipopo_constants.HANDLER_PROVIDES ) if not provides: # Nothing to do return () # 1 handler per provided service return [ ServiceRegistrationHandler( specs, controller, is_factory, is_prototype ) for specs, controller, is_factory, is_prototype in provides ]
python
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ # Retrieve the handler configuration provides = component_context.get_handler( ipopo_constants.HANDLER_PROVIDES ) if not provides: # Nothing to do return () # 1 handler per provided service return [ ServiceRegistrationHandler( specs, controller, is_factory, is_prototype ) for specs, controller, is_factory, is_prototype in provides ]
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L56-L78
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler._field_controller_generator
def _field_controller_generator(self): """ Generates the methods called by the injected controller """ # Local variable, to avoid messing with "self" stored_instance = self._ipopo_instance def get_value(self, name): # pylint: disable=W0613 """ Retrieves the controller value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return stored_instance.get_controller_state(name) def set_value(self, name, new_value): # pylint: disable=W0613 """ Sets the property value and trigger an update event :param name: The property name :param new_value: The new property value """ # Get the previous value old_value = stored_instance.get_controller_state(name) if new_value != old_value: # Update the controller state stored_instance.set_controller_state(name, new_value) return new_value return get_value, set_value
python
def _field_controller_generator(self): """ Generates the methods called by the injected controller """ # Local variable, to avoid messing with "self" stored_instance = self._ipopo_instance def get_value(self, name): # pylint: disable=W0613 """ Retrieves the controller value, from the iPOPO dictionaries :param name: The property name :return: The property value """ return stored_instance.get_controller_state(name) def set_value(self, name, new_value): # pylint: disable=W0613 """ Sets the property value and trigger an update event :param name: The property name :param new_value: The new property value """ # Get the previous value old_value = stored_instance.get_controller_state(name) if new_value != old_value: # Update the controller state stored_instance.set_controller_state(name, new_value) return new_value return get_value, set_value
Generates the methods called by the injected controller
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L154-L187
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler.manipulate
def manipulate(self, stored_instance, component_instance): """ Manipulates the component instance :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance self._ipopo_instance = stored_instance if self.__controller is None: # No controller: do nothing return # Get the current value of the member (True by default) controller_value = getattr(component_instance, self.__controller, True) # Store the controller value stored_instance.set_controller_state( self.__controller, controller_value ) # Prepare the methods names getter_name = "{0}{1}".format( ipopo_constants.IPOPO_CONTROLLER_PREFIX, ipopo_constants.IPOPO_GETTER_SUFFIX, ) setter_name = "{0}{1}".format( ipopo_constants.IPOPO_CONTROLLER_PREFIX, ipopo_constants.IPOPO_SETTER_SUFFIX, ) # Inject the getter and setter at the instance level getter, setter = self._field_controller_generator() setattr(component_instance, getter_name, getter) setattr(component_instance, setter_name, setter)
python
def manipulate(self, stored_instance, component_instance): """ Manipulates the component instance :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance """ # Store the stored instance self._ipopo_instance = stored_instance if self.__controller is None: # No controller: do nothing return # Get the current value of the member (True by default) controller_value = getattr(component_instance, self.__controller, True) # Store the controller value stored_instance.set_controller_state( self.__controller, controller_value ) # Prepare the methods names getter_name = "{0}{1}".format( ipopo_constants.IPOPO_CONTROLLER_PREFIX, ipopo_constants.IPOPO_GETTER_SUFFIX, ) setter_name = "{0}{1}".format( ipopo_constants.IPOPO_CONTROLLER_PREFIX, ipopo_constants.IPOPO_SETTER_SUFFIX, ) # Inject the getter and setter at the instance level getter, setter = self._field_controller_generator() setattr(component_instance, getter_name, getter) setattr(component_instance, setter_name, setter)
Manipulates the component instance :param stored_instance: The iPOPO component StoredInstance :param component_instance: The component instance
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L189-L224
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler.on_controller_change
def on_controller_change(self, name, value): """ Called by the instance manager when a controller value has been modified :param name: The name of the controller :param value: The new value of the controller """ if self.__controller != name: # Nothing to do return # Update the controller value self.__controller_on = value if value: # Controller switched to "ON" self._register_service() else: # Controller switched to "OFF" self._unregister_service()
python
def on_controller_change(self, name, value): """ Called by the instance manager when a controller value has been modified :param name: The name of the controller :param value: The new value of the controller """ if self.__controller != name: # Nothing to do return # Update the controller value self.__controller_on = value if value: # Controller switched to "ON" self._register_service() else: # Controller switched to "OFF" self._unregister_service()
Called by the instance manager when a controller value has been modified :param name: The name of the controller :param value: The new value of the controller
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L251-L270
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler.on_property_change
def on_property_change(self, name, old_value, new_value): """ Called by the instance manager when a component property is modified :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value """ if self._registration is not None: # use the registration to trigger the service event self._registration.set_properties({name: new_value})
python
def on_property_change(self, name, old_value, new_value): """ Called by the instance manager when a component property is modified :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value """ if self._registration is not None: # use the registration to trigger the service event self._registration.set_properties({name: new_value})
Called by the instance manager when a component property is modified :param name: The changed property name :param old_value: The previous property value :param new_value: The new property value
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L272-L282
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler._register_service
def _register_service(self): """ Registers the provided service, if possible """ if ( self._registration is None and self.specifications and self.__validated and self.__controller_on ): # Use a copy of component properties properties = self._ipopo_instance.context.properties.copy() bundle_context = self._ipopo_instance.bundle_context # Register the service self._registration = bundle_context.register_service( self.specifications, self._ipopo_instance.instance, properties, factory=self.__is_factory, prototype=self.__is_prototype, ) self._svc_reference = self._registration.get_reference() # Notify the component self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION, self._svc_reference, )
python
def _register_service(self): """ Registers the provided service, if possible """ if ( self._registration is None and self.specifications and self.__validated and self.__controller_on ): # Use a copy of component properties properties = self._ipopo_instance.context.properties.copy() bundle_context = self._ipopo_instance.bundle_context # Register the service self._registration = bundle_context.register_service( self.specifications, self._ipopo_instance.instance, properties, factory=self.__is_factory, prototype=self.__is_prototype, ) self._svc_reference = self._registration.get_reference() # Notify the component self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_REGISTRATION, self._svc_reference, )
Registers the provided service, if possible
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L302-L330
tcalmant/ipopo
pelix/ipopo/handlers/provides.py
ServiceRegistrationHandler._unregister_service
def _unregister_service(self): """ Unregisters the provided service, if needed """ if self._registration is not None: # Ignore error try: self._registration.unregister() except BundleException as ex: # Only log the error at this level logger = logging.getLogger( "-".join((self._ipopo_instance.name, "ServiceRegistration")) ) logger.error("Error unregistering a service: %s", ex) # Notify the component (even in case of error) self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_UNREGISTRATION, self._svc_reference, ) self._registration = None self._svc_reference = None
python
def _unregister_service(self): """ Unregisters the provided service, if needed """ if self._registration is not None: # Ignore error try: self._registration.unregister() except BundleException as ex: # Only log the error at this level logger = logging.getLogger( "-".join((self._ipopo_instance.name, "ServiceRegistration")) ) logger.error("Error unregistering a service: %s", ex) # Notify the component (even in case of error) self._ipopo_instance.safe_callback( ipopo_constants.IPOPO_CALLBACK_POST_UNREGISTRATION, self._svc_reference, ) self._registration = None self._svc_reference = None
Unregisters the provided service, if needed
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/provides.py#L332-L354
tcalmant/ipopo
pelix/utilities.py
use_service
def use_service(bundle_context, svc_reference): """ Utility context to safely use a service in a "with" block. It looks after the the given service and releases its reference when exiting the context. :param bundle_context: The calling bundle context :param svc_reference: The reference of the service to use :return: The requested service :raise BundleException: Service not found :raise TypeError: Invalid service reference """ if svc_reference is None: raise TypeError("Invalid ServiceReference") try: # Give the service yield bundle_context.get_service(svc_reference) finally: try: # Release it bundle_context.unget_service(svc_reference) except pelix.constants.BundleException: # Service might have already been unregistered pass
python
def use_service(bundle_context, svc_reference): """ Utility context to safely use a service in a "with" block. It looks after the the given service and releases its reference when exiting the context. :param bundle_context: The calling bundle context :param svc_reference: The reference of the service to use :return: The requested service :raise BundleException: Service not found :raise TypeError: Invalid service reference """ if svc_reference is None: raise TypeError("Invalid ServiceReference") try: # Give the service yield bundle_context.get_service(svc_reference) finally: try: # Release it bundle_context.unget_service(svc_reference) except pelix.constants.BundleException: # Service might have already been unregistered pass
Utility context to safely use a service in a "with" block. It looks after the the given service and releases its reference when exiting the context. :param bundle_context: The calling bundle context :param svc_reference: The reference of the service to use :return: The requested service :raise BundleException: Service not found :raise TypeError: Invalid service reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L64-L88
tcalmant/ipopo
pelix/utilities.py
SynchronizedClassMethod
def SynchronizedClassMethod(*locks_attr_names, **kwargs): # pylint: disable=C1801 """ A synchronizer decorator for class methods. An AttributeError can be raised at runtime if the given lock attribute doesn't exist or if it is None. If a parameter ``sorted`` is found in ``kwargs`` and its value is True, then the list of locks names will be sorted before locking. :param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be used for synchronization :return: The decorator method, surrounded with the lock """ # Filter the names (remove empty ones) locks_attr_names = [ lock_name for lock_name in locks_attr_names if lock_name ] if not locks_attr_names: raise ValueError("The lock names list can't be empty") if "sorted" not in kwargs or kwargs["sorted"]: # Sort the lock names if requested # (locking always in the same order reduces the risk of dead lock) locks_attr_names = list(locks_attr_names) locks_attr_names.sort() def wrapped(method): """ The wrapping method :param method: The wrapped method :return: The wrapped method :raise AttributeError: The given attribute name doesn't exist """ @functools.wraps(method) def synchronized(self, *args, **kwargs): """ Calls the wrapped method with a lock """ # Raises an AttributeError if needed locks = [getattr(self, attr_name) for attr_name in locks_attr_names] locked = collections.deque() i = 0 try: # Lock for lock in locks: if lock is None: # No lock... raise AttributeError( "Lock '{0}' can't be None in class {1}".format( locks_attr_names[i], type(self).__name__ ) ) # Get the lock i += 1 lock.acquire() locked.appendleft(lock) # Use the method return method(self, *args, **kwargs) finally: # Unlock what has been locked in all cases for lock in locked: lock.release() locked.clear() del locks[:] return synchronized # Return the wrapped method return wrapped
python
def SynchronizedClassMethod(*locks_attr_names, **kwargs): # pylint: disable=C1801 """ A synchronizer decorator for class methods. An AttributeError can be raised at runtime if the given lock attribute doesn't exist or if it is None. If a parameter ``sorted`` is found in ``kwargs`` and its value is True, then the list of locks names will be sorted before locking. :param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be used for synchronization :return: The decorator method, surrounded with the lock """ # Filter the names (remove empty ones) locks_attr_names = [ lock_name for lock_name in locks_attr_names if lock_name ] if not locks_attr_names: raise ValueError("The lock names list can't be empty") if "sorted" not in kwargs or kwargs["sorted"]: # Sort the lock names if requested # (locking always in the same order reduces the risk of dead lock) locks_attr_names = list(locks_attr_names) locks_attr_names.sort() def wrapped(method): """ The wrapping method :param method: The wrapped method :return: The wrapped method :raise AttributeError: The given attribute name doesn't exist """ @functools.wraps(method) def synchronized(self, *args, **kwargs): """ Calls the wrapped method with a lock """ # Raises an AttributeError if needed locks = [getattr(self, attr_name) for attr_name in locks_attr_names] locked = collections.deque() i = 0 try: # Lock for lock in locks: if lock is None: # No lock... raise AttributeError( "Lock '{0}' can't be None in class {1}".format( locks_attr_names[i], type(self).__name__ ) ) # Get the lock i += 1 lock.acquire() locked.appendleft(lock) # Use the method return method(self, *args, **kwargs) finally: # Unlock what has been locked in all cases for lock in locked: lock.release() locked.clear() del locks[:] return synchronized # Return the wrapped method return wrapped
A synchronizer decorator for class methods. An AttributeError can be raised at runtime if the given lock attribute doesn't exist or if it is None. If a parameter ``sorted`` is found in ``kwargs`` and its value is True, then the list of locks names will be sorted before locking. :param locks_attr_names: A list of the lock(s) attribute(s) name(s) to be used for synchronization :return: The decorator method, surrounded with the lock
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L250-L326
tcalmant/ipopo
pelix/utilities.py
is_lock
def is_lock(lock): """ Tests if the given lock is an instance of a lock class """ if lock is None: # Don't do useless tests return False for attr in "acquire", "release", "__enter__", "__exit__": if not hasattr(lock, attr): # Missing something return False # Same API as a lock return True
python
def is_lock(lock): """ Tests if the given lock is an instance of a lock class """ if lock is None: # Don't do useless tests return False for attr in "acquire", "release", "__enter__", "__exit__": if not hasattr(lock, attr): # Missing something return False # Same API as a lock return True
Tests if the given lock is an instance of a lock class
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L329-L343
tcalmant/ipopo
pelix/utilities.py
remove_duplicates
def remove_duplicates(items): """ Returns a list without duplicates, keeping elements order :param items: A list of items :return: The list without duplicates, in the same order """ if items is None: return items new_list = [] for item in items: if item not in new_list: new_list.append(item) return new_list
python
def remove_duplicates(items): """ Returns a list without duplicates, keeping elements order :param items: A list of items :return: The list without duplicates, in the same order """ if items is None: return items new_list = [] for item in items: if item not in new_list: new_list.append(item) return new_list
Returns a list without duplicates, keeping elements order :param items: A list of items :return: The list without duplicates, in the same order
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L373-L387
tcalmant/ipopo
pelix/utilities.py
add_listener
def add_listener(registry, listener): """ Adds a listener in the registry, if it is not yet in :param registry: A registry (a list) :param listener: The listener to register :return: True if the listener has been added """ if listener is None or listener in registry: return False registry.append(listener) return True
python
def add_listener(registry, listener): """ Adds a listener in the registry, if it is not yet in :param registry: A registry (a list) :param listener: The listener to register :return: True if the listener has been added """ if listener is None or listener in registry: return False registry.append(listener) return True
Adds a listener in the registry, if it is not yet in :param registry: A registry (a list) :param listener: The listener to register :return: True if the listener has been added
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L393-L405
tcalmant/ipopo
pelix/utilities.py
remove_listener
def remove_listener(registry, listener): """ Removes a listener from the registry :param registry: A registry (a list) :param listener: The listener to remove :return: True if the listener was in the list """ if listener is not None and listener in registry: registry.remove(listener) return True return False
python
def remove_listener(registry, listener): """ Removes a listener from the registry :param registry: A registry (a list) :param listener: The listener to remove :return: True if the listener was in the list """ if listener is not None and listener in registry: registry.remove(listener) return True return False
Removes a listener from the registry :param registry: A registry (a list) :param listener: The listener to remove :return: True if the listener was in the list
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L408-L420
tcalmant/ipopo
pelix/utilities.py
to_iterable
def to_iterable(value, allow_none=True): """ Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns None if value is None, else it returns an empty list :return: A list containing the given string, or the given value """ if value is None: # None given if allow_none: return None return [] elif isinstance(value, (list, tuple, set, frozenset)): # Iterable given, return it as-is return value # Return a one-value list return [value]
python
def to_iterable(value, allow_none=True): """ Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns None if value is None, else it returns an empty list :return: A list containing the given string, or the given value """ if value is None: # None given if allow_none: return None return [] elif isinstance(value, (list, tuple, set, frozenset)): # Iterable given, return it as-is return value # Return a one-value list return [value]
Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns None if value is None, else it returns an empty list :return: A list containing the given string, or the given value
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L551-L574
tcalmant/ipopo
pelix/utilities.py
Deprecated.__log
def __log(self, method_name): """ Logs the deprecation message on first call, does nothing after :param method_name: Name of the deprecated method """ if not self.__already_logged: # Print only if not already done stack = "\n\t".join(traceback.format_stack()) logging.getLogger(self.__logger).warning( "%s: %s\n%s", method_name, self.__message, stack ) self.__already_logged = True
python
def __log(self, method_name): """ Logs the deprecation message on first call, does nothing after :param method_name: Name of the deprecated method """ if not self.__already_logged: # Print only if not already done stack = "\n\t".join(traceback.format_stack()) logging.getLogger(self.__logger).warning( "%s: %s\n%s", method_name, self.__message, stack ) self.__already_logged = True
Logs the deprecation message on first call, does nothing after :param method_name: Name of the deprecated method
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L177-L190
tcalmant/ipopo
pelix/utilities.py
CountdownEvent.step
def step(self): # type: () -> bool """ Decreases the internal counter. Raises an error if the counter goes below 0 :return: True if this step was the final one, else False :raise ValueError: The counter has gone below 0 """ with self.__lock: self.__value -= 1 if self.__value == 0: # All done self.__event.set() return True elif self.__value < 0: # Gone too far raise ValueError("The counter has gone below 0") return False
python
def step(self): # type: () -> bool """ Decreases the internal counter. Raises an error if the counter goes below 0 :return: True if this step was the final one, else False :raise ValueError: The counter has gone below 0 """ with self.__lock: self.__value -= 1 if self.__value == 0: # All done self.__event.set() return True elif self.__value < 0: # Gone too far raise ValueError("The counter has gone below 0") return False
Decreases the internal counter. Raises an error if the counter goes below 0 :return: True if this step was the final one, else False :raise ValueError: The counter has gone below 0
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/utilities.py#L692-L711
tcalmant/ipopo
pelix/shell/completion/pelix.py
BundleCompleter.display_hook
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available bundle matches and the bundle name :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len) # Sort matching IDs matches = sorted(int(match) for match in matches) # Print the match and the associated name session.write_line() for bnd_id in matches: bnd = context.get_bundle(bnd_id) session.write_line(match_pattern, bnd_id, bnd.get_symbolic_name()) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
python
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available bundle matches and the bundle name :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ # Prepare a line pattern for each match match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len) # Sort matching IDs matches = sorted(int(match) for match in matches) # Print the match and the associated name session.write_line() for bnd_id in matches: bnd = context.get_bundle(bnd_id) session.write_line(match_pattern, bnd_id, bnd.get_symbolic_name()) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay()
Displays the available bundle matches and the bundle name :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/pelix.py#L71-L97
tcalmant/ipopo
pelix/shell/completion/pelix.py
BundleCompleter.complete
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of bundle IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of bundle IDs (strings) matching the current value # and not yet in arguments rl_matches = [] for bnd in context.get_bundles(): bnd_id = "{0} ".format(bnd.get_bundle_id()) if bnd_id.startswith(current): rl_matches.append(bnd_id) return rl_matches
python
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of bundle IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of bundle IDs (strings) matching the current value # and not yet in arguments rl_matches = [] for bnd in context.get_bundles(): bnd_id = "{0} ".format(bnd.get_bundle_id()) if bnd_id.startswith(current): rl_matches.append(bnd_id) return rl_matches
Returns the list of bundle IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/pelix.py#L99-L125
tcalmant/ipopo
pelix/shell/completion/pelix.py
ServiceCompleter.display_hook
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ try: # Prepare a line pattern for each match match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len) # Sort matching IDs matches = sorted(int(match) for match in matches) # Print the match and the associated name session.write_line() for svc_id in matches: svc_ref = context.get_service_reference( None, "({}={})".format(SERVICE_ID, svc_id) ) session.write_line(match_pattern, svc_id, str(svc_ref)) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay() except Exception as ex: session.write_line("\n{}\n\n", ex)
python
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match """ try: # Prepare a line pattern for each match match_pattern = "{{0: >{}}}: {{1}}".format(longest_match_len) # Sort matching IDs matches = sorted(int(match) for match in matches) # Print the match and the associated name session.write_line() for svc_id in matches: svc_ref = context.get_service_reference( None, "({}={})".format(SERVICE_ID, svc_id) ) session.write_line(match_pattern, svc_id, str(svc_ref)) # Print the prompt, then current line session.write(prompt) session.write_line_no_feed(readline.get_line_buffer()) readline.redisplay() except Exception as ex: session.write_line("\n{}\n\n", ex)
Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session (for display) :param context: BundleContext of the shell :param matches: List of words matching the substitution :param longest_match_len: Length of the largest match
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/pelix.py#L134-L165
tcalmant/ipopo
pelix/shell/completion/pelix.py
ServiceCompleter.complete
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of bundle IDs (strings) matching the current value # and not yet in arguments rl_matches = [] for svc_ref in context.get_all_service_references(None, None): svc_id = "{0} ".format(svc_ref.get_property(SERVICE_ID)) if svc_id.startswith(current): rl_matches.append(svc_id) return rl_matches
python
def complete( self, config, prompt, session, context, current_arguments, current ): # type: (CompletionInfo, str, ShellSession, BundleContext, List[str], str) -> List[str] """ Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches """ # Register a method to display helpful completion self.set_display_hook(self.display_hook, prompt, session, context) # Return a list of bundle IDs (strings) matching the current value # and not yet in arguments rl_matches = [] for svc_ref in context.get_all_service_references(None, None): svc_id = "{0} ".format(svc_ref.get_property(SERVICE_ID)) if svc_id.startswith(current): rl_matches.append(svc_id) return rl_matches
Returns the list of services IDs matching the current state :param config: Configuration of the current completion :param prompt: Shell prompt (for re-display) :param session: Shell session (to display in shell) :param context: Bundle context of the Shell bundle :param current_arguments: Current arguments (without the command itself) :param current: Current word :return: A list of matches
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/completion/pelix.py#L167-L193
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
ExportDistributionProvider.supports_export
def supports_export(self, exported_configs, service_intents, export_props): """ Method called by rsa.export_service to ask if this ExportDistributionProvider supports export for given exported_configs (list), service_intents (list), and export_props (dict). If a ExportContainer instance is returned then it is used to export the service. If None is returned, then this distribution provider will not be used to export the service. The default implementation returns self._get_or_create_container. """ return self._get_or_create_container( exported_configs, service_intents, export_props )
python
def supports_export(self, exported_configs, service_intents, export_props): """ Method called by rsa.export_service to ask if this ExportDistributionProvider supports export for given exported_configs (list), service_intents (list), and export_props (dict). If a ExportContainer instance is returned then it is used to export the service. If None is returned, then this distribution provider will not be used to export the service. The default implementation returns self._get_or_create_container. """ return self._get_or_create_container( exported_configs, service_intents, export_props )
Method called by rsa.export_service to ask if this ExportDistributionProvider supports export for given exported_configs (list), service_intents (list), and export_props (dict). If a ExportContainer instance is returned then it is used to export the service. If None is returned, then this distribution provider will not be used to export the service. The default implementation returns self._get_or_create_container.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L351-L366
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
ImportDistributionProvider.supports_import
def supports_import( self, exported_configs, service_intents, endpoint_props ): """ Method called by rsa.export_service to ask if this ImportDistributionProvider supports import for given exported_configs (list), service_intents (list), and export_props (dict). If a ImportContainer instance is returned then it is used to import the service. If None is returned, then this distribution provider will not be used to import the service. The default implementation returns self._get_or_create_container. """ return self._get_or_create_container( exported_configs, service_intents, endpoint_props )
python
def supports_import( self, exported_configs, service_intents, endpoint_props ): """ Method called by rsa.export_service to ask if this ImportDistributionProvider supports import for given exported_configs (list), service_intents (list), and export_props (dict). If a ImportContainer instance is returned then it is used to import the service. If None is returned, then this distribution provider will not be used to import the service. The default implementation returns self._get_or_create_container. """ return self._get_or_create_container( exported_configs, service_intents, endpoint_props )
Method called by rsa.export_service to ask if this ImportDistributionProvider supports import for given exported_configs (list), service_intents (list), and export_props (dict). If a ImportContainer instance is returned then it is used to import the service. If None is returned, then this distribution provider will not be used to import the service. The default implementation returns self._get_or_create_container.
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L386-L403
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
Container.is_valid
def is_valid(self): # type: () -> bool """ Checks if the component is valid :return: Always True if it doesn't raise an exception :raises AssertionError: Invalid properties """ assert self._bundle_context assert self._container_props is not None assert self._get_distribution_provider() assert self.get_config_name() assert self.get_namespace() return True
python
def is_valid(self): # type: () -> bool """ Checks if the component is valid :return: Always True if it doesn't raise an exception :raises AssertionError: Invalid properties """ assert self._bundle_context assert self._container_props is not None assert self._get_distribution_provider() assert self.get_config_name() assert self.get_namespace() return True
Checks if the component is valid :return: Always True if it doesn't raise an exception :raises AssertionError: Invalid properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L429-L442
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
Container._validate_component
def _validate_component(self, bundle_context, container_props): # type: (BundleContext, Dict[str, Any]) -> None """ Component validated :param bundle_context: Bundle context :param container_props: Instance properties :raises AssertionError: Invalid properties """ self._bundle_context = bundle_context self._container_props = container_props self.is_valid()
python
def _validate_component(self, bundle_context, container_props): # type: (BundleContext, Dict[str, Any]) -> None """ Component validated :param bundle_context: Bundle context :param container_props: Instance properties :raises AssertionError: Invalid properties """ self._bundle_context = bundle_context self._container_props = container_props self.is_valid()
Component validated :param bundle_context: Bundle context :param container_props: Instance properties :raises AssertionError: Invalid properties
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L445-L456
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
Container._add_export
def _add_export(self, ed_id, inst): # type: (str, Tuple[Any, EndpointDescription]) -> None """ Keeps track of an exported service :param ed_id: ID of the endpoint description :param inst: A tuple: (service instance, endpoint description) """ with self._exported_instances_lock: self._exported_services[ed_id] = inst
python
def _add_export(self, ed_id, inst): # type: (str, Tuple[Any, EndpointDescription]) -> None """ Keeps track of an exported service :param ed_id: ID of the endpoint description :param inst: A tuple: (service instance, endpoint description) """ with self._exported_instances_lock: self._exported_services[ed_id] = inst
Keeps track of an exported service :param ed_id: ID of the endpoint description :param inst: A tuple: (service instance, endpoint description)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L478-L487
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
Container._find_export
def _find_export(self, func): # type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]] """ Look for an export using the given lookup method The lookup method must accept a single parameter, which is a tuple containing a service instance and endpoint description. :param func: A function to look for the excepted export :return: The found tuple or None """ with self._exported_instances_lock: for val in self._exported_services.values(): if func(val): return val return None
python
def _find_export(self, func): # type: (Callable[[Tuple[Any, EndpointDescription]], bool]) -> Optional[Tuple[Any, EndpointDescription]] """ Look for an export using the given lookup method The lookup method must accept a single parameter, which is a tuple containing a service instance and endpoint description. :param func: A function to look for the excepted export :return: The found tuple or None """ with self._exported_instances_lock: for val in self._exported_services.values(): if func(val): return val return None
Look for an export using the given lookup method The lookup method must accept a single parameter, which is a tuple containing a service instance and endpoint description. :param func: A function to look for the excepted export :return: The found tuple or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L513-L529
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
ExportContainer._export_service
def _export_service(self, svc, ed): # type: (Any, EndpointDescription) -> None """ Registers a service export :param svc: Service instance :param ed: Endpoint description """ self._add_export(ed.get_id(), (svc, ed))
python
def _export_service(self, svc, ed): # type: (Any, EndpointDescription) -> None """ Registers a service export :param svc: Service instance :param ed: Endpoint description """ self._add_export(ed.get_id(), (svc, ed))
Registers a service export :param svc: Service instance :param ed: Endpoint description
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L586-L594
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
ExportContainer.prepare_endpoint_props
def prepare_endpoint_props(self, intfs, svc_ref, export_props): # type: (List[str], ServiceReference, Dict[str, Any]) -> Dict[str, Any] """ Sets up the properties of an endpoint :param intfs: Specifications to export :param svc_ref: Reference of the exported service :param export_props: Export properties :return: The properties of the endpoint """ pkg_vers = rsa.get_package_versions(intfs, export_props) exported_configs = get_string_plus_property_value( svc_ref.get_property(SERVICE_EXPORTED_CONFIGS) ) if not exported_configs: exported_configs = [self.get_config_name()] service_intents = set() svc_intents = export_props.get(SERVICE_INTENTS, None) if svc_intents: service_intents.update(svc_intents) svc_exp_intents = export_props.get(SERVICE_EXPORTED_INTENTS, None) if svc_exp_intents: service_intents.update(svc_exp_intents) svc_exp_intents_extra = export_props.get( SERVICE_EXPORTED_INTENTS_EXTRA, None ) if svc_exp_intents_extra: service_intents.update(svc_exp_intents_extra) rsa_props = rsa.get_rsa_props( intfs, exported_configs, self._get_supported_intents(), svc_ref.get_property(SERVICE_ID), export_props.get(ENDPOINT_FRAMEWORK_UUID), pkg_vers, list(service_intents), ) ecf_props = rsa.get_ecf_props( self.get_id(), self.get_namespace(), rsa.get_next_rsid(), rsa.get_current_time_millis(), ) extra_props = rsa.get_extra_props(export_props) merged = rsa.merge_dicts(rsa_props, ecf_props, extra_props) # remove service.bundleid merged.pop(SERVICE_BUNDLE_ID, None) # remove service.scope merged.pop(SERVICE_SCOPE, None) return merged
python
def prepare_endpoint_props(self, intfs, svc_ref, export_props): # type: (List[str], ServiceReference, Dict[str, Any]) -> Dict[str, Any] """ Sets up the properties of an endpoint :param intfs: Specifications to export :param svc_ref: Reference of the exported service :param export_props: Export properties :return: The properties of the endpoint """ pkg_vers = rsa.get_package_versions(intfs, export_props) exported_configs = get_string_plus_property_value( svc_ref.get_property(SERVICE_EXPORTED_CONFIGS) ) if not exported_configs: exported_configs = [self.get_config_name()] service_intents = set() svc_intents = export_props.get(SERVICE_INTENTS, None) if svc_intents: service_intents.update(svc_intents) svc_exp_intents = export_props.get(SERVICE_EXPORTED_INTENTS, None) if svc_exp_intents: service_intents.update(svc_exp_intents) svc_exp_intents_extra = export_props.get( SERVICE_EXPORTED_INTENTS_EXTRA, None ) if svc_exp_intents_extra: service_intents.update(svc_exp_intents_extra) rsa_props = rsa.get_rsa_props( intfs, exported_configs, self._get_supported_intents(), svc_ref.get_property(SERVICE_ID), export_props.get(ENDPOINT_FRAMEWORK_UUID), pkg_vers, list(service_intents), ) ecf_props = rsa.get_ecf_props( self.get_id(), self.get_namespace(), rsa.get_next_rsid(), rsa.get_current_time_millis(), ) extra_props = rsa.get_extra_props(export_props) merged = rsa.merge_dicts(rsa_props, ecf_props, extra_props) # remove service.bundleid merged.pop(SERVICE_BUNDLE_ID, None) # remove service.scope merged.pop(SERVICE_SCOPE, None) return merged
Sets up the properties of an endpoint :param intfs: Specifications to export :param svc_ref: Reference of the exported service :param export_props: Export properties :return: The properties of the endpoint
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L611-L661
tcalmant/ipopo
pelix/rsa/providers/distribution/__init__.py
ExportContainer.export_service
def export_service(self, svc_ref, export_props): # type: (ServiceReference, Dict[str, Any]) -> EndpointDescription """ Exports the given service :param svc_ref: Reference to the service to export :param export_props: Export properties :return: The endpoint description """ ed = EndpointDescription.fromprops(export_props) self._export_service( self._get_bundle_context().get_service(svc_ref), ed ) return ed
python
def export_service(self, svc_ref, export_props): # type: (ServiceReference, Dict[str, Any]) -> EndpointDescription """ Exports the given service :param svc_ref: Reference to the service to export :param export_props: Export properties :return: The endpoint description """ ed = EndpointDescription.fromprops(export_props) self._export_service( self._get_bundle_context().get_service(svc_ref), ed ) return ed
Exports the given service :param svc_ref: Reference to the service to export :param export_props: Export properties :return: The endpoint description
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/rsa/providers/distribution/__init__.py#L663-L676
tcalmant/ipopo
pelix/shell/xmpp.py
main
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Prepare arguments parser = argparse.ArgumentParser( prog="pelix.shell.xmpp", parents=[make_common_parser()], description="Pelix XMPP Shell", ) group = parser.add_argument_group("XMPP options") group.add_argument("-j", "--jid", dest="jid", help="Jabber ID") group.add_argument("--password", dest="password", help="JID password") group.add_argument("-s", "--server", dest="server", help="XMPP server host") group.add_argument( "-p", "--port", dest="port", type=int, default=5222, help="XMPP server port", ) group.add_argument( "--tls", dest="use_tls", action="store_true", help="Use a STARTTLS connection", ) group.add_argument( "--ssl", dest="use_ssl", action="store_true", help="Use an SSL connection", ) # Parse them args = parser.parse_args(argv) # Handle common arguments init = handle_common_arguments(args) # Quiet down the SleekXMPP logger if not args.verbose: logging.getLogger("sleekxmpp").setLevel(logging.WARNING) if not args.server and not args.jid: _logger.error("No JID nor server given. Abandon.") sys.exit(1) # Get the password if necessary password = args.password if args.jid and args.password is None: try: import getpass except ImportError: _logger.error( "getpass() unavailable: give a password in command line" ) else: try: password = getpass.getpass() except getpass.GetPassWarning: pass # Get the server from the JID, if necessary server = args.server if not server: server = sleekxmpp.JID(args.jid).domain # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.console", "pelix.shell.xmpp", ] bundles.extend(init.bundles) # Use the utility method to create, run and delete the framework framework = pelix.framework.create_framework( remove_duplicates(bundles), init.properties ) framework.start() # Instantiate a Remote Shell with use_ipopo(framework.get_bundle_context()) as ipopo: ipopo.instantiate( pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell", { "shell.xmpp.server": server, "shell.xmpp.port": args.port, "shell.xmpp.jid": args.jid, "shell.xmpp.password": password, "shell.xmpp.tls": args.use_tls, "shell.xmpp.ssl": args.use_ssl, }, ) # Instantiate configured components init.instantiate_components(framework.get_bundle_context()) try: framework.wait_for_stop() except KeyboardInterrupt: framework.stop()
python
def main(argv=None): """ Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None """ # Prepare arguments parser = argparse.ArgumentParser( prog="pelix.shell.xmpp", parents=[make_common_parser()], description="Pelix XMPP Shell", ) group = parser.add_argument_group("XMPP options") group.add_argument("-j", "--jid", dest="jid", help="Jabber ID") group.add_argument("--password", dest="password", help="JID password") group.add_argument("-s", "--server", dest="server", help="XMPP server host") group.add_argument( "-p", "--port", dest="port", type=int, default=5222, help="XMPP server port", ) group.add_argument( "--tls", dest="use_tls", action="store_true", help="Use a STARTTLS connection", ) group.add_argument( "--ssl", dest="use_ssl", action="store_true", help="Use an SSL connection", ) # Parse them args = parser.parse_args(argv) # Handle common arguments init = handle_common_arguments(args) # Quiet down the SleekXMPP logger if not args.verbose: logging.getLogger("sleekxmpp").setLevel(logging.WARNING) if not args.server and not args.jid: _logger.error("No JID nor server given. Abandon.") sys.exit(1) # Get the password if necessary password = args.password if args.jid and args.password is None: try: import getpass except ImportError: _logger.error( "getpass() unavailable: give a password in command line" ) else: try: password = getpass.getpass() except getpass.GetPassWarning: pass # Get the server from the JID, if necessary server = args.server if not server: server = sleekxmpp.JID(args.jid).domain # Set the initial bundles bundles = [ "pelix.ipopo.core", "pelix.shell.core", "pelix.shell.ipopo", "pelix.shell.console", "pelix.shell.xmpp", ] bundles.extend(init.bundles) # Use the utility method to create, run and delete the framework framework = pelix.framework.create_framework( remove_duplicates(bundles), init.properties ) framework.start() # Instantiate a Remote Shell with use_ipopo(framework.get_bundle_context()) as ipopo: ipopo.instantiate( pelix.shell.FACTORY_XMPP_SHELL, "xmpp-shell", { "shell.xmpp.server": server, "shell.xmpp.port": args.port, "shell.xmpp.jid": args.jid, "shell.xmpp.password": password, "shell.xmpp.tls": args.use_tls, "shell.xmpp.ssl": args.use_ssl, }, ) # Instantiate configured components init.instantiate_components(framework.get_bundle_context()) try: framework.wait_for_stop() except KeyboardInterrupt: framework.stop()
Entry point :param argv: Script arguments (None for sys.argv) :return: An exit code or None
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/xmpp.py#L364-L474
tcalmant/ipopo
pelix/shell/xmpp.py
_XmppOutStream.flush
def flush(self): """ Sends buffered data to the target """ # Flush buffer content = self._buffer.getvalue() self._buffer = StringIO() if content: # Send message self._client.send_message(self._target, content, mtype="chat")
python
def flush(self): """ Sends buffered data to the target """ # Flush buffer content = self._buffer.getvalue() self._buffer = StringIO() if content: # Send message self._client.send_message(self._target, content, mtype="chat")
Sends buffered data to the target
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/shell/xmpp.py#L114-L124
tcalmant/ipopo
pelix/internals/registry.py
_FactoryCounter._get_from_factory
def _get_from_factory(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns a service instance from a Prototype Service Factory :param factory: The prototype service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory """ svc_ref = svc_registration.get_reference() try: # Use the existing service service, counter = self.__factored[svc_ref] counter.inc() except KeyError: # Create the service service = factory.get_service(self.__bundle, svc_registration) counter = _UsageCounter() counter.inc() # Store the counter self.__factored[svc_ref] = (service, counter) return service
python
def _get_from_factory(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns a service instance from a Prototype Service Factory :param factory: The prototype service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory """ svc_ref = svc_registration.get_reference() try: # Use the existing service service, counter = self.__factored[svc_ref] counter.inc() except KeyError: # Create the service service = factory.get_service(self.__bundle, svc_registration) counter = _UsageCounter() counter.inc() # Store the counter self.__factored[svc_ref] = (service, counter) return service
Returns a service instance from a Prototype Service Factory :param factory: The prototype service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L138-L161
tcalmant/ipopo
pelix/internals/registry.py
_FactoryCounter._get_from_prototype
def _get_from_prototype(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns a service instance from a Prototype Service Factory :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory """ svc_ref = svc_registration.get_reference() service = factory.get_service(self.__bundle, svc_registration) try: # Check if the service already exists services, counter = self.__factored[svc_ref] services.append(service) counter.inc() except KeyError: counter = _UsageCounter() counter.inc() # Store the counter self.__factored[svc_ref] = ([service], counter) return service
python
def _get_from_prototype(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns a service instance from a Prototype Service Factory :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory """ svc_ref = svc_registration.get_reference() service = factory.get_service(self.__bundle, svc_registration) try: # Check if the service already exists services, counter = self.__factored[svc_ref] services.append(service) counter.inc() except KeyError: counter = _UsageCounter() counter.inc() # Store the counter self.__factored[svc_ref] = ([service], counter) return service
Returns a service instance from a Prototype Service Factory :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance returned by the factory
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L163-L187
tcalmant/ipopo
pelix/internals/registry.py
_FactoryCounter.get_service
def get_service(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns the service required by the bundle. The Service Factory is called only when necessary while the Prototype Service Factory is called each time :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance (created if necessary) """ svc_ref = svc_registration.get_reference() if svc_ref.is_prototype(): return self._get_from_prototype(factory, svc_registration) return self._get_from_factory(factory, svc_registration)
python
def get_service(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> Any """ Returns the service required by the bundle. The Service Factory is called only when necessary while the Prototype Service Factory is called each time :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance (created if necessary) """ svc_ref = svc_registration.get_reference() if svc_ref.is_prototype(): return self._get_from_prototype(factory, svc_registration) return self._get_from_factory(factory, svc_registration)
Returns the service required by the bundle. The Service Factory is called only when necessary while the Prototype Service Factory is called each time :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: The requested service instance (created if necessary)
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L189-L204
tcalmant/ipopo
pelix/internals/registry.py
_FactoryCounter.unget_service
def unget_service(self, factory, svc_registration, service=None): # type: (Any, ServiceRegistration, Any) -> bool """ Releases references to the given service reference :param factory: The service factory :param svc_registration: The ServiceRegistration object :param service: Service instance (for prototype factories) :return: True if all service references to this service factory have been released """ svc_ref = svc_registration.get_reference() try: _, counter = self.__factored[svc_ref] except KeyError: logging.warning( "Trying to release an unknown service factory: %s", svc_ref ) else: if svc_ref.is_prototype(): # Notify the factory to clean up this instance factory.unget_service_instance( self.__bundle, svc_registration, service ) if not counter.dec(): # All references have been released: clean up del self.__factored[svc_ref] # Call the factory factory.unget_service(self.__bundle, svc_registration) # No more reference to this service return True # Some references are still there return False
python
def unget_service(self, factory, svc_registration, service=None): # type: (Any, ServiceRegistration, Any) -> bool """ Releases references to the given service reference :param factory: The service factory :param svc_registration: The ServiceRegistration object :param service: Service instance (for prototype factories) :return: True if all service references to this service factory have been released """ svc_ref = svc_registration.get_reference() try: _, counter = self.__factored[svc_ref] except KeyError: logging.warning( "Trying to release an unknown service factory: %s", svc_ref ) else: if svc_ref.is_prototype(): # Notify the factory to clean up this instance factory.unget_service_instance( self.__bundle, svc_registration, service ) if not counter.dec(): # All references have been released: clean up del self.__factored[svc_ref] # Call the factory factory.unget_service(self.__bundle, svc_registration) # No more reference to this service return True # Some references are still there return False
Releases references to the given service reference :param factory: The service factory :param svc_registration: The ServiceRegistration object :param service: Service instance (for prototype factories) :return: True if all service references to this service factory have been released
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L206-L242
tcalmant/ipopo
pelix/internals/registry.py
_FactoryCounter.cleanup_service
def cleanup_service(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> bool """ If this bundle used that factory, releases the reference; else does nothing :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: True if the bundle was using the factory, else False """ svc_ref = svc_registration.get_reference() try: # "service" for factories, "services" for prototypes services, _ = self.__factored.pop(svc_ref) except KeyError: return False else: if svc_ref.is_prototype() and services: for service in services: try: factory.unget_service_instance( self.__bundle, svc_registration, service ) except Exception: # Ignore instance-level exceptions, potential errors # will reappear in unget_service() pass # Call the factory factory.unget_service(self.__bundle, svc_registration) # No more association svc_ref.unused_by(self.__bundle) return True
python
def cleanup_service(self, factory, svc_registration): # type: (Any, ServiceRegistration) -> bool """ If this bundle used that factory, releases the reference; else does nothing :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: True if the bundle was using the factory, else False """ svc_ref = svc_registration.get_reference() try: # "service" for factories, "services" for prototypes services, _ = self.__factored.pop(svc_ref) except KeyError: return False else: if svc_ref.is_prototype() and services: for service in services: try: factory.unget_service_instance( self.__bundle, svc_registration, service ) except Exception: # Ignore instance-level exceptions, potential errors # will reappear in unget_service() pass # Call the factory factory.unget_service(self.__bundle, svc_registration) # No more association svc_ref.unused_by(self.__bundle) return True
If this bundle used that factory, releases the reference; else does nothing :param factory: The service factory :param svc_registration: The ServiceRegistration object :return: True if the bundle was using the factory, else False
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L244-L277
tcalmant/ipopo
pelix/internals/registry.py
ServiceReference.unused_by
def unused_by(self, bundle): """ Indicates that this reference is not being used anymore by the given bundle. This method should only be used by the framework. :param bundle: A bundle that used this reference """ if bundle is None or bundle is self.__bundle: # Ignore return with self.__usage_lock: try: if not self.__using_bundles[bundle].dec(): # This bundle has cleaner all of its usages of this # reference del self.__using_bundles[bundle] except KeyError: # Ignore error pass
python
def unused_by(self, bundle): """ Indicates that this reference is not being used anymore by the given bundle. This method should only be used by the framework. :param bundle: A bundle that used this reference """ if bundle is None or bundle is self.__bundle: # Ignore return with self.__usage_lock: try: if not self.__using_bundles[bundle].dec(): # This bundle has cleaner all of its usages of this # reference del self.__using_bundles[bundle] except KeyError: # Ignore error pass
Indicates that this reference is not being used anymore by the given bundle. This method should only be used by the framework. :param bundle: A bundle that used this reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L454-L474
tcalmant/ipopo
pelix/internals/registry.py
ServiceReference.used_by
def used_by(self, bundle): """ Indicates that this reference is being used by the given bundle. This method should only be used by the framework. :param bundle: A bundle using this reference """ if bundle is None or bundle is self.__bundle: # Ignore return with self.__usage_lock: self.__using_bundles.setdefault(bundle, _UsageCounter()).inc()
python
def used_by(self, bundle): """ Indicates that this reference is being used by the given bundle. This method should only be used by the framework. :param bundle: A bundle using this reference """ if bundle is None or bundle is self.__bundle: # Ignore return with self.__usage_lock: self.__using_bundles.setdefault(bundle, _UsageCounter()).inc()
Indicates that this reference is being used by the given bundle. This method should only be used by the framework. :param bundle: A bundle using this reference
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L476-L488
tcalmant/ipopo
pelix/internals/registry.py
ServiceRegistration.set_properties
def set_properties(self, properties): """ Updates the service properties :param properties: The new properties :raise TypeError: The argument is not a dictionary """ if not isinstance(properties, dict): raise TypeError("Waiting for dictionary") # Keys that must not be updated for forbidden_key in OBJECTCLASS, SERVICE_ID: try: del properties[forbidden_key] except KeyError: pass to_delete = [] for key, value in properties.items(): if self.__properties.get(key) == value: # No update to_delete.append(key) for key in to_delete: # Remove unchanged properties del properties[key] if not properties: # Nothing to do return # Ensure that the service has a valid service ranking try: properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING]) except (ValueError, TypeError): # Bad value: ignore update del properties[SERVICE_RANKING] except KeyError: # Service ranking not updated: ignore pass # pylint: disable=W0212 with self.__reference._props_lock: # Update the properties previous = self.__properties.copy() self.__properties.update(properties) if self.__reference.needs_sort_update(): # The sort key and the registry must be updated self.__update_callback(self.__reference) # Trigger a new computation in the framework event = ServiceEvent( ServiceEvent.MODIFIED, self.__reference, previous ) self.__framework._dispatcher.fire_service_event(event)
python
def set_properties(self, properties): """ Updates the service properties :param properties: The new properties :raise TypeError: The argument is not a dictionary """ if not isinstance(properties, dict): raise TypeError("Waiting for dictionary") # Keys that must not be updated for forbidden_key in OBJECTCLASS, SERVICE_ID: try: del properties[forbidden_key] except KeyError: pass to_delete = [] for key, value in properties.items(): if self.__properties.get(key) == value: # No update to_delete.append(key) for key in to_delete: # Remove unchanged properties del properties[key] if not properties: # Nothing to do return # Ensure that the service has a valid service ranking try: properties[SERVICE_RANKING] = int(properties[SERVICE_RANKING]) except (ValueError, TypeError): # Bad value: ignore update del properties[SERVICE_RANKING] except KeyError: # Service ranking not updated: ignore pass # pylint: disable=W0212 with self.__reference._props_lock: # Update the properties previous = self.__properties.copy() self.__properties.update(properties) if self.__reference.needs_sort_update(): # The sort key and the registry must be updated self.__update_callback(self.__reference) # Trigger a new computation in the framework event = ServiceEvent( ServiceEvent.MODIFIED, self.__reference, previous ) self.__framework._dispatcher.fire_service_event(event)
Updates the service properties :param properties: The new properties :raise TypeError: The argument is not a dictionary
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L562-L618
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.clear
def clear(self): """ Clears the event dispatcher """ with self.__bnd_lock: self.__bnd_listeners = [] with self.__svc_lock: self.__svc_listeners.clear() with self.__fw_lock: self.__fw_listeners = []
python
def clear(self): """ Clears the event dispatcher """ with self.__bnd_lock: self.__bnd_listeners = [] with self.__svc_lock: self.__svc_listeners.clear() with self.__fw_lock: self.__fw_listeners = []
Clears the event dispatcher
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L661-L672
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.add_bundle_listener
def add_bundle_listener(self, listener): """ Adds a bundle listener :param listener: The bundle listener to register :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "bundle_changed"): raise BundleException("Invalid bundle listener given") with self.__bnd_lock: if listener in self.__bnd_listeners: self._logger.warning( "Already known bundle listener '%s'", listener ) return False self.__bnd_listeners.append(listener) return True
python
def add_bundle_listener(self, listener): """ Adds a bundle listener :param listener: The bundle listener to register :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "bundle_changed"): raise BundleException("Invalid bundle listener given") with self.__bnd_lock: if listener in self.__bnd_listeners: self._logger.warning( "Already known bundle listener '%s'", listener ) return False self.__bnd_listeners.append(listener) return True
Adds a bundle listener :param listener: The bundle listener to register :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L674-L694
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.add_framework_listener
def add_framework_listener(self, listener): """ Registers a listener that will be called back right before the framework stops. :param listener: The framework stop listener :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "framework_stopping"): raise BundleException("Invalid framework listener given") with self.__fw_lock: if listener in self.__fw_listeners: self._logger.warning( "Already known framework listener '%s'", listener ) return False self.__fw_listeners.append(listener) return True
python
def add_framework_listener(self, listener): """ Registers a listener that will be called back right before the framework stops. :param listener: The framework stop listener :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "framework_stopping"): raise BundleException("Invalid framework listener given") with self.__fw_lock: if listener in self.__fw_listeners: self._logger.warning( "Already known framework listener '%s'", listener ) return False self.__fw_listeners.append(listener) return True
Registers a listener that will be called back right before the framework stops. :param listener: The framework stop listener :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L696-L717
tcalmant/ipopo
pelix/internals/registry.py
EventDispatcher.add_service_listener
def add_service_listener( self, bundle_context, listener, specification=None, ldap_filter=None ): """ Registers a service listener :param bundle_context: The bundle_context of the service listener :param listener: The service listener :param specification: The specification that must provide the service (optional, None to accept all services) :param ldap_filter: Filter that must match the service properties (optional, None to accept all services) :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "service_changed"): raise BundleException("Invalid service listener given") with self.__svc_lock: if listener in self.__listeners_data: self._logger.warning( "Already known service listener '%s'", listener ) return False try: ldap_filter = ldapfilter.get_ldap_filter(ldap_filter) except ValueError as ex: raise BundleException("Invalid service filter: {0}".format(ex)) stored = ListenerInfo( bundle_context, listener, specification, ldap_filter ) self.__listeners_data[listener] = stored self.__svc_listeners.setdefault(specification, []).append(stored) return True
python
def add_service_listener( self, bundle_context, listener, specification=None, ldap_filter=None ): """ Registers a service listener :param bundle_context: The bundle_context of the service listener :param listener: The service listener :param specification: The specification that must provide the service (optional, None to accept all services) :param ldap_filter: Filter that must match the service properties (optional, None to accept all services) :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given """ if listener is None or not hasattr(listener, "service_changed"): raise BundleException("Invalid service listener given") with self.__svc_lock: if listener in self.__listeners_data: self._logger.warning( "Already known service listener '%s'", listener ) return False try: ldap_filter = ldapfilter.get_ldap_filter(ldap_filter) except ValueError as ex: raise BundleException("Invalid service filter: {0}".format(ex)) stored = ListenerInfo( bundle_context, listener, specification, ldap_filter ) self.__listeners_data[listener] = stored self.__svc_listeners.setdefault(specification, []).append(stored) return True
Registers a service listener :param bundle_context: The bundle_context of the service listener :param listener: The service listener :param specification: The specification that must provide the service (optional, None to accept all services) :param ldap_filter: Filter that must match the service properties (optional, None to accept all services) :return: True if the listener has been registered, False if it was already known :raise BundleException: An invalid listener has been given
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/internals/registry.py#L719-L755