Browse Source

Fixed many bugs in wrapper

Yentl Van Tendeloo 8 years ago
parent
commit
0075fd12b8
2 changed files with 213 additions and 207 deletions
  1. 205 207
      wrappers/modelverse.py
  2. 8 0
      wrappers/test_modelverse.py

+ 205 - 207
wrappers/modelverse.py

@@ -3,6 +3,11 @@ import urllib2
 import json
 import random
 from urllib2 import URLError
+import sys
+
+# Bind to the compiler
+sys.path.append("../interface/HUTN")
+from hutn_compiler.compiler import main as do_compile
 
 # Helper functions and configuration: do not use yourself!
 taskname = random.random()
@@ -12,20 +17,49 @@ mode = 0
 
 def _input(value):
     # Ugly json encoding of primitives
-    value = '"%s"' % value if type(value) == str else value
-    urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
+    if isinstance(value, type([])):
+        value = json.dumps(value)
+        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": taskname}))).read()
+    else:
+        value = json.dumps(value)
+        urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
 
 def _input_raw(value, taskname):
     # Ugly json encoding of primitives
     urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
 
-def _compile_AL(AL_file):
+def _compile_AL(code):
     # Compile an action language file and send the compiled code
-    pass
+    code_fragments = code.split("\n")
+    code_fragments = [i for i in code_fragments if i.strip() != ""]
+    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
+    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
+    code_fragments = [i[initial_tabs:] for i in code_fragments]
+    code_fragments.append("")
+    code = "\n".join(code_fragments)
+
+    with open("__constraint.alc", "w") as f:
+        f.write(code)
+        f.flush()
 
-def _compile_model(model_file):
+    _input(do_compile("__constraint.alc", "../interface/HUTN/grammars/actionlanguage.g", "CS"))
+
+def _compile_model(code):
     # Compile a model and send the compiled graph
-    pass
+    # First change multiple spaces to a tab
+    code_fragments = code.split("\n")
+    code_fragments = [i for i in code_fragments if i.strip() != ""]
+    code_fragments = [i.replace("    ", "\t") for i in code_fragments]
+    initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
+    code_fragments = [i[initial_tabs:] for i in code_fragments]
+    code_fragments.append("")
+    code = "\n".join(code_fragments)
+
+    with open("__model.mvc", "w") as f:
+        f.write(code)
+        f.flush()
+
+    _input(do_compile("__model.mvc", "../interface/HUTN/grammars/modelling.g", "M") + ["exit"])
 
 def _output():
     try:
@@ -39,37 +73,40 @@ def _last_output():
     return last_output
 
 # Exceptions
-class UnknownError(Exception):
+class ModelverseException(Exception):
+    pass
+
+class UnknownError(ModelverseException):
     pass
 
-class UnknownIdentifier(Exception):
+class UnknownIdentifier(ModelverseException):
     pass
 
-class UnknownType(Exception):
+class UnknownType(ModelverseException):
     pass
 
-class UnsupportedValue(Exception):
+class UnsupportedValue(ModelverseException):
     pass
 
-class CompilationError(Exception):
+class CompilationError(ModelverseException):
     pass
 
-class NoSuchAttribute(Exception):
+class NoSuchAttribute(ModelverseException):
     pass
 
-class UnknownModel(Exception):
+class UnknownModel(ModelverseException):
     pass
 
-class ConnectionError(Exception):
+class ConnectionError(ModelverseException):
     pass
 
-class ModelExists(Exception):
+class ModelExists(ModelverseException):
     pass
 
-class PermissionDenied(Exception):
+class PermissionDenied(ModelverseException):
     pass
 
-class InvalidMode(Exception):
+class InvalidMode(ModelverseException):
     pass
 
 # Main MvC operations
@@ -89,8 +126,6 @@ def init(address_param="http://localhost:8001"):
         mode = 1
     except URLError as e:
         raise ConnectionError(e.reason)
-    except Exception as e:
-        raise UnknownError(str(e))
 
 def login(username, password):
     """Log in an existing user."""
@@ -100,12 +135,11 @@ def login(username, password):
     global mode
     if mode != 1:
         raise InvalidMode()
-    try:
-        _input(username)
-        _input(password)
-        mode = 2
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input(username)
+    _input(password)
+    while (_output() != "Ready for command..."):
+        pass
+    mode = 2
 
 def register(username, password):
     """Register a new user."""
@@ -115,31 +149,44 @@ def register(username, password):
     global mode
     if mode != 1:
         raise InvalidMode()
-    try:
-        _input(username)
-        _input(password)
-        _input(password)
-        while (_output() != "Ready for command..."):
-            print(_last_output())
-            pass
-        mode = 2
-    except Exception as e:
-        raise UnknownError(str(e))
-
-def model_add(model_name, metamodel_name):
+    _input(username)
+    _input(password)
+    _input(password)
+    while (_output() != "Ready for command..."):
+        pass
+    mode = 2
+
+def model_add(model_name, metamodel_name, model_code):
     """Instantiate a new model."""
     # return None
     # raises UnknownModel
     # raises ModelExists
     # raises UnknownError
+    # raises PermissionDenied
+    # raises CompilationError
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("model_add")
-        _input(metamodel_name)
+    _input("model_add")
+    _output()
+    _output()
+    _input(metamodel_name)
+    if _output() == "Model name?":
         _input(model_name)
-    except Exception as e:
-        raise UnknownError(str(e))
+        if _output() == "Waiting for model constructors...":
+            try:
+                _compile_model(model_code)
+            except Exception:
+                raise CompilationError()
+
+            while (_output() != "Ready for command..."):
+                print(_last_output())
+                pass
+        else:
+            raise ModelExists()
+    elif _last_output() == "Could not find type model!":
+        raise UnknownModel()
+    elif _last_output() == "Permission denied":
+        raise PermissionDenied()
 
 def model_modify(model_name):
     """Modify an existing model."""
@@ -150,20 +197,23 @@ def model_modify(model_name):
     global mode
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("model_modify")
-        _input(model_name)
+
+    _input("model_modify")
+    _output()
+    _input(model_name)
+    if _output() == "Permission denied":
+        raise PermissionDenied()
+    elif _last_output() == "Could not find model!":
+        raise UnknownModel()
+    elif _last_output() == "Model loaded, ready for commands!":
         mode = 3
-        _input("help")
-        _output()
         if ("r/w" in _output()):
             write = True
         else:
             write = False
-        _output()
+        while (_output() != "Please give your command."):
+            pass
         return write
-    except Exception as e:
-        raise UnknownError(str(e))
 
 def model_list():
     """List all models."""
@@ -171,19 +221,15 @@ def model_list():
     # raises UnknownError
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("model_list")
-        lst = []
-        while (_output() != "Ready for command..."):
-            v = _last_output()
-            print("Got: " + str(v))
-            m, mm = v.split(":")
-            m.strip()
-            mm.strip()
-            lst.append((m, mm))
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("model_list")
+    lst = []
+    while (_output() != "Ready for command..."):
+        v = _last_output()
+        m, mm = v.split(":")
+        m.strip()
+        mm.strip()
+        lst.append((m, mm))
+    return lst
 
 def model_list_full():
     """List full information on all models."""
@@ -191,19 +237,16 @@ def model_list_full():
     # raises UnknownError
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("model_list_full")
-        lst = []
-        while (_output() != "Ready for command..."):
-            v = _last_output()
-            m, mm = v.split(":")
-            m.strip()
-            mm.strip()
-            perm, own, grp, m = m.split(" ")
-            lst.append((m, mm, own, grp, perm))
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("model_list_full")
+    lst = []
+    while (_output() != "Ready for command..."):
+        v = _last_output()
+        m, mm = v.split(":")
+        m.strip()
+        mm.strip()
+        perm, own, grp, m = m.split(" ")
+        lst.append((m, mm, own, grp, perm))
+    return lst
 
 def model_overwrite(model_name, new_model):
     """Upload a new model and overwrite an existing model."""
@@ -214,12 +257,9 @@ def model_overwrite(model_name, new_model):
     # raises UnknownError
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("model_overwrite")
-        _input(model_name)
-        _compile_model(new_model)
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("model_overwrite")
+    _input(model_name)
+    _compile_model(new_model)
 
 def user_logout():
     """Log out the current user. A new login will be required afterwards."""
@@ -228,11 +268,8 @@ def user_logout():
     global mode
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("exit")
-        mode = 1
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("exit")
+    mode = 1
 
 def user_delete():
     """Removes the current user. A new login will be required afterwards."""
@@ -241,31 +278,26 @@ def user_delete():
     global mode
     if mode != 2:
         raise InvalidMode()
-    try:
-        _input("self-destruct")
-        mode = 1
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("self-destruct")
+    mode = 1
 
 # Actual operations on the model
-def list():
+def element_list():
     """Return a list of all IDs and the type of the element"""
     # return [(name1, type1), (name2, type2), ...]
     # raises UnknownError
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("list")
-        lst = []
-        while (_output() != "Ready for command..."):
-            v = _last_output()
-            m, mm = v.split(":")
-            m.strip()
-            mm.strip()
-            lst.append((m, mm))
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("list")
+    lst = []
+    _output()
+    while (_output() != "Please give your command."):
+        v = _last_output()
+        m, mm = v.split(":")
+        m.strip()
+        mm.strip()
+        lst.append((m, mm))
+    return lst
 
 def types():
     """Return a list of all types usable in the model"""
@@ -273,17 +305,14 @@ def types():
     # raises UnknownError
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("types")
-        lst = []
-        while (_output() != "Ready for command..."):
-            v = _last_output()
-            m, mm = v.split(":")
-            m.strip()
-            lst.append(m)
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("types")
+    lst = []
+    while (_output() != "Ready for command..."):
+        v = _last_output()
+        m, mm = v.split(":")
+        m.strip()
+        lst.append(m)
+    return lst
 
 def read(ID):
     """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
@@ -292,22 +321,19 @@ def read(ID):
     # raises UnknownIdentifier
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("read")
-        _input(ID)
-        _output()
-        t = _output().split(":")[1].strip()
-        if (not _output().startswith("Source:")):
-            rval = (t, None)
-        else:
-            src = _last_output().split(":")[1].strip()
-            trg = _output().split(":")[1].strip()
-            rval = (t, (src, trg))
-        while (_output() != "Ready for command..."):
-            pass
-        return rval
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("read")
+    _input(ID)
+    _output()
+    t = _output().split(":")[1].strip()
+    if (not _output().startswith("Source:")):
+        rval = (t, None)
+    else:
+        src = _last_output().split(":")[1].strip()
+        trg = _output().split(":")[1].strip()
+        rval = (t, (src, trg))
+    while (_output() != "Ready for command..."):
+        pass
+    return rval
 
 def read_attrs(ID):
     """Return a dictionary of attribute value pairs"""
@@ -315,22 +341,19 @@ def read_attrs(ID):
     # raises UnknownError
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("read")
-        _input(ID)
-        rval = {}
-        while (_output() != "Attributes:"):
-            pass
-        while (_output() != "Ready for command..."):
-            r = _last_output()
-            key, value = r.split(":")
-            _, value = value.split("=")
-            key.strip()
-            value.strip()
-            rval[key] = value
-        return rval
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("read")
+    _input(ID)
+    rval = {}
+    while (_output() != "Attributes:"):
+        pass
+    while (_output() != "Ready for command..."):
+        r = _last_output()
+        key, value = r.split(":")
+        _, value = value.split("=")
+        key.strip()
+        value.strip()
+        rval[key] = value
+    return rval
 
 def instantiate(typename, edge=None, ID=""):
     """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
@@ -340,15 +363,12 @@ def instantiate(typename, edge=None, ID=""):
     # raises UnknownIdentifier
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("instantiate")
-        _input(typename)
-        _input(ID)
-        if (edge is not None):
-            _input(edge[0])
-            _input(edge[1])
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("instantiate")
+    _input(typename)
+    _input(ID)
+    if (edge is not None):
+        _input(edge[0])
+        _input(edge[1])
 
 def delete(ID):
     """Delete the element with the given ID"""
@@ -357,11 +377,8 @@ def delete(ID):
     # raises UnknownIdentifier
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("delete")
-        _input(ID)
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("delete")
+    _input(ID)
 
 def attr_assign(ID, attr, value):
     """Assign a value to an attribute"""
@@ -372,13 +389,10 @@ def attr_assign(ID, attr, value):
     # raises UnsupportedValue
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("attr_modify")
-        _input(ID)
-        _input(attr)
-        _input(value)
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("attr_modify")
+    _input(ID)
+    _input(attr)
+    _input(value)
 
 def attr_assign_code(ID, attr, code):
     """Assign a piece of Action Language code to the attribute"""
@@ -389,13 +403,10 @@ def attr_assign_code(ID, attr, code):
     # raises UnsupportedValue
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("attr_modify")
-        _input(ID)
-        _input(attr)
-        _compile_AL(code)
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("attr_modify")
+    _input(ID)
+    _input(attr)
+    _compile_AL(code)
 
 def upload(new_model):
     """Overwrite the current model with the provided model"""
@@ -404,11 +415,8 @@ def upload(new_model):
     # raises CompilationError
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("upload")
-        _compile_model(new_model)
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("upload")
+    _compile_model(new_model)
 
 def read_outgoing(ID, typename):
     """Returns a list of all outgoing associations of a specific type ("" = all)"""
@@ -418,16 +426,13 @@ def read_outgoing(ID, typename):
     # raises UnknownType
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("read_outgoing")
-        _input(ID)
-        _input(typename)
-        lst = []
-        while (_output() != "Please give your command."):
-            lst.append(_last_output())
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("read_outgoing")
+    _input(ID)
+    _input(typename)
+    lst = []
+    while (_output() != "Please give your command."):
+        lst.append(_last_output())
+    return lst
 
 def read_incoming(ID, typename):
     """Returns a list of all incoming associations of a specific type ("" = all)"""
@@ -437,16 +442,13 @@ def read_incoming(ID, typename):
     # raises UnknownType
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("read_incoming")
-        _input(ID)
-        _input(typename)
-        lst = []
-        while (_output() != "Please give your command."):
-            lst.append(_last_output())
-        return lst
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("read_incoming")
+    _input(ID)
+    _input(typename)
+    lst = []
+    while (_output() != "Please give your command."):
+        lst.append(_last_output())
+    return lst
 
 def model_exit():
     """Leave model modify mode."""
@@ -455,11 +457,8 @@ def model_exit():
     global mode
     if mode != 3:
         raise InvalidMode()
-    try:
-        _input("exit")
-        mode = 2
-    except Exception as e:
-        raise UnknownError(str(e))
+    _input("exit")
+    mode = 2
 
 def transformation_add_MT_language():
     """Create a new Model Transformation language out of a set of metamodels."""
@@ -548,4 +547,3 @@ def admin_promote():
 def admin_demote():
     """Demote a user from admin status."""
     raise NotImplementedError()
-

+ 8 - 0
wrappers/test_modelverse.py

@@ -6,4 +6,12 @@ password = str(random())
 
 init()
 register(username, password)
+
+try:
+    model_add("PetriNets", "SimpleClassDiagrams", open("../models/petrinet_ports.mvc", "r").read())
+except ModelExists:
+    pass
+
+model_modify("PetriNets")
+print(element_list())
 print(model_list())