def direct_message_consume_adding_subscriptions(
            messaging_service: MessagingService, consumer_subscription: str,
            listener_topics: list):
        """ to publish str or byte array type message
            Args:
                messaging_service: connected messaging service
                consumer_subscription: Each topic subscribed
                listener_topics: list of topics subscribed to
        """
        try:
            global MAX_SLEEP
            topics = [TopicSubscription.of(consumer_subscription)]

            direct_receive_service = messaging_service.create_direct_message_receiver_builder(
            )
            direct_receive_service = direct_receive_service.with_subscriptions(
                topics).build()
            direct_receive_service.start()
            direct_receive_service.receive_async(MessageHandlerImpl1())
            for topic in listener_topics:
                direct_receive_service.add_subscription(
                    TopicSubscription.of(topic))

            print(f"Subscribed to: {consumer_subscription}")
            time.sleep(MAX_SLEEP)
        finally:
            direct_receive_service.terminate()
    def direct_message_consume_adding_subscriptions(
            messaging_service: MessagingService, consumer_subscription: str,
            listener_topics: list):
        """ to publish str or byte array type message"""
        try:
            topics = [TopicSubscription.of(consumer_subscription)]

            direct_receive_service = messaging_service.create_direct_message_receiver_builder(
            )
            direct_receive_service = direct_receive_service.with_subscriptions(
                topics).build()
            direct_receive_service.start()
            direct_receive_service.receive_async(MessageHandlerImpl1())
            for topic in listener_topics:
                direct_receive_service.add_subscription(
                    TopicSubscription.of(topic))

            print(f"Subscribed to: {consumer_subscription}")
            while True:
                global MAX_SLEEP
                if MAX_SLEEP <= 0:
                    break
                else:
                    MAX_SLEEP -= 1
                    time.sleep(1)
        finally:
            direct_receive_service.terminate(0)
    def consume_direct_message_published_from_rest_client(
            service: MessagingService, consumer_subscription: str):
        """To consume direct message payload with content type and content encoding using receive_message()"""
        try:
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
                .with_subscriptions(topics).build()
            receiver.start()

            with ThreadPoolExecutor(max_workers=1) as e:
                e.submit(HowToDirectPublishMessage.
                         direct_message_publish_outbound_with_all_props,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)

            message_payload: 'InboundMessage' = receiver.receive_message()

            rest_specific_fields = message_payload.get_rest_interoperability_support(
            )
            content_type = rest_specific_fields.get_http_content_type()
            content_encoding = rest_specific_fields.get_http_content_encoding()
            print(
                f"received message content type is :{content_type} \n content encoding is : {content_encoding}"
            )
        finally:
            receiver.terminate()
    def direct_message_consume(messaging_service: MessagingService,
                               consumer_subscription: str):
        """ to publish str or byte array type message"""
        try:
            global MAX_SLEEP
            topics = [TopicSubscription.of(consumer_subscription)]

            direct_receive_service = messaging_service.create_direct_message_receiver_builder(
            )
            direct_receive_service = direct_receive_service.with_subscriptions(
                topics).build()
            direct_receive_service.start()
            direct_receive_service.receive_async(MessageHandlerImpl())
            remaining_time = MAX_SLEEP
            print(f"Subscribed to: {consumer_subscription}")
            time.sleep(MAX_SLEEP)
        finally:
            api_metrics = HowToAccessApiMetrics()
            api_metrics.access_individual_api_metrics(
                messaging_service, Metric.TOTAL_MESSAGES_RECEIVED)
            api_metrics.to_string_api_metrics(messaging_service)

            api_metrics.reset_api_metrics(messaging_service)

            direct_receive_service.terminate()
    def consume_full_message_and_do_ack_using_receive_message(
            messaging_service, topic, publisher, message):
        """method to consume persistent message and do ack at later time using receive_message"""
        queue_name = constants.QUEUE_NAME_FORMAT.substitute(
            iteration=topic_name)
        try:
            HowToConsumeMessageExclusiveVsSharedMode.create_queue_and_add_topic(
                queue_name)
            queue = Queue.durable_exclusive_queue(queue_name)

            receiver = messaging_service.create_persistent_message_receiver_builder() \
                .build(queue)
            receiver.start()
            receiver.add_subscription(TopicSubscription.of(topic_name))
            with ThreadPoolExecutor(max_workers=1) as e:
                time.sleep(2)
                e.submit(
                    HowToPublishPersistentMessage.
                    publish_string_message_non_blocking, publisher, topic,
                    message)
            message_received: 'InboundMessage' = receiver.receive_message(
                timeout=DEFAULT_TIMEOUT)

            receiver.ack(message_received)
            print(
                f"received message: {message_received.get_payload_as_string()}"
            )
        finally:
            receiver.terminate(0)
            HowToConsumeMessageExclusiveVsSharedMode.delete_queue(
                queue_name=queue_name)
 def blocking_consume_direct_messages_in_loop_with_time_out(
         service: MessagingService, consumer_subscription: str,
         receive_timeout):
     try:
         topics = [TopicSubscription.of(consumer_subscription)]
         receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
             .with_subscriptions(topics).build()
         receiver.start()
         count = 0
         for count in range(100):
             try:
                 with ThreadPoolExecutor(max_workers=1) as e:
                     e.submit(
                         HowToDirectPublishMessage.direct_message_publish,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)
                 message_payload: 'InboundMessage' = receiver.receive_message(
                     receive_timeout)
                 print(
                     f"message_payload in string: {message_payload.get_payload_as_string()}, msg_count: {count}"
                 )
             except PubSubPlusClientError as exception:
                 raise exception
     finally:
         receiver.terminate()
 def create_persistent_message_receiver(messaging_service, queue):
     """method to create, build and start the persistent message receiver"""
     receiver = messaging_service.create_persistent_message_receiver_builder(
     ).build(queue)
     receiver.start()
     print(
         f'PERSISTENT receiver started... Listening to Queue [{queue.get_name()}]'
     )
     receiver.add_subscription(TopicSubscription.of(topic_name))
     return receiver
Exemplo n.º 8
0
    def consume_full_message_and_do_ack(service: MessagingService, queue_to_consume: Queue, publisher, message):
        receiver: PersistentMessageReceiver = service.create_persistent_message_receiver_builder() \
            .with_message_auto_acknowledgement().build(queue_to_consume)
        receiver.start()
        print(f'PERSISTENT receiver started... Listening to Queue [{queue_to_consume.get_name()}]')
        receiver.add_subscription(TopicSubscription.of(topic_name))

        HowToPublishPersistentMessage.publish_string_message_non_blocking(publisher, topic, message)

        message: InboundMessage = receiver.receive_message()
        print(f"the message payload is {message.get_payload_as_string()}")
 def create_persistent_message_receiver_with_activation_passivation_support(
         messaging_service, queue, passivation_activation_listener):
     """method to create persistent message receiver with the activation and passivation support"""
     receiver = messaging_service.create_persistent_message_receiver_builder() \
         .with_activation_passivation_support(receiver_state_change_listener=passivation_activation_listener) \
         .build(queue)
     receiver.start()
     print(
         f'PERSISTENT receiver started with activation passivation support... '
         f'Listening to Queue [{queue.get_name()}]')
     receiver.add_subscription(TopicSubscription.of(topic_name))
     return receiver
Exemplo n.º 10
0
    def consume_full_message_using_callback_and_do_ack(service: MessagingService, queue_to_consume: Queue,
                                                       publisher, message):
        try:
            receiver: PersistentMessageReceiver = service.create_persistent_message_receiver_builder() \
                .with_message_auto_acknowledgement().build(queue_to_consume)
            receiver.start()
            print(f'PERSISTENT receiver started... Listening to Queue [{queue_to_consume.get_name()}]')
            receiver.add_subscription(TopicSubscription.of(topic_name))
            message_handler = BasicTestMessageHandler()
            receiver.receive_async(message_handler)

            HowToPublishPersistentMessage.publish_string_message_non_blocking(publisher, topic, message)
        finally:
            receiver.terminate()
            HowToConsumeMessageExclusiveVsSharedMode.delete_queue(queue_to_consume.get_name())
 def consume_direct_message_byte_payload(service: MessagingService,
                                         consumer_subscription: str):
     """To consume direct message payload in bytes using receive_message()"""
     try:
         topics = [TopicSubscription.of(consumer_subscription)]
         receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
             .with_subscriptions(topics).build()
         receiver.start()
         with ThreadPoolExecutor(max_workers=1) as e:
             e.submit(HowToDirectPublishMessage.direct_message_publish,
                      messaging_service=service,
                      destination=Topic.of(consumer_subscription),
                      message=constants.MESSAGE_TO_SEND)
         message_payload = receiver.receive_message().get_payload_as_bytes()
         print(f"received message payload in bytes is : {message_payload}")
     finally:
         receiver.terminate()
Exemplo n.º 12
0
 def direct_message_consume2(messaging_service: MessagingService,
                             consumer_subscription: str):
     """This method will create an receiver instance to receive str or byte array type message"""
     try:
         global MAX_SLEEP
         topics = [TopicSubscription.of(consumer_subscription)]
         group_name = ShareName.of('test')
         direct_receive_service = messaging_service.create_direct_message_receiver_builder(
         )
         direct_receive_service = direct_receive_service.with_subscriptions(
             topics).build(shared_subscription_group=group_name)
         direct_receive_service.start()
         direct_receive_service.receive_async(MessageHandlerImpl2())
         print(f"Subscribed to: {consumer_subscription}")
         time.sleep(MAX_SLEEP)
     finally:
         direct_receive_service.terminate()
         messaging_service.disconnect()
    def direct_message_consume_for_business_obj(
            messaging_service: MessagingService, consumer_subscription: str):
        """ to publish str or byte array type message"""
        try:
            global MAX_SLEEP
            topics = [TopicSubscription.of(consumer_subscription)]

            direct_receive_service = messaging_service.create_direct_message_receiver_builder(
            )
            direct_receive_service = direct_receive_service.with_subscriptions(
                topics).build()
            direct_receive_service.start()
            direct_receive_service.receive_async(MessageHandlerImpl())
            print(f"Subscribed to: {consumer_subscription}")
            time.sleep(MAX_SLEEP)
        finally:
            direct_receive_service.terminate()
            messaging_service.disconnect()
    def consume_using_message_selector(messaging_service, topic, publisher,
                                       message):
        """method to consume persistent message and do ack at later time using receive_message"""
        try:
            queue_name = constants.QUEUE_NAME_FORMAT.substitute(
                iteration=topic_name)
            HowToConsumeMessageExclusiveVsSharedMode.create_queue_and_add_topic(
                queue_name)
            durable_non_exclusive_queue = Queue.durable_non_exclusive_queue(
                queue_name)

            msg_selector_expression = "JMSCorrelationID = '1' and JMSPriority = 1"

            receiver = messaging_service.create_persistent_message_receiver_builder() \
                .with_message_selector(msg_selector_expression) \
                .build(durable_non_exclusive_queue)

            receiver.start()
            receiver.add_subscription(TopicSubscription.of(topic_name))
            outbound_msg = messaging_service.message_builder() \
                .with_application_message_id(constants.APPLICATION_MESSAGE_ID) \
                .with_priority(constants.MESSAGE_PRIORITY) \
                .with_expiration(constants.MESSAGE_EXPIRATION)

            additional_message_properties = {CORRELATION_ID: '1', PRIORITY: 1}
            with ThreadPoolExecutor(max_workers=1) as e:
                time.sleep(3)
                e.submit(
                    HowToPublishPersistentMessage.
                    publish_typed_message_with_extended_message_props_non_blocking,
                    outbound_msg, publisher, topic, message,
                    additional_message_properties)

            message_received: 'InboundMessage' = receiver.receive_message(
                timeout=DEFAULT_TIMEOUT)

            receiver.ack(message_received)
            print(
                f"received message: {message_received.get_payload_as_string()}"
            )
        finally:
            receiver.terminate(0)
            HowToConsumeMessageExclusiveVsSharedMode.delete_queue(
                queue_name=queue_name)
    def request_reply_message_consume2(messaging_service: MessagingService, consumer_subscription: str,
                                       reply_timeout: int):
        """This method will create an receiver instance to receive str or byte array type message"""
        try:
            global MAX_SLEEP
            topic_subscription = TopicSubscription.of(consumer_subscription)
            group_name = ShareName.of('test')

            receiver = messaging_service.request_reply(). \
                create_request_reply_message_receiver_builder().build(request_topic_subscription=topic_subscription,
                                                                      share_name=group_name)
            receiver.start()
            msg, replier = receiver.receive_message(timeout=reply_timeout)
            print(f"incoming message is {msg.get_payload_as_string()}")
            if replier is not None:
                outbound_msg = messaging_service.message_builder().build("pong reply")
                replier.reply(outbound_msg)
            print(f"Subscribed to: {consumer_subscription}")
            time.sleep(MAX_SLEEP)
        finally:
            receiver.terminate()
    def run():
        messaging_service = None
        try:
            reply_timeout = 10000
            topic_name = f'request_reply/pub_sub/sampler'
            topic = Topic.of(topic_name)
            topic_subscription = TopicSubscription.of(topic_name)
            messaging_service = MessagingService.builder().from_properties(SamplerBoot().broker_properties()).build()
            messaging_service.connect()

            HowToUseRequestReplyPattern.async_request_and_response(service=messaging_service,
                                                                   request_destination=topic,
                                                                   for_requests=topic_subscription,
                                                                   reply_timeout=reply_timeout)

            HowToUseRequestReplyPattern.blocking_request_and_response(service=messaging_service,
                                                                      request_destination=topic,
                                                                      for_requests=topic_subscription,
                                                                      reply_timeout=reply_timeout)
        finally:
            if messaging_service:
                messaging_service.disconnect()
    def consume_direct_detailed_message(service: MessagingService,
                                        consumer_subscription: str):
        try:
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = service.create_direct_message_receiver_builder()\
                .with_subscriptions(topics).build()
            receiver.start()

            with ThreadPoolExecutor(max_workers=1) as e:
                e.submit(HowToDirectPublishMessage.
                         direct_message_publish_outbound_with_all_props,
                         messaging_service=service,
                         destination=Topic.of(consumer_subscription),
                         message=constants.MESSAGE_TO_SEND)

            message_payload: 'InboundMessage' = receiver.receive_message()
            expiration = message_payload.get_expiration()
            print(
                f"received message payload is :{message_payload.get_payload_as_string()} "
                f"\n expiration is : {expiration}")
        finally:
            receiver.terminate()
Exemplo n.º 18
0
def direct_message_consume(messaging_service: MessagingService,
                           topic_subscription: str):
    try:
        trace.set_tracer_provider(TracerProvider())
        jaeger_exporter = jaeger.JaegerSpanExporter(
            service_name="<Solace> REST Messaging call to Security Co",
            agent_host_name="localhost",
            agent_port=6831,
        )

        trace.get_tracer_provider().add_span_processor(
            BatchExportSpanProcessor(jaeger_exporter))

        tracer = trace.get_tracer(__name__)

        topics = [TopicSubscription.of(topic_subscription)]

        # Create a direct message consumer service with the topic subscription and start it
        direct_receive_service = messaging_service.create_direct_message_receiver_builder(
        )
        direct_receive_service = direct_receive_service.with_subscriptions(
            topics).build()
        direct_receive_service.start()

        # Register a callback message handler
        direct_receive_service.receive_async(MessageHandlerImpl())
        print(f"Subscribed to: {topic_subscription}")
        # Infinite loop until Keyboard interrupt is received
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print('\nDisconnecting Messaging Service')
    finally:
        messaging_service.disconnect()
        direct_receive_service.terminate()
direct_publisher.set_publish_failure_listener(PublisherErrorHandling())
direct_publisher.set_publisher_readiness_listener

# Blocking Start thread
direct_publisher.start()
# print(f'Direct Publisher ready? {direct_publisher.is_ready()}')

unique_name = ""
while not unique_name:
    unique_name = input("Enter your name: ").replace(" ", "")

# Define a Topic subscriptions
topics = [TOPIC_PREFIX + "/python/>", TOPIC_PREFIX + "/control/>"]
topics_sub = []
for t in topics:
    topics_sub.append(TopicSubscription.of(t))

msgSeqNum = 0
# Prepare outbound message payload and body
message_body = f'Hello from Python Hellow World Sample!'
outbound_msg = messaging_service.message_builder() \
                .with_application_message_id("sample_id") \
                .with_property("application", "samples") \
                .with_property("language", "Python") \
                .build(message_body)
try:
    print(f"Subscribed to: {topics}")
    # Build a Receiver
    direct_receiver = messaging_service.create_direct_message_receiver_builder(
    ).with_subscriptions(topics_sub).build()
    direct_receiver.start()
    def consume_just_SDTMapStream_payload(messaging_service,
                                          consumer_subscription):
        """ to consume message"""
        print("consume here testing")
        try:
            # Create a direct message publisher and start it
            direct_publisher = messaging_service.create_direct_message_publisher_builder(
            ).build()
            # Blocking Start thread
            direct_publisher.start()
            print("messaging_service in consumer : ", messaging_service)
            topics = [TopicSubscription.of(consumer_subscription)]
            receiver: DirectMessageReceiver = messaging_service.create_direct_message_receiver_builder() \
                .with_subscriptions(topics).build()
            print("Receiver started...")
            receiver.start()

            # Callback for received messages
            receiver.receive_async(MessageHandlerImpl())
            MESSAGE_TO_SEND = [
                [1, 'c', None,
                 bytearray(b'1'), {
                     'a': 2
                 }, True, 5.5],
                ({
                    "key1": 1,
                    "key2": 2
                }, {
                    "key1": 'value1',
                    "key2": 2
                }, {
                    "key1": tuple(["John", "Doe", "Alice"])
                }), {
                    "key1": 'value1',
                    "key2": True,
                    "key3": {
                        "key31": None,
                        "key32": {
                            "5": 6,
                            "7": {
                                "8": 9
                            }
                        }
                    },
                    "key4": [1.1, None, 3, {
                        "key42": [1, 2, 3]
                    }],
                    "key5": bytearray([0x13, 0x11, 0x10, 0x09, 0x08, 0x01]),
                    "key6": '',
                    "key7": (1, 2, 3)
                }, {
                    "1": 2,
                    "3": {
                        "5": 6,
                        "7": {
                            "8": 9
                        },
                        "11": {
                            "a": "b",
                            "c": [1, 2, 3]
                        }
                    }
                }, 'hello everyone'
            ]
            tasks = []
            with ThreadPoolExecutor() as executor:
                for message in MESSAGE_TO_SEND:
                    future = executor.submit(
                        HowToWorkWithSolaceSDTTypesAndMessages.publish_SDTMap,
                        messaging_service=messaging_service,
                        destination=Topic.of(consumer_subscription),
                        message=message)
                    tasks.append(future)
                # can wait of tasks or wait for for first task using concurrent.futures methods
            # on context exit all pending tasks in the executor must complete
        finally:
            print("Terminating receiver")
            receiver.terminate()