modelverse.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. import urllib
  2. import urllib2
  3. import json
  4. import random
  5. from urllib2 import URLError
  6. import sys
  7. # Bind to the compiler (might have to update path manually!)
  8. sys.path.append("interface/HUTN")
  9. from hutn_compiler.compiler import main as do_compile
  10. # Helper functions and configuration: do not use yourself!
  11. taskname = random.random()
  12. address = None
  13. last_output = None
  14. mode = 0
  15. def _input(value):
  16. # Ugly json encoding of primitives
  17. if isinstance(value, type([])):
  18. value = json.dumps(value)
  19. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": taskname}))).read()
  20. else:
  21. value = json.dumps(value)
  22. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  23. print("Set input: " + str(value))
  24. def _input_raw(value, taskname):
  25. # Ugly json encoding of primitives
  26. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  27. def _compile_AL(code):
  28. # Compile an action language file and send the compiled code
  29. code_fragments = code.split("\n")
  30. code_fragments = [i for i in code_fragments if i.strip() != ""]
  31. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  32. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  33. code_fragments = [i[initial_tabs:] for i in code_fragments]
  34. code_fragments.append("")
  35. code = "\n".join(code_fragments)
  36. with open("__constraint.alc", "w") as f:
  37. f.write(code)
  38. f.flush()
  39. return do_compile("__constraint.alc", "interface/HUTN/grammars/actionlanguage.g", "CS")
  40. def _compile_model(code):
  41. # Compile a model and send the compiled graph
  42. # First change multiple spaces to a tab
  43. code_fragments = code.split("\n")
  44. code_fragments = [i for i in code_fragments if i.strip() != ""]
  45. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  46. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  47. code_fragments = [i[initial_tabs:] for i in code_fragments]
  48. code_fragments.append("")
  49. code = "\n".join(code_fragments)
  50. with open("__model.mvc", "w") as f:
  51. f.write(code)
  52. f.flush()
  53. return do_compile("__model.mvc", "interface/HUTN/grammars/modelling.g", "M") + ["exit"]
  54. def _output(expected=None):
  55. try:
  56. global last_output
  57. last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read())
  58. print("Got output: " + str(last_output))
  59. except:
  60. raise UnknownError()
  61. if expected is not None and last_output != expected:
  62. raise InterfaceMismatch(_last_output(), expected)
  63. return last_output
  64. def _last_output():
  65. return last_output
  66. # Exceptions
  67. class ModelverseException(Exception):
  68. pass
  69. class UnknownException(ModelverseException):
  70. pass
  71. class UnknownIdentifier(ModelverseException):
  72. pass
  73. class UnknownType(ModelverseException):
  74. pass
  75. class NotAnAssociation(ModelverseException):
  76. pass
  77. class UnsupportedValue(ModelverseException):
  78. pass
  79. class CompilationError(ModelverseException):
  80. pass
  81. class NoSuchAttribute(ModelverseException):
  82. pass
  83. class UnknownModel(ModelverseException):
  84. pass
  85. class ConnectionError(ModelverseException):
  86. pass
  87. class ModelExists(ModelverseException):
  88. pass
  89. class PermissionDenied(ModelverseException):
  90. pass
  91. class InvalidMode(ModelverseException):
  92. pass
  93. class InterfaceMismatch(ModelverseException):
  94. pass
  95. # Main MvC operations
  96. def init(address_param="http://localhost:8001"):
  97. """Starts up the connection to the Modelverse."""
  98. # return None
  99. # raises ConnectionError
  100. # raises UnknownError
  101. # raises InvalidMode
  102. global mode
  103. if mode != 0:
  104. raise InvalidMode()
  105. global address
  106. address = address_param
  107. try:
  108. _input_raw('"%s"' % taskname, "task_manager")
  109. mode = 1
  110. except URLError as e:
  111. raise ConnectionError(e.reason)
  112. def login(username, password):
  113. """Log in a user, if user doesn't exist, it is created."""
  114. # return None
  115. # raises UnknownError
  116. # raises PermissionDenied
  117. # raises InterfaceMismatch
  118. global mode
  119. if mode != 1:
  120. raise InvalidMode()
  121. _output("Log on as which user?")
  122. _input(username)
  123. if _output() == "User password?":
  124. _input(password)
  125. if _output() == "Welcome to the Model Management Interface v2.0!":
  126. _output("Use the 'help' command for a list of possible commands")
  127. _output("Ready for command...")
  128. mode = 2
  129. elif _last_output() == "Wrong password!":
  130. raise PermissionDenied()
  131. else:
  132. raise InterfaceMismatch(_last_output())
  133. elif _last_output() == "This is a new user: please give password!":
  134. _input(password)
  135. _output("Please repeat the password")
  136. _input(password)
  137. if _output() == "Passwords match!":
  138. _output("Welcome to the Model Management Interface v2.0!")
  139. _output("Use the 'help' command for a list of possible commands")
  140. _output("Ready for command...")
  141. mode = 2
  142. elif _last_output() == "Not the same password!":
  143. # We just sent the same password, so it should be identical, unless the interface changed
  144. raise InterfaceMismatch(_last_output())
  145. else:
  146. raise InterfaceMismatch(_last_output())
  147. else:
  148. raise InterfaceMismatch(_last_output())
  149. def model_add(model_name, metamodel_name, model_code=None):
  150. """Instantiate a new model."""
  151. # return None
  152. # raises UnknownModel
  153. # raises ModelExists
  154. # raises UnknownError
  155. # raises PermissionDenied
  156. # raises CompilationError
  157. if mode != 2:
  158. raise InvalidMode()
  159. # Do this before creating the model, as otherwise compilation errors would make us inconsistent
  160. if model_code is not None:
  161. try:
  162. compiled = _compile_model(model_code)
  163. except:
  164. raise CompilationError()
  165. else:
  166. compiled = ["exit"]
  167. _input("model_add")
  168. _output("Creating new model!")
  169. _output("Model type?")
  170. _input(metamodel_name)
  171. if _output() == "Model name?":
  172. _input(model_name)
  173. if _output() == "Waiting for model constructors...":
  174. _input(compiled)
  175. _output("Model upload success!")
  176. _output("Ready for command...")
  177. elif _last_output() == "Model with that name already exists!":
  178. _output("Ready for command...")
  179. raise ModelExists()
  180. else:
  181. raise InterfaceMismatch(_last_output())
  182. elif _last_output().startswith("Could not find type model"):
  183. _output("Ready for command...")
  184. raise UnknownModel()
  185. elif _last_output() == "Permission denied":
  186. _output("Ready for command...")
  187. raise PermissionDenied()
  188. def model_modify(model_name):
  189. """Modify an existing model."""
  190. # return is_write
  191. # raises UnknownModel
  192. # raises PermissionDenied
  193. # raises UnknownError
  194. global mode
  195. if mode != 2:
  196. raise InvalidMode()
  197. _input("model_modify")
  198. _output("Which model do you want to modify?")
  199. _input(model_name)
  200. if _output() == "Permission denied":
  201. _output("Ready for command...")
  202. raise PermissionDenied()
  203. elif _last_output() == "Could not find model!":
  204. _output("Ready for command...")
  205. raise UnknownModel()
  206. elif _last_output() == "Model loaded, ready for commands!":
  207. mode = 3
  208. if ("r/w" in _output()):
  209. write = True
  210. else:
  211. write = False
  212. _output("Use 'help' command for a list of possible commands")
  213. _output("Please give your command.")
  214. return write
  215. else:
  216. raise InterfaceMismatch()
  217. def model_list():
  218. """List all models."""
  219. # return [(model1, metamodel1), (model2, metamodel2), ...]
  220. # raises UnknownError
  221. if mode != 2:
  222. raise InvalidMode()
  223. _input("model_list")
  224. lst = []
  225. while (_output() != "Ready for command..."):
  226. v = _last_output()
  227. m, mm = v.split(":")
  228. m = m.strip()
  229. mm = mm.strip()
  230. lst.append((m, mm))
  231. return lst
  232. def model_list_full():
  233. """List full information on all models."""
  234. # return [(model1, metamodel1, owner1, group1, permissions1), (model2, metamodel2, owner2, group2, permissions2), ...]
  235. # raises UnknownError
  236. if mode != 2:
  237. raise InvalidMode()
  238. _input("model_list_full")
  239. lst = []
  240. while (_output() != "Ready for command..."):
  241. v = _last_output()
  242. m, mm = v.split(":")
  243. m = m.strip()
  244. mm = mm.strip()
  245. perm, own, grp, m = m.split(" ")
  246. lst.append((m, mm, own, grp, perm))
  247. return lst
  248. def model_overwrite(model_name, new_model=None):
  249. """Upload a new model and overwrite an existing model."""
  250. # return None
  251. # raises UnknownModel
  252. # raises PermissionDenied
  253. # raises CompilationError
  254. # raises UnknownError
  255. if mode != 2:
  256. raise InvalidMode()
  257. if new_model is not None:
  258. try:
  259. compiled = _compile_model(new_model)
  260. except Exception as e:
  261. raise CompilationError(e)
  262. else:
  263. compiled = ["exit"]
  264. _input("model_overwrite")
  265. _output("Which model to overwrite?")
  266. _input(model_name)
  267. if _output() == "Permission denied":
  268. _output("Ready for command...")
  269. raise PermissionDenied()
  270. elif _last_output() == "No such model":
  271. _output("Ready for command...")
  272. raise UnknownModel()
  273. elif _last_output() == "Waiting for model constructors...":
  274. _input(compiled)
  275. _output("Model overwrite success")
  276. _output("Ready for command...")
  277. def user_logout():
  278. """Log out the current user and break the connection."""
  279. # return None
  280. # raises UnknownException
  281. global mode
  282. if mode != 2:
  283. raise InvalidMode()
  284. _input("exit")
  285. mode = 0
  286. def user_delete():
  287. """Removes the current user and break the connection."""
  288. # return None
  289. # raises UnknownException
  290. global mode
  291. if mode != 2:
  292. raise InvalidMode()
  293. _input("self-destruct")
  294. mode = 0
  295. def model_render(model, mapper):
  296. """Fetch a rendered verion of a model."""
  297. # return JSON_representation
  298. # raises UnknownException
  299. # raises UnknownIdentifier
  300. # raises InterfaceMismatch
  301. global mode
  302. if mode != 2:
  303. raise InvalidMode()
  304. _input("model_render")
  305. _output()
  306. _input(model)
  307. _output()
  308. _input(mapper)
  309. rendered = _output()
  310. _output("Ready for command...")
  311. return rendered
  312. def transformation_add_MT_language():
  313. """Create a new Model Transformation language out of a set of metamodels."""
  314. raise NotImplementedError()
  315. def transformation_add_MT():
  316. """Create a new model transformation."""
  317. raise NotImplementedError()
  318. def transformation_add_AL():
  319. """Create a new action language fragment."""
  320. raise NotImplementedError()
  321. def transformation_add_MANUAL():
  322. """Create a new manual model operation."""
  323. raise NotImplementedError()
  324. def transformation_execute():
  325. """Execute an existing model operation."""
  326. raise NotImplementedError()
  327. def transformation_list():
  328. """List existing model operations."""
  329. raise NotImplementedError()
  330. def transformation_list_full():
  331. """List detailed information on model operations."""
  332. raise NotImplementedError()
  333. def transformation_detail():
  334. """List full details of a a model operation."""
  335. raise NotImplementedError()
  336. def transformation_RAMify():
  337. """Ramify an existing metamodel."""
  338. raise NotImplementedError()
  339. def process_execute():
  340. """Execute a process model."""
  341. raise NotImplementedError()
  342. def permission_modify():
  343. """Modify permissions of a model."""
  344. raise NotImplementedError()
  345. def permission_owner():
  346. """Modify the owning user of a model."""
  347. raise NotImplementedError()
  348. def permission_group():
  349. """Modify the owning group of a model."""
  350. raise NotImplementedError()
  351. def group_create():
  352. """Create a new group."""
  353. raise NotImplementedError()
  354. def group_delete():
  355. """Delete a group of which you are an owner."""
  356. raise NotImplementedError()
  357. def group_owner_add():
  358. """Add a new owning user to a group you own."""
  359. raise NotImplementedError()
  360. def group_owner_delete():
  361. """Delete an owning user to a group you own."""
  362. raise NotImplementedError()
  363. def group_join():
  364. """Add a new user to a group you own."""
  365. raise NotImplementedError()
  366. def group_kick():
  367. """Delete a user from a group you own."""
  368. raise NotImplementedError()
  369. def group_list():
  370. """List existing groups."""
  371. raise NotImplementedError()
  372. def admin_promote():
  373. """Promote a user to admin status."""
  374. raise NotImplementedError()
  375. def admin_demote():
  376. """Demote a user from admin status."""
  377. raise NotImplementedError()
  378. # Actual operations on the model
  379. def element_list():
  380. """Return a list of all IDs and the type of the element"""
  381. # return [(name1, type1), (name2, type2), ...]
  382. # raises UnknownError
  383. if mode != 3:
  384. raise InvalidMode()
  385. _input("list")
  386. lst = []
  387. _output("List of all elements:")
  388. while (_output() != "Please give your command."):
  389. v = _last_output()
  390. m, mm = v.split(":")
  391. m = m.strip()
  392. mm = mm.strip()
  393. lst.append((m, mm))
  394. return lst
  395. def types():
  396. """Return a list of all types usable in the model"""
  397. # return [type1, type2, ...]
  398. # raises UnknownError
  399. if mode != 3:
  400. raise InvalidMode()
  401. _input("types")
  402. _output("List of types:")
  403. lst = []
  404. while (_output() != "Please give your command."):
  405. v = _last_output()
  406. m, mm = v.split(":")
  407. m = m.strip()
  408. lst.append(m)
  409. return lst
  410. def read(ID):
  411. """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
  412. # return (type, (source, target))
  413. # raises UnknownError
  414. # raises UnknownIdentifier
  415. if mode != 3:
  416. raise InvalidMode()
  417. _input("read")
  418. _output("Element to read?")
  419. _input(ID)
  420. if _output() == "Unknown element; aborting":
  421. _output("Please give your command.")
  422. raise UnknownIdentifier()
  423. elif _last_output() == "ID: " + str(ID):
  424. t = _output().split(":")[1].strip()
  425. if (not _output().startswith("Source:")):
  426. rval = (t, None)
  427. else:
  428. src = _last_output().split(":")[1].strip()
  429. trg = _output().split(":")[1].strip()
  430. rval = (t, (src, trg))
  431. while (_output() != "Please give your command."):
  432. pass
  433. return rval
  434. def read_attrs(ID):
  435. """Return a dictionary of attribute value pairs"""
  436. # return {attr1: value1, attr2: value2, ...}
  437. # raises UnknownError
  438. # raises UnknownIdentifier
  439. if mode != 3:
  440. raise InvalidMode()
  441. _input("read")
  442. _output("Element to read?")
  443. _input(ID)
  444. if _output() == "Unknown element; aborting":
  445. _output("Please give your command.")
  446. raise UnknownIdentifier()
  447. elif _last_output() == "ID: " + str(ID):
  448. rval = {}
  449. # Skip until attributes
  450. while (_output() != "Attributes:"):
  451. pass
  452. while (_output() != "Please give your command."):
  453. r = _last_output()
  454. key, value = r.split(":")
  455. _, value = value.split("=")
  456. key = json.loads(key.strip())
  457. value = value.strip()
  458. value = None if value == "None" else json.loads(value)
  459. rval[key] = value
  460. return rval
  461. def instantiate(typename, edge=None, ID=""):
  462. """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
  463. # return instantiated_ID
  464. # raises UnknownError
  465. # raises UnknownType
  466. # raises UnknownIdentifier
  467. # raises NotAnEdge
  468. if mode != 3:
  469. raise InvalidMode()
  470. _input("instantiate")
  471. if (_output() == "Permission denied"):
  472. _output("Please give your command.")
  473. raise PermissionDenied()
  474. else:
  475. _input(typename)
  476. if (_output() == "Name of new element?"):
  477. _input(ID)
  478. if (_output() == "Element already exists; aborting"):
  479. _output("Please give your command.")
  480. raise ElementExists()
  481. if (edge is not None) and (_last_output() == "Source name?"):
  482. # Is an edge and we have data
  483. _input(edge[0])
  484. if _output() == "Destination name?":
  485. _input(edge[1])
  486. if _output() == "Instantiation successful!":
  487. ID = _output()
  488. _output("Please give your command.")
  489. return ID
  490. elif _last_output() == "Unknown destination; aborting":
  491. _output("Please give your command.")
  492. raise UnknownIdentifier()
  493. else:
  494. raise InterfaceMismatch(_last_output())
  495. elif _last_output() == "Unknown source; aborting":
  496. _output("Please give your command.")
  497. raise UnknownIdentifier()
  498. else:
  499. raise InterfaceMismatch(_last_output())
  500. elif (edge is None) and (_last_output() != "Source name?"):
  501. # Is no edge and we don't have data
  502. if _last_output() == "Instantiation successful!":
  503. ID = _output()
  504. _output("Please give your command.")
  505. return ID
  506. else:
  507. raise InterfaceMismatch(_last_output())
  508. elif (edge is not None) and (_last_output() != "Source name?"):
  509. # Is no edge, but we have edge data to input: ERROR
  510. # Delete the element again
  511. ID = _last_output()
  512. _output("Please give your command.")
  513. delete_element(ID)
  514. raise NotAnEdge()
  515. elif (edge is None) and (_last_output() == "Source name?"):
  516. # Is an edge, but we have no edge data to input: ERROR
  517. # Add an empty source, which is guaranteed not to be there
  518. _input("")
  519. _output("Unknown source; aborting")
  520. _output("Please give your command.")
  521. raise NotAnEdge()
  522. elif (_last_output() == "Permission denied"):
  523. _output("Please give your command.")
  524. raise PermissionDenied()
  525. elif (_last_output() == "Unknown type specified; aborting"):
  526. _output("Please give your command.")
  527. raise UnknownType()
  528. else:
  529. raise InterfaceMismatch(_last_output())
  530. def delete_element(ID):
  531. """Delete the element with the given ID"""
  532. # return None
  533. # raises UnknownError
  534. # raises UnknownIdentifier
  535. if mode != 3:
  536. raise InvalidMode()
  537. _input("delete")
  538. if _output() == "What is the name of the element you want to delete?":
  539. _input(ID)
  540. if _output() == "Deleted!":
  541. _output("Please give your command.")
  542. elif _last_output() == "No such element; aborting":
  543. _output("Please give your command.")
  544. raise UnknownIdentifier()
  545. else:
  546. raise InterfaceMismatch(_last_output())
  547. elif _last_output() == "Permission denied":
  548. _output("Please give your command.")
  549. raise PermissionDenied()
  550. else:
  551. raise InterfaceMismatch(_last_output())
  552. def attr_assign(ID, attr, value):
  553. """Assign a value to an attribute"""
  554. # return None
  555. # raises UnknownError
  556. # raises UnknownIdentifier
  557. # raises NoSuchAttribute
  558. # raises UnsupportedValue
  559. if mode != 3:
  560. raise InvalidMode()
  561. _input("attr_add")
  562. if _output() == "Which element do you want to assign an attribute to?":
  563. _input(ID)
  564. if _output() == "Which attribute do you want to assign?":
  565. _input(attr)
  566. if _output() == "Value of attribute?":
  567. _input(value)
  568. _output("Added attribute!")
  569. _output("Please give your command.")
  570. elif _last_output() == "No such attribute!":
  571. _output("Please give your command.")
  572. raise NoSuchAttribute()
  573. else:
  574. raise InterfaceMismatch(_last_output())
  575. elif _last_output() == "No such element!":
  576. _output("Please give your command.")
  577. raise UnknownIdentifier()
  578. else:
  579. raise InterfaceMismatch(_last_output())
  580. elif _last_output() == "Permission denied":
  581. _output("Please give your command.")
  582. raise PermissionDenied()
  583. else:
  584. raise InterfaceMismatch(_last_output())
  585. def attr_assign_code(ID, attr, code):
  586. """Assign a piece of Action Language code to the attribute"""
  587. # return None
  588. # raises UnknownError
  589. # raises UnknownIdentifier
  590. # raises NoSuchAttribute
  591. # raises UnsupportedValue
  592. if mode != 3:
  593. raise InvalidMode()
  594. try:
  595. compiled = _compile_AL(code)
  596. except Exception as e:
  597. raise CompilationError(e)
  598. _input("attr_add")
  599. if _output() == "Which element do you want to assign an attribute to?":
  600. _input(ID)
  601. if _output() == "Which attribute do you want to assign?":
  602. _input(attr)
  603. if _output() == "Waiting for code constructors...":
  604. _input(compiled)
  605. _output("Added attribute!")
  606. _output("Please give your command.")
  607. elif _last_output() == "No such attribute!":
  608. _output("Please give your command.")
  609. raise NoSuchAttribute()
  610. else:
  611. raise InterfaceMismatch(_last_output())
  612. elif _last_output() == "No such element!":
  613. _output("Please give your command.")
  614. raise UnknownIdentifier()
  615. else:
  616. raise InterfaceMismatch(_last_output())
  617. elif _last_output() == "Permission denied":
  618. _output("Please give your command.")
  619. raise PermissionDenied()
  620. else:
  621. raise InterfaceMismatch(_last_output())
  622. def attr_delete(ID, attr):
  623. """Remove an attribute."""
  624. if mode != 3:
  625. raise InvalidMode()
  626. _input("attr_del")
  627. if _output() == "Which element do you want to remove an attribute of?":
  628. _input(ID)
  629. if _output() == "Which attribute do you want to delete?":
  630. _input(attr)
  631. if _output() == "Attribute deleted!":
  632. _output("Please give your command.")
  633. elif _last_output() == "No such attribute!":
  634. _output("Please give your command.")
  635. raise NoSuchAttribute()
  636. else:
  637. raise InterfaceMismatch(_last_output())
  638. elif _last_output() == "No such element!":
  639. _output("Please give your command.")
  640. raise UnknownIdentifier()
  641. else:
  642. raise InterfaceMismatch(_last_output())
  643. elif _last_output() == "Permission denied":
  644. _output("Please give your command.")
  645. raise PermissionDenied()
  646. else:
  647. raise InterfaceMismatch(_last_output())
  648. def read_outgoing(ID, typename):
  649. """Returns a list of all outgoing associations of a specific type ("" = all)"""
  650. # return [name1, name2, ...]
  651. # raises UnknownError
  652. # raises UnknownIdentifier
  653. if mode != 3:
  654. raise InvalidMode()
  655. _input("read_outgoing")
  656. _output("Element to read from?")
  657. _input(ID)
  658. if _output() == "Type of outgoing edge (empty for all)?":
  659. _input(typename)
  660. lst = []
  661. while (_output() != "Please give your command."):
  662. lst.append(_last_output())
  663. return lst
  664. elif _last_output() == "Unknown element; aborting":
  665. _output("Please give your command.")
  666. raise UnknownIdentifier()
  667. else:
  668. raise InterfaceMismatch()
  669. def read_incoming(ID, typename):
  670. """Returns a list of all incoming associations of a specific type ("" = all)"""
  671. # return [name1, name2, ...]
  672. # raises UnknownError
  673. # raises UnknownIdentifier
  674. # raises UnknownType
  675. if mode != 3:
  676. raise InvalidMode()
  677. _input("read_incoming")
  678. _output("Element to read from?")
  679. _input(ID)
  680. if _output() == "Type of incoming edge (empty for all)?":
  681. _input(typename)
  682. lst = []
  683. while (_output() != "Please give your command."):
  684. lst.append(_last_output())
  685. return lst
  686. elif _last_output() == "Unknown element; aborting":
  687. _output("Please give your command.")
  688. raise UnknownIdentifier()
  689. else:
  690. raise InterfaceMismatch()
  691. def read_association_source(ID):
  692. """Returns the source of an association."""
  693. # returns name
  694. # raises UnknownError
  695. # raises UnknownIdentifier
  696. # raises NotAnAssociation
  697. _input("read_association_source")
  698. _output("Association to read source of?")
  699. _input(ID)
  700. if _output() == "Read source:":
  701. result = _output()
  702. _output("Please give your command.")
  703. return result
  704. elif _last_output() == "Unknown element; aborting":
  705. _output("Please give your command.")
  706. raise UnknownIdentifier()
  707. elif _last_output() == "Not an association; aborting":
  708. _output("Please give your command.")
  709. raise NotAnEdge()
  710. else:
  711. raise InterfaceMismatch(_last_output())
  712. def read_association_destination(ID):
  713. """Returns the destination of an association."""
  714. # returns name
  715. # raises UnknownError
  716. # raises UnknownIdentifier
  717. # raises NotAnAssociation
  718. _input("read_association_destination")
  719. _output("Association to read destination of?")
  720. _input(ID)
  721. if _output() == "Read destination:":
  722. result = _output()
  723. _output("Please give your command.")
  724. return result
  725. elif _last_output() == "Unknown element; aborting":
  726. _output("Please give your command.")
  727. raise UnknownIdentifier()
  728. elif _last_output() == "Not an association; aborting":
  729. _output("Please give your command.")
  730. raise NotAnEdge()
  731. else:
  732. raise InterfaceMismatch(_last_output())
  733. def model_exit():
  734. """Leave model modify mode."""
  735. # return None
  736. # raises UnknownError
  737. global mode
  738. if mode != 3:
  739. raise InvalidMode()
  740. _input("exit")
  741. _output("Ready for command...")
  742. mode = 2