def configure_client_certificate_authentication_customized_settings( props, key_file, key_store_password, key_store_url): """ For a client to use a client certificate authentication scheme, the host event broker must be properly configured for TLS/SSL connections, and Client Certificate Verification must be enabled for the particular Message VPN that the client is connecting to. On client side client certificate needs to be present in a keystore file. Args: props: key_store_password: password for the key store key_store_url: url to the key store file key_file: key file Returns: configured and connected instance of MessagingService ready to be used for messaging tasks """ try: transport_security = TLS.create() \ .with_certificate_validation(True, validate_server_name=False, trust_store_file_path=SamplerUtil.get_trusted_store_dir()) messaging_service = MessagingService.builder() \ .from_properties(props) \ .with_transport_security_strategy(transport_security) \ .with_authentication_strategy(ClientCertificateAuthentication.of(certificate_file=key_store_url, key_file=key_file, key_password=key_store_password)) \ .build(SamplerUtil.get_new_application_id()) return messaging_service.connect() except Exception as exception: print(exception) finally: messaging_service.disconnect()
def run(): """ :return: """ service = None try: service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect() print(f"Message service: {service.is_connected}") if service.is_connected: destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) message_count = 10 print( "Execute Direct Publish - String without using back pressure" ) HowToDirectMessagingHealthCheckSampler() \ .direct_message_publish_without_backpressure(service, destination_name, constants.MESSAGE_TO_SEND, message_count) buffer_capacity = 100 print("Execute Direct Publish - String using back pressure") HowToDirectMessagingHealthCheckSampler() \ .direct_message_publish_on_backpressure_reject(service, destination_name, constants.MESSAGE_TO_SEND, buffer_capacity, message_count) else: print( f'Failed to connect service with properties: {boot.broker_properties()}' ) finally: if service: service.disconnect()
def run(): try: message = constants.MESSAGE_TO_SEND messaging_service = MessagingService.builder().from_properties( boot.broker_properties()).build() messaging_service.connect() publisher = HowToPublishPersistentMessage.create_persistent_message_publisher( messaging_service) HowToConsumeMessageExclusiveVsSharedMode\ .PersistentMessageReceiverQueueAccessTypes\ .receive_from_durable_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_from_non_durable_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_from_durable_non_exclusive_queue(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .PersistentMessageReceiverQueueAccessTypes \ .receive_with_state_change_listener(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .consume_full_message_and_do_ack_using_receive_message(messaging_service, topic, publisher, message) HowToConsumeMessageExclusiveVsSharedMode \ .consume_using_message_selector(messaging_service, topic, publisher, message) finally: publisher.terminate() messaging_service.disconnect()
def connect_using_properties(retries: int, retry_interval: int): """ creates a new instance of message service, that is used to configure direct message instances from config Returns: new connection for Direct messaging Raises: PubSubPlusClientError """ service_config = dict() messaging_service = None try: service_config[ transport_layer_properties.RECONNECTION_ATTEMPTS] = retries service_config[ transport_layer_properties. RECONNECTION_ATTEMPTS_WAIT_INTERVAL] = retry_interval messaging_service = MessagingService.builder().from_properties( boot.broker_properties()).build() messaging_service.connect() return messaging_service except PubSubPlusClientError as exception: raise exception finally: if messaging_service: messaging_service.disconnect()
def run(): """ :return: """ try: service = MessagingService.builder().from_properties( boot.broker_properties()).build() result = service.connect_async().result() print(f"Message service status: {result}") if result == 0: destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) message_count = 10 print( "Execute Direct Publish - String without using back pressure" ) HowToDirectMessagingHealthCheckSampler() \ .direct_message_publish_without_backpressure(service, destination_name, constants.MESSAGE_TO_SEND, message_count) buffer_capacity = 100 print("Execute Direct Publish - String using back pressure") HowToDirectMessagingHealthCheckSampler() \ .direct_message_publish_on_backpressure_reject(service, destination_name, constants.MESSAGE_TO_SEND, buffer_capacity, message_count) finally: service.disconnect_async()
def run(): try: """method to run the sampler""" service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect() finally: service.disconnect()
def run(): service = MessagingService.builder().from_properties(boot.broker_properties()).build() service.connect_async() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT print("Execute Direct Consume - String") HowToDirectConsumeBusinessObjectSampler(). \ direct_message_consume_for_business_obj(service, consumer_subscription)
def run(): service = MessagingService.builder().from_properties(boot.broker_properties()).build() service.connect() consumer_subscription = 'request_reply/pub_sub/sampler' reply_timeout = 5000 HowToUseShareNameWithRequestReplyPattern.run_subscribers(service=service, consumer_subscription=consumer_subscription, reply_timeout=reply_timeout) service.disconnect()
def run(): """ :return: """ service = None try: service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect() print(f"Message service connected: {service.is_connected}") if service.is_connected: destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) message_count = 10 buffer_capacity = 100 print("Execute Direct Publish - String using back pressure") HowToDirectPublishWithBackPressureSampler() \ .direct_message_publish_on_backpressure_reject(service, destination_name, constants.MESSAGE_TO_SEND, buffer_capacity, message_count) print( "Execute Direct Publish - String Outbound Message with all props using back pressure" ) HowToDirectPublishWithBackPressureSampler(). \ direct_message_publish_outbound_with_all_props_on_backpressure_on_reject(service, destination_name, constants.MESSAGE_TO_SEND + "_outbound based", buffer_capacity, message_count) print( "Execute Direct Publish - String Outbound Message with all props using back pressure elastic" ) HowToDirectPublishWithBackPressureSampler() \ .direct_message_publish_outbound_with_all_props_on_backpressure_elastic(service, destination_name, constants.MESSAGE_TO_SEND + "_outbound based", message_count) print( "Execute Direct Publish - String Outbound Message with all props using back pressure wait" ) HowToDirectPublishWithBackPressureSampler() \ .direct_message_publish_outbound_with_all_props_on_backpressure_wait(service, destination_name, constants.MESSAGE_TO_SEND + str("_outbound based"), buffer_capacity, message_count) else: print( "failed to connect service with properties: {boot.broker_properties}" ) finally: if service: service.disconnect()
def run(): service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect_async() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT listener_topics = ['try-me', 'try-me1', 'try-me2', 'try-me3'] HowToAddAndRemoveSubscriptionSampler() \ .direct_message_consume_adding_subscriptions(service, consumer_subscription, listener_topics) HowToAddAndRemoveSubscriptionSampler() \ .direct_message_consume_removing_subscriptions(service, consumer_subscription, listener_topics)
def create_from_file(): """ creates a new instance of message service, that is used to configure direct message instances from properties file Returns:new connection for Direct messaging """ try: messaging_service = MessagingService.builder().from_file().build() return messaging_service.connect() finally: messaging_service.disconnect()
def when_tcp_reconnection_happens(): """method to test the listener service event""" attempt_listener = ReconnectionAttemptListenerImpl() listener = ReconnectionListenerImpl() messaging_service = MessagingService.builder().from_properties(boot.broker_properties()) \ .with_reconnection_retry_strategy(RetryStrategy.parametrized_retry(3, 3)).build(). \ add_reconnection_attempt_listener(attempt_listener). \ add_reconnection_listener(listener) messaging_service.connect() # If message disconnect occurs due to any network issue, service will automatically get connects again # Apply some logic to simulate network issue, upon message service disconnect, # this listener will notify once it is automatically connect/disconnect messaging_service.remove_reconnection_listener(listener)
def basic_compression(props, compression_range): """method for applying compression to the messaging service Args: props: broker properties compression_range: int value the compression value """ try: messaging_service = MessagingService.builder().from_properties(props) \ .with_message_compression(compression_range).build() return messaging_service.connect() finally: messaging_service.disconnect()
def create_from_environment_variables(): """ creates a new instance of message service, that is used to configure direct message instances from environment variables Returns:new connection for Direct messaging """ try: messaging_service = MessagingService.builder( ).from_environment_variables().build() return messaging_service.connect() finally: messaging_service.disconnect()
def publish_message_with_unique_service(): try: service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect_async() destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) direct_publish_service = service.create_direct_message_publisher_builder( ).build() direct_publish_service.start_async() direct_publish_service.publish(destination=destination_name, message=constants.MESSAGE_TO_SEND) finally: service.disconnect() direct_publish_service.terminate(0)
def run(): """ this method creates a messaging service connection and publishes the message """ service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect_async() destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) print("Execute Direct Publish - Generics Outbound Message") HowToDirectMessagePublishBusinessObject() \ .direct_message_publish_outbound_business_obj(service, destination_name, message_obj=MyData('some value'), converter=PopoConverter())
def tls_downgradable_to_plain_text(props): """method for validating the tls downgradable to plain text Args: props: broker properties Returns: a new connection to messaging service """ try: transport_security = TLS.create().downgradable() messaging_service = MessagingService.builder().from_properties(props) \ .with_transport_security_strategy(transport_security).build() messaging_service.connect() finally: messaging_service.disconnect()
def run(): """ :return: """ service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect_async() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT print("Execute Direct Consume - String") with ThreadPoolExecutor(max_workers=2) as e: e.submit(HowToDirectConsumeShareNameSampler.direct_message_consume, service, consumer_subscription) e.submit( HowToDirectConsumeShareNameSampler.direct_message_consume2, service, consumer_subscription)
def run(): try: message = constants.MESSAGE_TO_SEND messaging_service = MessagingService.builder().from_properties(boot.broker_properties()).build() messaging_service.connect() print(f'Message service is connected? {messaging_service.is_connected}') topic_name = constants.TOPIC_ENDPOINT_DEFAULT topic = Topic.of(topic_name) outbound_msg = messaging_service.message_builder() \ .with_application_message_id(constants.APPLICATION_MESSAGE_ID) publisher = HowToPublishPersistentMessage.create_persistent_message_publisher(messaging_service) HowToPublishPersistentMessage.publish_byte_message_non_blocking(publisher, topic, bytearray(message, _sol_constants.ENCODING_TYPE)) HowToPublishPersistentMessage.publish_string_message_non_blocking(publisher, topic, message) HowToPublishPersistentMessage.publish_typed_message_non_blocking(message_builder=outbound_msg, message_publisher=publisher, destination=topic, message=message) HowToPublishPersistentMessage \ .publish_typed_message_with_extended_message_props_non_blocking(message_builder=outbound_msg, message_publisher=publisher, destination=topic, message=message) HowToPublishPersistentMessage \ .correlate_message_on_broker_ack_with_user_context_non_blocking(message_builder=outbound_msg, message_publisher=publisher, destination=topic, message=message) HowToPublishPersistentMessage \ .publish_byte_message_blocking_waiting_for_publisher_confirmation(messaging_service=messaging_service, message_publisher=publisher, destination=topic, message=message, time_out=2000) finally: publisher.terminate() messaging_service.disconnect()
def tls_with_cipher_suites(props, cipher_suite: str): """method for validating the cipher suited with tls Args: props: broker properties cipher_suite (str): cipher suite list Returns: a new connection to messaging service """ try: transport_security = TLS.create().with_cipher_suites(cipher_suite) messaging_service = MessagingService.builder().from_properties(props) \ .with_transport_security_strategy(transport_security).build() messaging_service.connect() finally: messaging_service.disconnect()
def create_from_properties(config: dict): """ creates a new instance of message service, that is used to configure direct message instances from config Returns: new connection for Direct messaging Raises: PubSubPlusClientError """ try: messaging_service = MessagingService.builder().from_properties( config).build() return messaging_service.connect() except PubSubPlusClientError as exception: raise exception finally: messaging_service.disconnect()
def run(): try: messaging_service = MessagingService.builder().from_properties( boot.broker_properties()).build() messaging_service.connect_async() destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) buffer_capacity = 20 message_count = 50 HowToHandleServiceInterruptionAndFailures.notify_on_direct_publisher_failures( messaging_service, destination_name, constants.MESSAGE_TO_SEND, buffer_capacity, message_count) HowToHandleServiceInterruptionAndFailures.\ notify_about_service_access_unrecoverable_interruption(messaging_service, destination_name, constants.MESSAGE_TO_SEND) finally: messaging_service.disconnect_async()
def run(): """ :return: """ service = MessagingService.builder().from_properties( boot.broker_properties()).build() service.connect() consumer_subscription = constants.TOPIC_ENDPOINT_DEFAULT print("\nConsume direct message") # HowToDirectConsumeSampler().direct_message_consume(service, consumer_subscription) HowToDirectConsumeSampler().publish_and_subscribe( messaging_service=service, consumer_subscription=consumer_subscription) print("\nConsume direct message in Bytes") HowToDirectConsumeSampler().consume_direct_message_byte_payload( service, consumer_subscription) print("\nConsume direct message in string") HowToDirectConsumeSampler().consume_direct_message_string_payload( service, consumer_subscription) print( "\nConsume direct message to receive http content type and encoding from the added properties" ) HowToDirectConsumeSampler( ).consume_direct_message_published_from_rest_client( service, consumer_subscription) print( "\nConsume direct message to receive expiration value from the added properties" ) HowToDirectConsumeSampler().consume_direct_detailed_message( service, consumer_subscription) print("\nConsume direct message using receive_message in a loop") HowToDirectConsumeSampler().blocking_consume_direct_messages_in_loop( service, consumer_subscription) print( "\nConsume direct message using receive_message with timeout in a loop" ) HowToDirectConsumeSampler( ).blocking_consume_direct_messages_in_loop_with_time_out( service, consumer_subscription, receive_timeout=2000)
def tls_downgradable_to_plain_text(props, trust_store_path: str): """method for validating the tls downgradable to plain text Args: props: broker properties Returns: a new connection to messaging service """ try: transport_security = TLS.create().downgradable() \ .with_certificate_validation(ignore_expiration=True, trust_store_file_path=trust_store_path) print(props) messaging_service = MessagingService.builder().from_properties(props) \ .with_transport_security_strategy(transport_security).build() messaging_service.connect() finally: messaging_service.disconnect()
def connect_retry_interval(retry_interval): """ creates a new instance of message service, that is used to configure direct message instances from config Returns: new connection for Direct messaging Raises: PubSubPlusClientError """ try: messaging_service = MessagingService.builder().from_properties(boot.broker_properties()) \ .with_reconnection_retry_strategy(RetryStrategy.forever_retry(retry_interval)).build() messaging_service.connect() return messaging_service except PubSubPlusClientError as exception: raise exception finally: messaging_service.disconnect()
def add_listener_when_reconnection_happens(retries: int, retry_interval: int) -> 'MessagingService': """method adds a reconnection listener when an reconnection happens using the reconnection strategy Args: retries (int): the number of retries count retry_interval (int): the retry interval value Returns: the listener events """ events = list() def on_reconnection(event_p): events.append(event_p) print("current event", events) try: destination_name = Topic.of(constants.TOPIC_ENDPOINT_DEFAULT) message = constants.MESSAGE_TO_SEND number_of_message_to_send = 10 messaging_service = MessagingService.builder().from_properties(boot.broker_properties()) \ .with_reconnection_retry_strategy(RetryStrategy.parametrized_retry(retries, retry_interval)) \ .add_reconnection_listener(on_reconnection).build() messaging_service1_status_code = messaging_service.connect_async() print("messaging service status code: ", messaging_service1_status_code) for _ in range(number_of_message_to_send): publish_service = messaging_service.create_direct_message_publisher_builder().build() publish_service.publish(destination=destination_name, message=message) session_force_failure_status = messaging_service.disconnect_force() print("session force failure status: ", session_force_failure_status) for _ in range(number_of_message_to_send): publish_service = messaging_service.create_direct_message_publisher_builder().build() publish_service.publish(destination=destination_name, message=message) messaging_service.disconnect() finally: timeout = time.time() + 60 * 1 while True: if 13 in events or time.time() > timeout: break return events # MessagingService got list
def tls_with_excluded_protocols(props, excluded_protocol: TLS.SecureProtocols): """method for validating excluding tls protocols Args: props: broker properties excluded_protocol (SecuredProtocols): contains a value or a list of values of protocols to be excluded Returns: a new connection to messaging service """ try: transport_security = TLS.create().with_excluded_protocols( excluded_protocol) messaging_service = MessagingService.builder().from_properties(props) \ .with_transport_security_strategy(transport_security).build() messaging_service.connect() finally: messaging_service.disconnect()
def configure_basic_auth_credentials(props, user_name: str, password: str): """setup for basic auth using user name and password Args: props: user_name: user name password: password Returns: configured and connected instance of MessagingService ready to be used for messaging tasks """ try: messaging_service = MessagingService.builder().from_properties(props) \ .with_authentication_strategy(BasicUserNamePassword.of(user_name, password)).build() return messaging_service.connect() except Exception as exception: print(exception) finally: messaging_service.disconnect()
def create_from_properties_async_application_id(config: dict, application_id: str): """ creates a new instance of message service, that is used to configure direct message instances from config Returns:new connection for Direct messaging Raises: PubSubPlusClientError: if we didn't receive future """ try: messaging_service = MessagingService.builder().from_properties( config).build(application_id) future = messaging_service.connect_async() return future.result() except PubSubPlusClientError as exception: raise exception finally: messaging_service.disconnect_async()
def add_listener_when_reconnection_happens( retries: int, retry_interval: int) -> 'MessagingService': """method adds a reconnection listener when an reconnection happens using the reconnection strategy Args: retries (int): the number of retries count retry_interval (int): the retry interval value Returns: the listener events """ events = list() class SampleServiceReconnectionHandler(ReconnectionAttemptListener, ReconnectionListener): def __init__(self): self.events = list() def on_reconnecting(event): self.events.append(event) print( 'Got reconnection attempt event, current reconnection events {self.events}' ) def on_reconnected(self, event): self.events.append(event) print( 'Got reconnected event, current reconnection events {self.events}' ) messaging_service = MessagingService.builder().from_properties(boot.broker_properties()) \ .with_reconnection_retry_strategy(RetryStrategy.parametrized_retry(retries, retry_interval)) \ .build() event_handler = SampleServiceReconnectionHandler() try: messaging_service.add_reconnection_listener(event_handler) messaging_service.connect() # wait for reconnection here # for now ommitting this code as it requires external connection administration finally: messaging_service.disconnect() return event_handler.events # MessagingService got list