Debian Codegraph @

python/examples/tx_recv_interactive.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 import sys
22 import threading
23 from proton.reactor import ApplicationEvent, Container, EventInjector
24 from proton.handlers import MessagingHandler, TransactionHandler
25
26
27 class TxRecv(MessagingHandler, TransactionHandler):
28 def __init__(self):
29 super(TxRecv, self).__init__(prefetch=0, auto_accept=False)
30
31 def on_start(self, event):
32 self.container = event.container
33 self.conn = self.container.connect("localhost:5672")
34 self.receiver = self.container.create_receiver(self.conn, "examples")
35 self.container.declare_transaction(self.conn, handler=self, settle_before_discharge=True)
36 self.transaction = None
37
38 def on_message(self, event):
39 print(event.message.body)
40 self.transaction.accept(event.delivery)
41
42 def on_transaction_declared(self, event):
43 self.transaction = event.transaction
44 print("transaction declared")
45
46 def on_transaction_committed(self, event):
47 print("transaction committed")
48 self.container.declare_transaction(self.conn, handler=self)
49
50 def on_transaction_aborted(self, event):
51 print("transaction aborted")
52 self.container.declare_transaction(self.conn, handler=self)
53
54 def on_commit(self, event):
55 self.transaction.commit()
56
57 def on_abort(self, event):
58 self.transaction.abort()
59
60 def on_fetch(self, event):
61 self.receiver.flow(1)
62
63 def on_quit(self, event):
64 c = self.receiver.connection
65 self.receiver.close()
66 c.close()
67
68
69 try:
70 reactor = Container(TxRecv())
71 events = EventInjector()
72 reactor.selectable(events)
73 thread = threading.Thread(target=reactor.run)
74 thread.daemon = True
75 thread.start()
76
77 print("Enter 'fetch', 'commit' or 'abort'")
78 while True:
79 line = sys.stdin.readline()
80 if line:
81 events.trigger(ApplicationEvent(line.strip()))
82 else:
83 break
84 except KeyboardInterrupt:
85 pass