Debian Codegraph @

python/examples/server_tx.py

raw
1 #!/usr/bin/env python3
2 #
3 # Licensed to the Apache Software Foundation (ASF) under one
4 # or more contributor license agreements. See the NOTICE file
5 # distributed with this work for additional information
6 # regarding copyright ownership. The ASF licenses this file
7 # to you under the Apache License, Version 2.0 (the
8 # "License"); you may not use this file except in compliance
9 # with the License. You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing,
14 # software distributed under the License is distributed on an
15 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 # KIND, either express or implied. See the License for the
17 # specific language governing permissions and limitations
18 # under the License.
19 #
20
21 from proton import Message
22 from proton.reactor import Container
23 from proton.handlers import MessagingHandler, TransactionHandler
24
25
26 class TxRequest(TransactionHandler):
27 def __init__(self, response, sender, request_delivery):
28 super(TxRequest, self).__init__()
29 self.response = response
30 self.sender = sender
31 self.request_delivery = request_delivery
32
33 def on_transaction_declared(self, event):
34 event.transaction.send(self.sender, self.response)
35 event.transaction.accept(self.request_delivery)
36 event.transaction.commit()
37
38 def on_transaction_committed(self, event):
39 print("Request processed successfully")
40
41 def on_transaction_aborted(self, event):
42 print("Request processing aborted")
43
44
45 class TxServer(MessagingHandler):
46 def __init__(self, host, address):
47 super(TxServer, self).__init__(auto_accept=False)
48 self.host = host
49 self.address = address
50
51 def on_start(self, event):
52 self.container = event.container
53 self.conn = event.container.connect(self.host, reconnect=False)
54 self.receiver = event.container.create_receiver(self.conn, self.address)
55 self.senders = {}
56 self.relay = None
57
58 def on_message(self, event):
59 sender = self.relay
60 if not sender:
61 sender = self.senders.get(event.message.reply_to)
62 if not sender:
63 sender = self.container.create_sender(self.conn, event.message.reply_to)
64 self.senders[event.message.reply_to] = sender
65
66 response = Message(address=event.message.reply_to, body=event.message.body.upper(),
67 correlation_id=event.message.correlation_id)
68 self.container.declare_transaction(self.conn, handler=TxRequest(response, sender, event.delivery))
69
70 def on_connection_open(self, event):
71 if event.connection.remote_offered_capabilities and 'ANONYMOUS-RELAY' in event.connection.remote_offered_capabilities:
72 self.relay = self.container.create_sender(self.conn, None)
73
74
75 try:
76 Container(TxServer("localhost:5672", "examples")).run()
77 except KeyboardInterrupt:
78 pass