INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Calculates the request payload size
def calculate_size(name, reduction): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
Calculates the request payload size
def calculate_size(timeout, durability, transaction_type, thread_id): """ Calculates the request payload size""" data_size = 0 data_size += LONG_SIZE_IN_BYTES data_size += INT_SIZE_IN_BYTES data_size += INT_SIZE_IN_BYTES data_size += LONG_SIZE_IN_BYTES return data_size
Encode request into client_message
def encode_request(timeout, durability, transaction_type, thread_id): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(timeout, durability, transaction_type, thread_id)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_long(timeout) client_message.append_int(durability) client_message.append_int(transaction_type) client_message.append_long(thread_id) client_message.update_frame_length() return client_message
This method does nothing and will simply tell if the next ID will be larger than the given ID. You don't need to call this method on cluster restart - uniqueness is preserved thanks to the timestamp component of the ID. This method exists to make :class:`~hazelcast.proxy.FlakeIdGenerator` drop-in replacement for the deprecated :class:`~hazelcast.proxy.IdGenerator`. :param id: (int), ID to compare. :return: (bool), True if the next ID will be larger than the supplied id, False otherwise.
def init(self, id): """ This method does nothing and will simply tell if the next ID will be larger than the given ID. You don't need to call this method on cluster restart - uniqueness is preserved thanks to the timestamp component of the ID. This method exists to make :class:`~hazelcast.proxy.FlakeIdGenerator` drop-in replacement for the deprecated :class:`~hazelcast.proxy.IdGenerator`. :param id: (int), ID to compare. :return: (bool), True if the next ID will be larger than the supplied id, False otherwise. """ # Add 1 hour worth of IDs as a reserve: due to long batch validity some clients might be still getting # older IDs. 1 hour is just a safe enough value, not a real guarantee: some clients might have longer # validity. # The init method should normally be called before any client generated IDs: in this case no reserve is # needed, so we don't want to increase the reserve excessively. reserve = to_millis(TimeUnit.HOUR) << (FlakeIdGenerator._BITS_NODE_ID + FlakeIdGenerator._BITS_SEQUENCE) return self.new_id().continue_with(lambda f: f.result() >= (id + reserve))
Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id. :param initial: (long), the given id. :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0.
def init(self, initial): """ Try to initialize this IdGenerator instance with the given id. The first generated id will be 1 greater than id. :param initial: (long), the given id. :return: (bool), ``true`` if initialization succeeded, ``false`` if id is less than 0. """ if initial <= 0: return False step = initial // BLOCK_SIZE with self._lock: init = self._atomic_long.compare_and_set(0, step + 1).result() if init: self._local = step self._residue = (initial % BLOCK_SIZE) + 1 return init
Generates and returns a cluster-wide unique id. Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live. If the cluster restarts, then id generation will start from 0. :return: (long), cluster-wide new unique id.
def new_id(self): """ Generates and returns a cluster-wide unique id. Generated ids are guaranteed to be unique for the entire cluster as long as the cluster is live. If the cluster restarts, then id generation will start from 0. :return: (long), cluster-wide new unique id. """ with self._lock: curr = self._residue self._residue += 1 if self._residue >= BLOCK_SIZE: increment = self._atomic_long.get_and_increment().result() self._local = increment self._residue = 0 return self.new_id() return self._local * BLOCK_SIZE + curr
Calculates the request payload size
def calculate_size(name, id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(id) return data_size
Transactional implementation of :func:`Queue.offer(item, timeout) <hazelcast.proxy.queue.Queue.offer>` :param item: (object), the item to be added. :param timeout: (long), maximum time in seconds to wait for addition (optional). :return: (bool), ``true`` if the element was added to this queue, ``false`` otherwise.
def offer(self, item, timeout=0): """ Transactional implementation of :func:`Queue.offer(item, timeout) <hazelcast.proxy.queue.Queue.offer>` :param item: (object), the item to be added. :param timeout: (long), maximum time in seconds to wait for addition (optional). :return: (bool), ``true`` if the element was added to this queue, ``false`` otherwise. """ check_not_none(item, "item can't be none") return self._encode_invoke(transactional_queue_offer_codec, item=self._to_data(item), timeout=to_millis(timeout))
Calculates the request payload size
def calculate_size(name, service_name, target): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(service_name) data_size += calculate_size_address(target) return data_size
Calculates the request payload size
def calculate_size(name, entry_processor): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_data(entry_processor) return data_size
Transactional implementation of :func:`MultiMap.put(key, value) <hazelcast.proxy.multi_map.MultiMap.put>` :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if the size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple.
def put(self, key, value): """ Transactional implementation of :func:`MultiMap.put(key, value) <hazelcast.proxy.multi_map.MultiMap.put>` :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if the size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_multi_map_put_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`MultiMap.get(key) <hazelcast.proxy.multi_map.MultiMap.get>` :param key: (object), the key whose associated values are returned. :return: (Sequence), the collection of the values associated with the key.
def get(self, key): """ Transactional implementation of :func:`MultiMap.get(key) <hazelcast.proxy.multi_map.MultiMap.get>` :param key: (object), the key whose associated values are returned. :return: (Sequence), the collection of the values associated with the key. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_multi_map_get_codec, key=self._to_data(key))
Transactional implementation of :func:`MultiMap.remove(key, value) <hazelcast.proxy.multi_map.MultiMap.remove>` :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return:
def remove(self, key, value): """ Transactional implementation of :func:`MultiMap.remove(key, value) <hazelcast.proxy.multi_map.MultiMap.remove>` :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_multi_map_remove_entry_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`MultiMap.remove_all(key) <hazelcast.proxy.multi_map.MultiMap.remove_all>` :param key: (object), the key of the entries to remove. :return: (list), the collection of the values associated with the key.
def remove_all(self, key): """ Transactional implementation of :func:`MultiMap.remove_all(key) <hazelcast.proxy.multi_map.MultiMap.remove_all>` :param key: (object), the key of the entries to remove. :return: (list), the collection of the values associated with the key. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_multi_map_remove_codec, key=self._to_data(key))
Transactional implementation of :func:`MultiMap.value_count(key) <hazelcast.proxy.multi_map.MultiMap.value_count>` :param key: (object), the key whose number of values is to be returned. :return: (int), the number of values matching the given key in the multimap.
def value_count(self, key): """ Transactional implementation of :func:`MultiMap.value_count(key) <hazelcast.proxy.multi_map.MultiMap.value_count>` :param key: (object), the key whose number of values is to be returned. :return: (int), the number of values matching the given key in the multimap. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_multi_map_value_count_codec, key=self._to_data(key))
Calculates the request payload size
def calculate_size(name, batch_size): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
Decode response from client message
def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(base=None, increment=None, batch_size=None) parameters['base'] = client_message.read_long() parameters['increment'] = client_message.read_long() parameters['batch_size'] = client_message.read_int() return parameters
Calculates the request payload size
def calculate_size(name, expected, updated): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES if expected is not None: data_size += calculate_size_data(expected) data_size += BOOLEAN_SIZE_IN_BYTES if updated is not None: data_size += calculate_size_data(updated) return data_size
Encode request into client_message
def encode_request(name, expected, updated): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, expected, updated)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_bool(expected is None) if expected is not None: client_message.append_data(expected) client_message.append_bool(updated is None) if updated is not None: client_message.append_data(updated) client_message.update_frame_length() return client_message
Calculates the request payload size
def calculate_size(name, max_size): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES return data_size
Executes a task on the owner of the specified key. :param key: (object), the specified key. :param task: (Task), a task executed on the owner of the specified key. :return: (:class:`~hazelcast.future.Future`), future representing pending completion of the task.
def execute_on_key_owner(self, key, task): """ Executes a task on the owner of the specified key. :param key: (object), the specified key. :param task: (Task), a task executed on the owner of the specified key. :return: (:class:`~hazelcast.future.Future`), future representing pending completion of the task. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) partition_id = self._client.partition_service.get_partition_id(key_data) uuid = self._get_uuid() return self._encode_invoke_on_partition(executor_service_submit_to_partition_codec, partition_id, uuid=uuid, callable=self._to_data(task), partition_id=partition_id)
Encode request into client_message
def encode_request(name, max_size): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, max_size)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_int(max_size) client_message.update_frame_length() return client_message
Executes a task on the specified member. :param member: (Member), the specified member. :param task: (Task), the task executed on the specified member. :return: (:class:`~hazelcast.future.Future`), Future representing pending completion of the task.
def execute_on_member(self, member, task): """ Executes a task on the specified member. :param member: (Member), the specified member. :param task: (Task), the task executed on the specified member. :return: (:class:`~hazelcast.future.Future`), Future representing pending completion of the task. """ uuid = self._get_uuid() address = member.address return self._execute_on_member(address, uuid, self._to_data(task))
Executes a task on each of the specified members. :param members: (Collection), the specified members. :param task: (Task), the task executed on the specified members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member.
def execute_on_members(self, members, task): """ Executes a task on each of the specified members. :param members: (Collection), the specified members. :param task: (Task), the task executed on the specified members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ task_data = self._to_data(task) futures = [] uuid = self._get_uuid() for member in members: f = self._execute_on_member(member.address, uuid, task_data) futures.append(f) return future.combine_futures(*futures)
Executes a task on all of the known cluster members. :param task: (Task), the task executed on the all of the members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member.
def execute_on_all_members(self, task): """ Executes a task on all of the known cluster members. :param task: (Task), the task executed on the all of the members. :return: (Map), :class:`~hazelcast.future.Future` tuples representing pending completion of the task on each member. """ return self.execute_on_members(self._client.cluster.get_member_list(), task)
Calculates the request payload size
def calculate_size(name, replace_existing_values): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES return data_size
Event handler
def handle(client_message, handle_event_distributed_object=None, to_object=None): """ Event handler """ message_type = client_message.get_message_type() if message_type == EVENT_DISTRIBUTEDOBJECT and handle_event_distributed_object is not None: name = client_message.read_str() service_name = client_message.read_str() event_type = client_message.read_str() handle_event_distributed_object(name=name, service_name=service_name, event_type=event_type)
Calculates the request payload size
def calculate_size(name, entries): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES for key, val in six.iteritems(entries): data_size += calculate_size_data(key) data_size += calculate_size_data(val) return data_size
Encode request into client_message
def encode_request(name, entries): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, entries)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_int(len(entries)) for entries_item in six.iteritems(entries): client_message.append_tuple(entries_item) client_message.update_frame_length() return client_message
Add a listener object to listen for lifecycle events. :param on_lifecycle_change: (Function), function to be called when LifeCycle state is changed. :return: (str), id of the listener.
def add_listener(self, on_lifecycle_change): """ Add a listener object to listen for lifecycle events. :param on_lifecycle_change: (Function), function to be called when LifeCycle state is changed. :return: (str), id of the listener. """ id = str(uuid.uuid4()) self._listeners[id] = on_lifecycle_change return id
Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise.
def remove_listener(self, registration_id): """ Removes a lifecycle listener. :param registration_id: (str), the id of the listener to be removed. :return: (bool), ``true`` if the listener is removed successfully, ``false`` otherwise. """ try: self._listeners.pop(registration_id) return True except KeyError: return False
Called when instance's state changes. :param new_state: (Lifecycle State), the new state of the instance.
def fire_lifecycle_event(self, new_state): """ Called when instance's state changes. :param new_state: (Lifecycle State), the new state of the instance. """ if new_state == LIFECYCLE_STATE_SHUTTING_DOWN: self.is_live = False self.state = new_state self.logger.info(self._git_info + "HazelcastClient is %s", new_state, extra=self._logger_extras) for listener in list(self._listeners.values()): try: listener(new_state) except: self.logger.exception("Exception in lifecycle listener", extra=self._logger_extras)
Event handler
def handle(client_message, handle_event_item=None, to_object=None): """ Event handler """ message_type = client_message.get_message_type() if message_type == EVENT_ITEM and handle_event_item is not None: item = None if not client_message.read_bool(): item = client_message.read_data() uuid = client_message.read_str() event_type = client_message.read_int() handle_event_item(item=item, uuid=uuid, event_type=event_type)
Calculates the request payload size
def calculate_size(name, value, timeout_millis): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_data(value) data_size += LONG_SIZE_IN_BYTES return data_size
Acquires the lock. If a lease time is specified, lock will be released after this lease time. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. :param lease_time: (long), time to wait before releasing the lock (optional).
def lock(self, lease_time=-1): """ Acquires the lock. If a lease time is specified, lock will be released after this lease time. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. :param lease_time: (long), time to wait before releasing the lock (optional). """ return self._encode_invoke(lock_lock_codec, invocation_timeout=MAX_SIZE, lease_time=to_millis(lease_time), thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())
Tries to acquire the lock. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease time is provided, lock will be released after this time elapses. :param timeout: (long), maximum time in seconds to wait for the lock (optional). :param lease_time: (long), time in seconds to wait before releasing the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, ``false``.
def try_lock(self, timeout=0, lease_time=-1): """ Tries to acquire the lock. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease time is provided, lock will be released after this time elapses. :param timeout: (long), maximum time in seconds to wait for the lock (optional). :param lease_time: (long), time in seconds to wait before releasing the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, ``false``. """ return self._encode_invoke(lock_try_lock_codec, invocation_timeout=MAX_SIZE, lease=to_millis(lease_time), thread_id=thread_id(), timeout=to_millis(timeout), reference_id=self.reference_id_generator.get_and_increment())
Releases the lock.
def unlock(self): """ Releases the lock. """ return self._encode_invoke(lock_unlock_codec, thread_id=thread_id(), reference_id=self.reference_id_generator.get_and_increment())
Calculates the request payload size
def calculate_size(name, txn_id, thread_id, key, value): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(txn_id) data_size += LONG_SIZE_IN_BYTES data_size += calculate_size_data(key) data_size += calculate_size_data(value) return data_size
Calculates the request payload size
def calculate_size(name, new_value): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += BOOLEAN_SIZE_IN_BYTES if new_value is not None: data_size += calculate_size_data(new_value) return data_size
Calculates the request payload size
def calculate_size(name, key, thread_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_data(key) data_size += LONG_SIZE_IN_BYTES return data_size
Decode response from client message
def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(response=None) if not client_message.read_bool(): parameters['response'] = EntryViewCodec.decode(client_message, to_object) return parameters
Encode request into client_message
def encode_request(name, entries): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, entries)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_int(len(entries)) for key, value in six.iteritems(entries): client_message.append_data(key) client_message.append_data(value) client_message.update_frame_length() return client_message
Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all events. :param include_value: (bool), whether received event should include the value or not (optional). :param key: (object), key for filtering the events (optional). :param added_func: Function to be called when an entry is added to map (optional). :param removed_func: Function to be called when an entry is removed_func from map (optional). :param clear_all_func: Function to be called when entries are cleared from map (optional). :return: (str), a registration id which is used as a key to remove the listener.
def add_entry_listener(self, include_value=False, key=None, added_func=None, removed_func=None, clear_all_func=None): """ Adds an entry listener for this multimap. The listener will be notified for all multimap add/remove/clear-all events. :param include_value: (bool), whether received event should include the value or not (optional). :param key: (object), key for filtering the events (optional). :param added_func: Function to be called when an entry is added to map (optional). :param removed_func: Function to be called when an entry is removed_func from map (optional). :param clear_all_func: Function to be called when entries are cleared from map (optional). :return: (str), a registration id which is used as a key to remove the listener. """ if key: key_data = self._to_data(key) request = multi_map_add_entry_listener_to_key_codec.encode_request(name=self.name, key=key_data, include_value=include_value, local_only=False) else: request = multi_map_add_entry_listener_codec.encode_request(name=self.name, include_value=include_value, local_only=False) def handle_event_entry(**_kwargs): event = EntryEvent(self._to_object, **_kwargs) if event.event_type == EntryEventType.added and added_func: added_func(event) elif event.event_type == EntryEventType.removed and removed_func: removed_func(event) elif event.event_type == EntryEventType.clear_all and clear_all_func: clear_all_func(event) return self._start_listening(request, lambda m: multi_map_add_entry_listener_codec.handle(m, handle_event_entry), lambda r: multi_map_add_entry_listener_codec.decode_response(r)[ 'response'])
Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ``true`` if this multimap contains an entry for the specified key.
def contains_key(self, key): """ Determines whether this multimap contains an entry with the key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the specified key. :return: (bool), ``true`` if this multimap contains an entry for the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_contains_key_codec, key_data, key=key_data, thread_id=thread_id())
Determines whether this map contains one or more keys for the specified value. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains an entry for the specified value.
def contains_value(self, value): """ Determines whether this map contains one or more keys for the specified value. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains an entry for the specified value. """ check_not_none(value, "value can't be None") value_data = self._to_data(value) return self._encode_invoke(multi_map_contains_value_codec, value=value_data)
Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple.
def contains_entry(self, key, value): """ Returns whether the multimap contains an entry with the value. :param key: (object), the specified key. :param value: (object), the specified value. :return: (bool), ``true`` if this multimap contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_contains_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** **Warning-2: The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and vice-versa.** :param key: (object), the specified key. :return: (Sequence), the list of the values associated with the specified key.
def get(self, key): """ Returns the list of values associated with the key. ``None`` if this map does not contain this key. **Warning: This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode and equals defined in the key's class.** **Warning-2: The list is NOT backed by the multimap, so changes to the map are list reflected in the collection, and vice-versa.** :param key: (object), the specified key. :return: (Sequence), the list of the values associated with the specified key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_get_codec, key_data, key=key_data, thread_id=thread_id())
Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key that is checked for lock. :return: (bool), ``true`` if lock is acquired, false otherwise.
def is_locked(self, key): """ Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key that is checked for lock. :return: (bool), ``true`` if lock is acquired, false otherwise. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_is_locked_codec, key_data, key=key_data)
Acquires the lock for the specified key infinitely or for the specified lease time if provided. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. Scope of the lock is this map only. Acquired lock is only for the key in this map. Locks are re-entrant; so, if the key is locked N times, it should be unlocked N times before another thread can acquire it. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to lock. :param lease_time: (int), time in seconds to wait before releasing the lock (optional).
def lock(self, key, lease_time=-1): """ Acquires the lock for the specified key infinitely or for the specified lease time if provided. If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired. Scope of the lock is this map only. Acquired lock is only for the key in this map. Locks are re-entrant; so, if the key is locked N times, it should be unlocked N times before another thread can acquire it. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to lock. :param lease_time: (int), time in seconds to wait before releasing the lock (optional). """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_lock_codec, key_data, key=key_data, thread_id=thread_id(), ttl=to_millis(lease_time), reference_id=self.reference_id_generator.get_and_increment())
Removes the given key-value tuple from the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: (bool), ``true`` if the size of the multimap changed after the remove operation, ``false`` otherwise.
def remove(self, key, value): """ Removes the given key-value tuple from the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key of the entry to remove. :param value: (object), the value of the entry to remove. :return: (bool), ``true`` if the size of the multimap changed after the remove operation, ``false`` otherwise. """ check_not_none(key, "key can't be None") check_not_none(key, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_remove_entry_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
Removes all the entries with the given key and returns the value list associated with this key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** **Warning-2: The returned list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param key: (object), the key of the entries to remove. :return: (Sequence), the collection of removed values associated with the given key.
def remove_all(self, key): """ Removes all the entries with the given key and returns the value list associated with this key. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** **Warning-2: The returned list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.** :param key: (object), the key of the entries to remove. :return: (Sequence), the collection of removed values associated with the given key. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_remove_codec, key_data, key=key_data, thread_id=thread_id())
Stores a key-value tuple in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple.
def put(self, key, value): """ Stores a key-value tuple in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key to be stored. :param value: (object), the value to be stored. :return: (bool), ``true`` if size of the multimap is increased, ``false`` if the multimap already contains the key-value tuple. """ check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") key_data = self._to_data(key) value_data = self._to_data(value) return self._encode_invoke_on_key(multi_map_put_codec, key_data, key=key_data, value=value_data, thread_id=thread_id())
Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise.
def remove_entry_listener(self, registration_id): """ Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise. """ return self._stop_listening(registration_id, lambda i: multi_map_remove_entry_listener_codec.encode_request(self.name, i))
Returns the number of values that match the given key in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key whose values count is to be returned. :return: (int), the number of values that match the given key in the multimap.
def value_count(self, key): """ Returns the number of values that match the given key in the multimap. **Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations of __hash__ and __eq__ defined in key's class.** :param key: (object), the key whose values count is to be returned. :return: (int), the number of values that match the given key in the multimap. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_value_count_codec, key_data, key=key_data, thread_id=thread_id())
Tries to acquire the lock for the specified key. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease_time is provided, lock will be released after this time elapses. :param key: (object), key to lock in this map. :param lease_time: (int), time in seconds to wait before releasing the lock (optional). :param timeout: (int), maximum time in seconds to wait for the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, false.
def try_lock(self, key, lease_time=-1, timeout=-1): """ Tries to acquire the lock for the specified key. When the lock is not available, * If timeout is not provided, the current thread doesn't wait and returns ``false`` immediately. * If a timeout is provided, the current thread becomes disabled for thread scheduling purposes and lies dormant until one of the followings happens: * the lock is acquired by the current thread, or * the specified waiting time elapses. If lease_time is provided, lock will be released after this time elapses. :param key: (object), key to lock in this map. :param lease_time: (int), time in seconds to wait before releasing the lock (optional). :param timeout: (int), maximum time in seconds to wait for the lock (optional). :return: (bool), ``true`` if the lock was acquired and otherwise, false. """ check_not_none(key, "key can't be None") key_data = self._to_data(key) return self._encode_invoke_on_key(multi_map_try_lock_codec, key_data, key=key_data, thread_id=thread_id(), lease=to_millis(lease_time), timeout=to_millis(timeout), reference_id=self.reference_id_generator.get_and_increment())
Calculates the request payload size
def calculate_size(name, values): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES for values_item in values: data_size += calculate_size_data(values_item) return data_size
Encode request into client_message
def encode_request(name, values): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, values)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_int(len(values)) for values_item in values: client_message.append_data(values_item) client_message.update_frame_length() return client_message
Transactional implementation of :func:`Map.contains_key(key) <hazelcast.proxy.map.Map.contains_key>` :param key: (object), the specified key. :return: (bool), ``true`` if this map contains an entry for the specified key, ``false`` otherwise.
def contains_key(self, key): """ Transactional implementation of :func:`Map.contains_key(key) <hazelcast.proxy.map.Map.contains_key>` :param key: (object), the specified key. :return: (bool), ``true`` if this map contains an entry for the specified key, ``false`` otherwise. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_contains_key_codec, key=self._to_data(key))
Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>` :param key: (object), the specified key. :return: (object), the value for the specified key.
def get(self, key): """ Transactional implementation of :func:`Map.get(key) <hazelcast.proxy.map.Map.get>` :param key: (object), the specified key. :return: (object), the value for the specified key. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_get_codec, key=self._to_data(key))
Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at the end of the transaction (either commit or rollback). :param key: (object), the specified key. :return: (object), the value for the specified key. .. seealso:: :func:`Map.get(key) <hazelcast.proxy.map.Map.get>`
def get_for_update(self, key): """ Locks the key and then gets and returns the value to which the specified key is mapped. Lock will be released at the end of the transaction (either commit or rollback). :param key: (object), the specified key. :return: (object), the value for the specified key. .. seealso:: :func:`Map.get(key) <hazelcast.proxy.map.Map.get>` """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_get_for_update_codec, key=self._to_data(key))
Transactional implementation of :func:`Map.put(key, value, ttl) <hazelcast.proxy.map.Map.put>` The object to be put will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param value: (object), the value to associate with the key. :param ttl: (int), maximum time in seconds for this entry to stay (optional). :return: (object), previous value associated with key or ``None`` if there was no mapping for key.
def put(self, key, value, ttl=-1): """ Transactional implementation of :func:`Map.put(key, value, ttl) <hazelcast.proxy.map.Map.put>` The object to be put will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param value: (object), the value to associate with the key. :param ttl: (int), maximum time in seconds for this entry to stay (optional). :return: (object), previous value associated with key or ``None`` if there was no mapping for key. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_map_put_codec, key=self._to_data(key), value=self._to_data(value), ttl=to_millis(ttl))
Transactional implementation of :func:`Map.put_if_absent(key, value) <hazelcast.proxy.map.Map.put_if_absent>` The object to be put will be accessible only in the current transaction context till the transaction is committed. :param key: (object), key of the entry. :param value: (object), value of the entry. :param ttl: (int), maximum time in seconds for this entry to stay in the map (optional). :return: (object), old value of the entry.
def put_if_absent(self, key, value): """ Transactional implementation of :func:`Map.put_if_absent(key, value) <hazelcast.proxy.map.Map.put_if_absent>` The object to be put will be accessible only in the current transaction context till the transaction is committed. :param key: (object), key of the entry. :param value: (object), value of the entry. :param ttl: (int), maximum time in seconds for this entry to stay in the map (optional). :return: (object), old value of the entry. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_map_put_if_absent_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`Map.set(key, value) <hazelcast.proxy.map.Map.set>` The object to be set will be accessible only in the current transaction context till the transaction is committed. :param key: (object), key of the entry. :param value: (object), value of the entry.
def set(self, key, value): """ Transactional implementation of :func:`Map.set(key, value) <hazelcast.proxy.map.Map.set>` The object to be set will be accessible only in the current transaction context till the transaction is committed. :param key: (object), key of the entry. :param value: (object), value of the entry. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_map_set_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`Map.replace(key, value) <hazelcast.proxy.map.Map.replace>` The object to be replaced will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param value: (object), the value to replace the previous value. :return: (object), previous value associated with key, or ``None`` if there was no mapping for key.
def replace(self, key, value): """ Transactional implementation of :func:`Map.replace(key, value) <hazelcast.proxy.map.Map.replace>` The object to be replaced will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param value: (object), the value to replace the previous value. :return: (object), previous value associated with key, or ``None`` if there was no mapping for key. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_map_replace_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`Map.replace_if_same(key, old_value, new_value) <hazelcast.proxy.map.Map.replace_if_same>` The object to be replaced will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param old_value: (object), replace the key value if it is the old value. :param new_value: (object), the new value to replace the old value. :return: (bool), ``true`` if the value was replaced, ``false`` otherwise.
def replace_if_same(self, key, old_value, new_value): """ Transactional implementation of :func:`Map.replace_if_same(key, old_value, new_value) <hazelcast.proxy.map.Map.replace_if_same>` The object to be replaced will be accessible only in the current transaction context till the transaction is committed. :param key: (object), the specified key. :param old_value: (object), replace the key value if it is the old value. :param new_value: (object), the new value to replace the old value. :return: (bool), ``true`` if the value was replaced, ``false`` otherwise. """ check_not_none(key, "key can't be none") check_not_none(old_value, "old_value can't be none") check_not_none(new_value, "new_value can't be none") return self._encode_invoke(transactional_map_replace_if_same_codec, key=self._to_data(key), old_value=self._to_data(old_value), new_value=self._to_data(new_value))
Transactional implementation of :func:`Map.remove(key) <hazelcast.proxy.map.Map.remove>` The object to be removed will be removed from only the current transaction context until the transaction is committed. :param key: (object), key of the mapping to be deleted. :return: (object), the previous value associated with key, or ``None`` if there was no mapping for key.
def remove(self, key): """ Transactional implementation of :func:`Map.remove(key) <hazelcast.proxy.map.Map.remove>` The object to be removed will be removed from only the current transaction context until the transaction is committed. :param key: (object), key of the mapping to be deleted. :return: (object), the previous value associated with key, or ``None`` if there was no mapping for key. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_remove_codec, key=self._to_data(key))
Transactional implementation of :func:`Map.remove_if_same(key, value) <hazelcast.proxy.map.Map.remove_if_same>` The object to be removed will be removed from only the current transaction context until the transaction is committed. :param key: (object), the specified key. :param value: (object), remove the key if it has this value. :return: (bool), ``true`` if the value was removed, ``false`` otherwise.
def remove_if_same(self, key, value): """ Transactional implementation of :func:`Map.remove_if_same(key, value) <hazelcast.proxy.map.Map.remove_if_same>` The object to be removed will be removed from only the current transaction context until the transaction is committed. :param key: (object), the specified key. :param value: (object), remove the key if it has this value. :return: (bool), ``true`` if the value was removed, ``false`` otherwise. """ check_not_none(key, "key can't be none") check_not_none(value, "value can't be none") return self._encode_invoke(transactional_map_remove_if_same_codec, key=self._to_data(key), value=self._to_data(value))
Transactional implementation of :func:`Map.delete(key) <hazelcast.proxy.map.Map.delete>` The object to be deleted will be removed from only the current transaction context until the transaction is committed. :param key: (object), key of the mapping to be deleted.
def delete(self, key): """ Transactional implementation of :func:`Map.delete(key) <hazelcast.proxy.map.Map.delete>` The object to be deleted will be removed from only the current transaction context until the transaction is committed. :param key: (object), key of the mapping to be deleted. """ check_not_none(key, "key can't be none") return self._encode_invoke(transactional_map_delete_codec, key=self._to_data(key))
Transactional implementation of :func:`Map.key_set(predicate) <hazelcast.proxy.map.Map.key_set>` :param predicate: (Predicate), predicate to filter the entries (optional). :return: (Sequence), a list of the clone of the keys. .. seealso:: :class:`~hazelcast.serialization.predicate.Predicate` for more info about predicates.
def key_set(self, predicate=None): """ Transactional implementation of :func:`Map.key_set(predicate) <hazelcast.proxy.map.Map.key_set>` :param predicate: (Predicate), predicate to filter the entries (optional). :return: (Sequence), a list of the clone of the keys. .. seealso:: :class:`~hazelcast.serialization.predicate.Predicate` for more info about predicates. """ if predicate: return self._encode_invoke(transactional_map_key_set_with_predicate_codec, predicate=self._to_data(predicate)) return self._encode_invoke(transactional_map_key_set_codec)
Transactional implementation of :func:`Map.values(predicate) <hazelcast.proxy.map.Map.values>` :param predicate: (Predicate), predicate to filter the entries (optional). :return: (Sequence), a list of clone of the values contained in this map. .. seealso:: :class:`~hazelcast.serialization.predicate.Predicate` for more info about predicates.
def values(self, predicate=None): """ Transactional implementation of :func:`Map.values(predicate) <hazelcast.proxy.map.Map.values>` :param predicate: (Predicate), predicate to filter the entries (optional). :return: (Sequence), a list of clone of the values contained in this map. .. seealso:: :class:`~hazelcast.serialization.predicate.Predicate` for more info about predicates. """ if predicate: return self._encode_invoke(transactional_map_values_with_predicate_codec, predicate=self._to_data(predicate)) return self._encode_invoke(transactional_map_values_codec)
Alters the currently stored reference by applying a function on it. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation.
def alter(self, function): """ Alters the currently stored reference by applying a function on it. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_codec, function=self._to_data(function))
Applies a function on the value, the actual stored value will not change. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the result of the function application.
def apply(self, function): """ Applies a function on the value, the actual stored value will not change. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the result of the function application. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_apply_codec, function=self._to_data(function))
Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the new value, the result of the applied function.
def alter_and_get(self, function): """ Alters the currently stored reference by applying a function on it and gets the result. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the new value, the result of the applied function. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_alter_and_get_codec, function=self._to_data(function))
Atomically sets the value to the given updated value only if the current value == the expected value. :param expected: (object), the expected value. :param updated: (object), the new value. :return: (bool), ``true`` if successful; or ``false`` if the actual value was not equal to the expected value.
def compare_and_set(self, expected, updated): """ Atomically sets the value to the given updated value only if the current value == the expected value. :param expected: (object), the expected value. :param updated: (object), the new value. :return: (bool), ``true`` if successful; or ``false`` if the actual value was not equal to the expected value. """ return self._encode_invoke(atomic_reference_compare_and_set_codec, expected=self._to_data(expected), updated=self._to_data(updated))
Checks if the reference contains the value. :param expected: (object), the value to check (is allowed to be ``None``). :return: (bool), ``true`` if the value is found, ``false`` otherwise.
def contains(self, expected): """ Checks if the reference contains the value. :param expected: (object), the value to check (is allowed to be ``None``). :return: (bool), ``true`` if the value is found, ``false`` otherwise. """ return self._encode_invoke(atomic_reference_contains_codec, expected=self._to_data(expected))
Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the old value, the value before the function is applied.
def get_and_alter(self, function): """ Alters the currently stored reference by applying a function on it on and gets the old value. :param function: (Function), A stateful serializable object which represents the Function defined on server side. This object must have a serializable Function counter part registered on server side with the actual ``org.hazelcast.core.IFunction`` implementation. :return: (object), the old value, the value before the function is applied. """ check_not_none(function, "function can't be None") return self._encode_invoke(atomic_reference_get_and_alter_codec, function=self._to_data(function))
Gets the old value and sets the new value. :param new_value: (object), the new value. :return: (object), the old value.
def get_and_set(self, new_value): """ Gets the old value and sets the new value. :param new_value: (object), the new value. :return: (object), the old value. """ return self._encode_invoke(atomic_reference_get_and_set_codec, new_value=self._to_data(new_value))
Atomically sets the given value. :param new_value: (object), the new value.
def set(self, new_value): """ Atomically sets the given value. :param new_value: (object), the new value. """ return self._encode_invoke(atomic_reference_set_codec, new_value=self._to_data(new_value))
Sets and gets the value. :param new_value: (object), the new value. :return: (object), the new value.
def set_and_get(self, new_value): """ Sets and gets the value. :param new_value: (object), the new value. :return: (object), the new value. """ return self._encode_invoke(atomic_reference_set_and_get_codec, new_value=self._to_data(new_value))
Calculates the request payload size
def calculate_size(name, uuid, callable, address): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(uuid) data_size += calculate_size_data(callable) data_size += calculate_size_address(address) return data_size
Encode request into client_message
def encode_request(name, uuid, callable, address): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, uuid, callable, address)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_str(uuid) client_message.append_data(callable) AddressCodec.encode(client_message, address) client_message.update_frame_length() return client_message
Calculates the request payload size
def calculate_size(name, registration_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(registration_id) return data_size
Returns serialization type of binary form. :return: Serialization type of binary form.
def get_type(self): """ Returns serialization type of binary form. :return: Serialization type of binary form. """ if self.total_size() == 0: return CONSTANT_TYPE_NULL return unpack_from(FMT_BE_INT, self._buffer, TYPE_OFFSET)[0]
Returns partition hash calculated for serialized object. Partition hash is used to determine partition of a Data and is calculated using * PartitioningStrategy during serialization. * If partition hash is not set then hash_code() is used. :return: partition hash
def get_partition_hash(self): """ Returns partition hash calculated for serialized object. Partition hash is used to determine partition of a Data and is calculated using * PartitioningStrategy during serialization. * If partition hash is not set then hash_code() is used. :return: partition hash """ if self.has_partition_hash(): return unpack_from(FMT_BE_INT, self._buffer, PARTITION_HASH_OFFSET)[0] return self.hash_code()
Determines whether this Data has partition hash or not. :return: (bool), ``true`` if Data has partition hash, ``false`` otherwise.
def has_partition_hash(self): """ Determines whether this Data has partition hash or not. :return: (bool), ``true`` if Data has partition hash, ``false`` otherwise. """ return self._buffer is not None \ and len(self._buffer) >= HEAP_DATA_OVERHEAD \ and unpack_from(FMT_BE_INT, self._buffer, PARTITION_HASH_OFFSET)[0] != 0
Calculates the request payload size
def calculate_size(name, overflow_policy, value): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += INT_SIZE_IN_BYTES data_size += calculate_size_data(value) return data_size
Decode response from client message
def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(response=None) parameters['response'] = client_message.read_long() return parameters
Serialize the input object into byte array representation :param obj: input object :param partitioning_strategy: function in the form of lambda key:partitioning_key :return: Data object
def to_data(self, obj, partitioning_strategy=None): """ Serialize the input object into byte array representation :param obj: input object :param partitioning_strategy: function in the form of lambda key:partitioning_key :return: Data object """ if obj is None: return None if isinstance(obj, Data): return obj out = self._create_data_output() try: serializer = self._registry.serializer_for(obj) partitioning_hash = self._calculate_partitioning_hash(obj, partitioning_strategy) out.write_int_big_endian(partitioning_hash) out.write_int_big_endian(serializer.get_type_id()) serializer.write(out, obj) return Data(out.to_byte_array()) except: handle_exception(sys.exc_info()[1], sys.exc_info()[2]) finally: pass
Deserialize input data :param data: serialized input Data object :return: Deserialized object
def to_object(self, data): """ Deserialize input data :param data: serialized input Data object :return: Deserialized object """ if not isinstance(data, Data): return data if is_null_data(data): return None inp = self._create_data_input(data) try: type_id = data.get_type() serializer = self._registry.serializer_by_type_id(type_id) if serializer is None: if self._active: raise HazelcastSerializationError("Missing Serializer for type-id:{}".format(type_id)) else: raise HazelcastInstanceNotActiveError() return serializer.read(inp) except: handle_exception(sys.exc_info()[1], sys.exc_info()[2]) finally: pass
Find and return the serializer for the type-id :param type_id: type-id the serializer :return: the serializer
def serializer_by_type_id(self, type_id): """ Find and return the serializer for the type-id :param type_id: type-id the serializer :return: the serializer """ if type_id <= 0: indx = index_for_default_type(type_id) serializer = self._constant_type_ids.get(indx, None) if serializer is not None: return serializer return self._id_dic.get(type_id, None)
Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered by user 4-pickle serialization as a fallback :param obj: input object :return: Serializer
def serializer_for(self, obj): """ Searches for a serializer for the provided object Serializers will be searched in this order; 1-NULL serializer 2-Default serializers, like primitives, arrays, string and some default types 3-Custom registered types by user 4-Global serializer if registered by user 4-pickle serialization as a fallback :param obj: input object :return: Serializer """ # 1-NULL serializer if obj is None: return self._null_serializer obj_type = type(obj) # 2-Default serializers, Dataserializable, Portable, primitives, arrays, String and some helper types(BigInteger etc) serializer = self.lookup_default_serializer(obj_type, obj) # 3-Custom registered types by user if serializer is None: serializer = self.lookup_custom_serializer(obj_type) # 5-Global serializer if registered by user if serializer is None: serializer = self.lookup_global_serializer(obj_type) # 4 Internal serializer if serializer is None: serializer = self.lookup_python_serializer(obj_type) if serializer is None: raise HazelcastSerializationError("There is no suitable serializer for:" + str(obj_type)) return serializer
Determines whether this record is expired or not. :param max_idle_seconds: (long), the maximum idle time of record, maximum time after the last access time. :return: (bool), ``true`` is this record is not expired.
def is_expired(self, max_idle_seconds): """ Determines whether this record is expired or not. :param max_idle_seconds: (long), the maximum idle time of record, maximum time after the last access time. :return: (bool), ``true`` is this record is not expired. """ now = current_time() return (self.expiration_time is not None and self.expiration_time < now) or \ (max_idle_seconds is not None and self.last_access_time + max_idle_seconds < now)
Returns the statistics of the NearCache. :return: (Dict), Dictionary that stores statistics related to this near cache.
def get_statistics(self): """ Returns the statistics of the NearCache. :return: (Dict), Dictionary that stores statistics related to this near cache. """ stats = { "creation_time": self._creation_time_in_seconds, "evictions": self._evictions, "expirations": self._expirations, "misses": self._misses, "hits": self._hits, "invalidations": self._invalidations, "invalidation_requests": self._invalidation_requests, "owned_entry_count": self.__len__(), "owned_entry_memory_cost": getsizeof(self), } return stats
Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination.
def combine_futures(*futures): """ Combines set of Futures. :param futures: (Futures), Futures to be combined. :return: Result of the combination. """ expected = len(futures) results = [] completed = AtomicInteger() combined = Future() def done(f): if not combined.done(): if f.is_success(): # TODO: ensure ordering of results as original list results.append(f.result()) if completed.get_and_increment() + 1 == expected: combined.set_result(results) else: combined.set_exception(f.exception(), f.traceback()) for future in futures: future.add_done_callback(done) return combined
Sets the result of the Future. :param result: Result of the Future.
def set_result(self, result): """ Sets the result of the Future. :param result: Result of the Future. """ if result is None: self._result = NONE_RESULT else: self._result = result self._event.set() self._invoke_callbacks()
Sets the exception for this Future in case of errors. :param exception: (Exception), exception to be threw in case of error. :param traceback: (Function), function to be called on traceback (optional).
def set_exception(self, exception, traceback=None): """ Sets the exception for this Future in case of errors. :param exception: (Exception), exception to be threw in case of error. :param traceback: (Function), function to be called on traceback (optional). """ if not isinstance(exception, BaseException): raise RuntimeError("Exception must be of BaseException type") self._exception = exception self._traceback = traceback self._event.set() self._invoke_callbacks()
Returns the result of the Future, which makes the call synchronous if the result has not been computed yet. :return: Result of the Future.
def result(self): """ Returns the result of the Future, which makes the call synchronous if the result has not been computed yet. :return: Result of the Future. """ self._reactor_check() self._event.wait() if self._exception: six.reraise(self._exception.__class__, self._exception, self._traceback) if self._result == NONE_RESULT: return None else: return self._result
Create a continuation that executes when the Future is completed. :param continuation_func: A function which takes the future as the only parameter. Return value of the function will be set as the result of the continuation future. :return: A new Future which will be completed when the continuation is done.
def continue_with(self, continuation_func, *args): """ Create a continuation that executes when the Future is completed. :param continuation_func: A function which takes the future as the only parameter. Return value of the function will be set as the result of the continuation future. :return: A new Future which will be completed when the continuation is done. """ future = Future() def callback(f): try: future.set_result(continuation_func(f, *args)) except: future.set_exception(sys.exc_info()[1], sys.exc_info()[2]) self.add_done_callback(callback) return future
Gets the existing connection for a given address. If it does not exist, the system will try to connect asynchronously. In this case, it returns a Future. When the connection is established at some point in time, it can be retrieved by using the get_connection(:class:`~hazelcast.core.Address`) or from Future. :param address: (:class:`~hazelcast.core.Address`), the address to connect to. :param authenticator: (Function), function to be used for authentication (optional). :return: (:class:`~hazelcast.connection.Connection`), the existing connection or it returns a Future which includes asynchronously.
def get_or_connect(self, address, authenticator=None): """ Gets the existing connection for a given address. If it does not exist, the system will try to connect asynchronously. In this case, it returns a Future. When the connection is established at some point in time, it can be retrieved by using the get_connection(:class:`~hazelcast.core.Address`) or from Future. :param address: (:class:`~hazelcast.core.Address`), the address to connect to. :param authenticator: (Function), function to be used for authentication (optional). :return: (:class:`~hazelcast.connection.Connection`), the existing connection or it returns a Future which includes asynchronously. """ if address in self.connections: return ImmediateFuture(self.connections[address]) else: with self._new_connection_mutex: if address in self._pending_connections: return self._pending_connections[address] else: authenticator = authenticator or self._cluster_authenticator try: translated_address = self._address_translator.translate(address) if translated_address is None: raise ValueError("Address translator could not translate address: {}".format(address)) connection = self._new_connection_func(translated_address, self._client.config.network_config.connection_timeout, self._client.config.network_config.socket_options, connection_closed_callback=self._connection_closed, message_callback=self._client.invoker._handle_client_message, network_config=self._client.config.network_config) except IOError: return ImmediateExceptionFuture(sys.exc_info()[1], sys.exc_info()[2]) future = authenticator(connection).continue_with(self.on_auth, connection, address) if not future.done(): self._pending_connections[address] = future return future
Checks for authentication of a connection. :param f: (:class:`~hazelcast.future.Future`), future that contains the result of authentication. :param connection: (:class:`~hazelcast.connection.Connection`), newly established connection. :param address: (:class:`~hazelcast.core.Address`), the adress of new connection. :return: Result of authentication.
def on_auth(self, f, connection, address): """ Checks for authentication of a connection. :param f: (:class:`~hazelcast.future.Future`), future that contains the result of authentication. :param connection: (:class:`~hazelcast.connection.Connection`), newly established connection. :param address: (:class:`~hazelcast.core.Address`), the adress of new connection. :return: Result of authentication. """ if f.is_success(): self.logger.info("Authenticated with %s", f.result(), extra=self._logger_extras) with self._new_connection_mutex: self.connections[connection.endpoint] = f.result() try: self._pending_connections.pop(address) except KeyError: pass for on_connection_opened, _ in self._connection_listeners: if on_connection_opened: on_connection_opened(f.result()) return f.result() else: self.logger.debug("Error opening %s", connection, extra=self._logger_extras) with self._new_connection_mutex: try: self._pending_connections.pop(address) except KeyError: pass six.reraise(f.exception().__class__, f.exception(), f.traceback())