[90] | 1 | import threading
|
---|
| 2 | from typing import TypeVar, List, cast, Optional
|
---|
| 3 |
|
---|
| 4 | from tudelft.utilities.listener.Listener import Listener
|
---|
| 5 | from tudelft_utilities_logging.ReportToLogger import ReportToLogger
|
---|
| 6 | from tudelft_utilities_logging.Reporter import Reporter
|
---|
| 7 |
|
---|
| 8 | from geniusweb.actions.Action import Action
|
---|
| 9 | from geniusweb.connection.ConnectionEnd import ConnectionEnd
|
---|
| 10 | from geniusweb.inform.Inform import Inform
|
---|
| 11 | from geniusweb.party.Party import Party
|
---|
| 12 |
|
---|
| 13 |
|
---|
| 14 |
|
---|
| 15 | class DefaultParty (Party, Listener[Inform]):
|
---|
| 16 | '''
|
---|
| 17 | Party with default implementation to handle the connection.
|
---|
| 18 | '''
|
---|
| 19 |
|
---|
| 20 | def __init__(self, reporter:Reporter=None):
|
---|
| 21 | '''
|
---|
| 22 | @param reporter the reporter to use. Generated automatically if None
|
---|
| 23 | '''
|
---|
| 24 | if not reporter:
|
---|
| 25 | reporter = ReportToLogger(self.__class__.__name__)
|
---|
| 26 | if not isinstance(reporter, Reporter):
|
---|
| 27 | raise ValueError("reporter must be instance of reporter, got "+str(reporter))
|
---|
| 28 | self._reporter=reporter
|
---|
| 29 | self._connection: Optional[ConnectionEnd[Inform,Action]] = None
|
---|
| 30 | self._lock = threading.Lock()
|
---|
| 31 |
|
---|
| 32 | def connect(self, connection: ConnectionEnd[Inform, Action] ):
|
---|
| 33 | try:
|
---|
| 34 | self._lock.acquire()
|
---|
| 35 | if self._connection:
|
---|
| 36 | raise ValueError("Already connected")
|
---|
| 37 | self._connection = connection
|
---|
| 38 | self._connection.addListener(self)
|
---|
| 39 | finally:
|
---|
| 40 | self._lock.release()
|
---|
| 41 |
|
---|
| 42 | #Override
|
---|
| 43 | def disconnect(self):
|
---|
| 44 | self._lock.acquire()
|
---|
| 45 | if self._connection:
|
---|
| 46 | self._connection.removeListener(self)
|
---|
| 47 | self._connection.close()
|
---|
| 48 | self._connection = None #type:ignore
|
---|
| 49 | self._lock.release()
|
---|
| 50 |
|
---|
| 51 |
|
---|
| 52 | #Override
|
---|
| 53 | def terminate(self):
|
---|
| 54 | self.disconnect();
|
---|
| 55 |
|
---|
| 56 |
|
---|
| 57 | def getConnection(self) -> Optional[ConnectionEnd[Inform, Action]]:
|
---|
| 58 | '''
|
---|
| 59 | @return currently available connection, or null if not currently
|
---|
| 60 | connected.
|
---|
| 61 | '''
|
---|
| 62 | return self._connection;
|
---|
| 63 |
|
---|
| 64 |
|
---|
| 65 | def getReporter(self)->Reporter:
|
---|
| 66 | return self._reporter;
|
---|
| 67 |
|
---|