def run(self, **kwargs): self.inputs = Parameters(self, self.inputs_def) self.outputs = Parameters(self, self.outputs_def) params = {} for in_model in self.inputs_def: try: param = kwargs.pop(in_model) if isinstance(param, Ecore.EObject): if param.eResource: resource = param.eResource else: rset = self.resource_set resource = rset.create_resource(URI(in_model)) resource.append(param) elif isinstance(param, Resource): resource = param else: resource = load_model(param) setattr(self.inputs, in_model, resource) params[in_model] = resource if in_model in self.inouts: setattr(self.outputs, in_model, resource) params[in_model] = resource except KeyError as e: raise type( e)(str(e) + ' is a missing input model'.format(in_model)) from None for out_model in list(set(self.outputs_def) - set(self.inouts)): resource = self.resource_set.create_resource(URI(out_model)) setattr(self.outputs, out_model, resource) params[out_model] = resource self.primary_output = self.outputs[0] self._main(**params)
def save(pkg, targetfolder, name=PKGNAME): """ Serialize an EPackage. For now, produce both XMI and EMFJSON formats on each call. """ xmipath = str((targetfolder / (name + '.xmi')).resolve()) jsonpath = str((targetfolder / (name + '.json')).resolve()) xmi = XMIResource(URI(xmipath)) json = JsonResource(URI(jsonpath), indent=4) xmi.append(pkg) json.append(pkg) xmi.save() json.save()
def load(): #return model_root rset = ResourceSet() resource = rset.get_resource(URI('metamodel.ecore')) mm_root = resource.contents[0] rset.metamodel_registry[mm_root.nsURI] = mm_root resource = rset.get_resource(URI('model.xmi')) model_root = resource.contents[0] MyMetamodel = DynamicEPackage(mm_root) #main_model_creator() #debug
def model_setup(): rset = ResourceSet() resource = rset.get_resource(URI('metamodel.ecore')) mm_root = resource.contents[0] mm_root.nsURI = 'ghmde' mm_root.nsPrefix = 'model' mm_root.name = 'ghmde' rset.metamodel_registry[mm_root.nsURI] = mm_root print(mm_root.nsURI) MyMetamodel = DynamicEPackage( mm_root) # We create a DynamicEPackage for the loaded root file_instance = MyMetamodel.File() print(file_instance) A = mm_root.getEClassifier('Model') # nuovo instance = A() dictionary = {} dictionary['model'] = instance dictionary['meta-model'] = MyMetamodel return dictionary
def generated_metamodel(pygen_output_dir): rset = ResourceSet() resource = rset.get_resource(URI('input/A.ecore')) library_model = resource.contents[0] generator = EcoreGenerator(with_dependencies=True) generator.generate(library_model, pygen_output_dir) return importlib.import_module('a')
def test_command_resource(mm): rset = ResourceSet() resource = rset.create_resource(URI('http://logical')) a = mm.A() resource.append(a) cmd = Set(a, 'name', 'test_value') assert cmd.resource is resource
def save_objects(*objects: EObject, path: str = "./out.highlevelnaoapp") -> None: """Save objects to the given path.""" resource = ResourceSet().create_resource(URI(path)) for obj in objects: resource.append(obj) resource.save()
def save(self, filename): uri = URI(filename) fileresource = self.rset.create_resource(uri) # add the current energy system fileresource.append(self.es) # save the resource fileresource.save()
def generated_library(pygen_output_dir): rset = ResourceSet() resource = rset.get_resource(URI('input/library.ecore')) library_model = resource.contents[0] generator = EcoreGenerator() generator.generate(library_model, pygen_output_dir) return importlib.import_module('library')
def save(self, es_id=None, filename=None): """Add the resource to the resourceSet when saving""" if filename is None: if es_id is None: self.resource.save() else: if es_id in self.esid_uri_dict: my_uri = self.esid_uri_dict[es_id] resource = self.rset.resources[my_uri] resource.save() else: # TODO: what to do? original behaviour self.resource.save() else: uri = URI(filename) fileresource = self.rset.create_resource(uri) if es_id is None: # add the current energy system fileresource.append(self.energy_system) else: if es_id in self.esid_uri_dict: my_uri = self.esid_uri_dict[es_id] es = self.rset.resources[my_uri].contents[0] fileresource.append(es) else: # TODO: what to do? original behaviour # add the current energy system fileresource.append(self.energy_system) # save the resource fileresource.save() self.rset.remove_resource(fileresource)
def test_roundtrip_LargeXMI(tmpdir, rset): resource = rset.get_resource(URI('tests/xmi-data/LargeConns.net.nml.xmi')) root = resource.contents[0] # We change the root name root.name = 'largeTestModel' # We serialize the modifications f = tmpdir.mkdir('pyecore-tmp').join('large.xmi') resource.save(output=URI(str(f))) # We read again the file resource = rset.get_resource(URI(str(f))) root = resource.contents[0] assert root assert root.name == 'largeTestModel'
def apply_relative_from_me(self, relative_path): # currently make all http-based uri's unique, # better would be to check each path's segment until there is a difference rel_uri = URI(relative_path) conv_uri: URI = URIConverter.convert(rel_uri) print('rel_uri', rel_uri, rel_uri.plain) print('conv_uri', conv_uri, conv_uri.plain) print('self.segments', self.segments) print('conv.segments', conv_uri.segments) if conv_uri.protocol == self.protocol: not_common = str() common = str() for i in range(len(self.segments) - 1, -1, -1): if self.segments[i] == conv_uri.segments[i]: common = self.segments[i] + '/' + common else: not_common = ( self.segments[i] + '/' + not_common ) if not_common is not '' else self.segments[i] common = self.protocol + '://' + common print('common', common) print('not_common', not_common) return not_common print('relative path:', relative_path) return relative_path
def loadModelDDM(self, input_file): rset = ResourceSet() # register the metamodel (available in the generated files) rset.metamodel_registry[ddm.nsURI] = ddm rset.resource_factory['ddm'] = lambda uri: XMIResource(uri) resource = rset.get_resource(URI(input_file)) model = resource.contents[0] return model
def test_resourceset_createresource_xmi(): rset = ResourceSet() resource = rset.create_resource(URI('simple.xmi')) rpath = path.abspath('simple.xmi') assert rpath in rset.resources assert rset.resources[rpath] is resource assert rset in resource._decoders assert isinstance(resource, rset.resource_factory['xmi']('').__class__)
def __init__(self): rset = ResourceSet() model_url = URI( os.path.join( os.path.dirname(__file__), '../ecore/GeppettoCommonLibrary.xmi')) # The model URI resource = rset.get_resource(model_url) # We load the model self.geppetto_common_library = resource.contents[0] # We get the root
def test_resource_update_URI(): resource = Resource(uri=URI('test_uri')) assert resource.uri.plain == 'test_uri' resource.uri = URI('http://new_URI') assert resource.uri.plain == 'http://new_URI' resource.uri = 'http://newnewURI' assert resource.uri.plain == 'http://newnewURI' rset = ResourceSet() resource = rset.create_resource('http://test_URI') assert resource.uri.plain == 'http://test_URI' resource.uri = 'http://newURI' assert 'http://newURI' in rset.resources assert 'http://test_URI' not in rset.resources assert resource.uri.plain == 'http://newURI'
def test__resource_uriconverter_abstract(): a = AbstractURIConverter() u = URI('test') with pytest.raises(NotImplementedError): a.convert(u) with pytest.raises(NotImplementedError): a.can_handle(u)
def test_editing_domain_load_resource(): ecore_file = path.join('tests', 'xmi', 'xmi-tests', 'My.ecore') domain = EditingDomain() resource = domain.load_resource(URI(ecore_file)) assert resource.contents root = resource.contents[0] assert isinstance(root, EPackage)
def test_editing_domain_execute_command(): ecore_file = path.join('tests', 'xmi', 'xmi-tests', 'My.ecore') domain = EditingDomain() resource = domain.load_resource(URI(ecore_file)) root = resource.contents[0] cmd = Set(root, 'name', 'new_name') domain.execute(cmd) assert root.name == 'new_name'
def import_file(self, uri_or_filename): if isinstance(uri_or_filename, str): if uri_or_filename[:4] == 'http': uri = HttpURI(uri_or_filename) else: uri = URI(uri_or_filename) else: uri = uri_or_filename return self.add_uri(uri)
def main(debug=False): # Go to working directory if str(os.path.dirname(__file__)) != '': os.chdir(str(os.path.dirname(__file__))) # Count arguments if len(sys.argv) < 2 or len(sys.argv) > 3: print( 'Please give at least an GRS file name (input model) and optionaly an XMI file name (output model)' ) sys.exit(0) # Obtain GRS model filename # ~ grs_filename = os.path.relpath(sys.argv[1], str(os.getcwd())) grs_filename = os.path.relpath(sys.argv[1], str(os.getcwd())) # Obtain XMI model filename if len(sys.argv) == 3: xmi_filename = sys.argv[2] else: xmi_filename = '../models/generos.xmi' # Load Grammar dsl_metamodel = metamodel_from_file('generos.tx', debug=False) # Convert importURI string (if needed) def conv(i): return i.replace(".", "/") + ".grs" # Scope Providers dsl_metamodel.register_scope_providers( {"*.*": scoping_providers.FQNImportURI(importAs=True)}) # Recursive function that loads the commands of the imported models to the main model def resolve_imports(current_model): # Load imported models imports = get_children_of_type("Import", current_model) for i in imports: for m in i._tx_loaded_models: # Recursively attach commands of more deep imports m = resolve_imports(m) # Attach commands of the submodels (imports) to the main model current_model.commands.extend(m.commands) return current_model # Load Model model = dsl_metamodel.model_from_file(grs_filename) resolve_imports(model) # Fire up the generation system = RosSystem() system.interpret(model) #create rset global_registry[Ecore.nsURI] = Ecore rset = ResourceSet() rset.metamodel_registry[metageneros.nsURI] = metageneros model_res = rset.create_resource(URI(xmi_filename)) # Save model_res.append(system.rosystem) model_res.save()
def test_resource_swap(simplemm): root = simplemm.Root() a = simplemm.A() b = simplemm.B() root.a.append(a) root.b.append(b) r1 = XMIResource(URI('resource1.xmi')) r2 = XMIResource(URI('resource2.xmi')) r1.append(root) assert root.eResource is r1 assert a.eResource is root.eResource assert b.eResource is root.eResource r2.append(root) assert root.eResource is r2 assert a.eResource is root.eResource assert b.eResource is root.eResource
def save(self, filename): ''' Saves the energy system to a file ''' uri = URI(filename) fileresource = self.rset.create_resource(uri) # add the current energy system fileresource.append(self.es) # save the resource fileresource.save() # return the resource return fileresource
def test_editing_domain_execute_command_bad_eding_domain(): ecore_file = path.join('tests', 'xmi', 'xmi-tests', 'My.ecore') resource = ResourceSet().get_resource(URI(ecore_file)) root = resource.contents[0] cmd = Set(root, 'name', 'new_name') domain = EditingDomain() with pytest.raises(ValueError): domain.execute(cmd)
def saveModel(model): # create a resourceSet that hold the contents of the gdm.ecore model and the instances we use/create rset = ResourceSet() # register the metamodel (available in the generated files) rset.metamodel_registry[gdm.nsURI] = gdm rset.resource_factory['gdm'] = lambda uri: XMIResource(uri) resource = rset.create_resource(URI('Static_model_test.xmi')) resource.append(model) resource.save() return
def load_file(self, uri_or_filename) -> (esdl.EnergySystem, []): """Loads a EnergySystem file or URI into a new resourceSet :returns EnergySystem and the parse warnings as a tuple (es, parse_info)""" if isinstance(uri_or_filename, str): if uri_or_filename[:4] == 'http': uri = HttpURI(uri_or_filename) else: uri = URI(uri_or_filename) else: uri = uri_or_filename return self.load_uri(uri)
def load_file(self, uri_or_filename): """Loads a EnergySystem file or URI into a new resourceSet :returns EnergySystem the first item in the resourceSet""" if isinstance(uri_or_filename, str): if uri_or_filename[:4] == 'http': uri = HttpURI(uri_or_filename) else: uri = URI(uri_or_filename) else: uri = uri_or_filename return self.load_uri(uri)
def import_file(self, uri_or_filename): """ :returns: EnergySystem and the parse warnings as a tuple (es, parse_info) """ if isinstance(uri_or_filename, str): if uri_or_filename[:4] == 'http': uri = HttpURI(uri_or_filename) else: uri = URI(uri_or_filename) else: uri = uri_or_filename return self.add_uri(uri)
def get_infrastructure_model_access(ecore_uri='./infrastructure.ecore', http_uri=False): """Return handler to instanciate classes of a metamodel.""" rset = ResourceSet() uri = URI(ecore_uri) if http_uri: uri = HttpURI(ecore_uri) resource = rset.get_resources(uri) mm_root = resource.contents[0] # We get the root (an EPackage here) return DynamicEPackage(mm_root)
def run(self, clean_mappings_cache=True, resource_set=None, **kwargs): sp = inspect.currentframe() context = TransformationExecution(self, resource_set) sp.f_globals["mycontext"] = context params = {} for in_model in self.inputs_def: try: param = kwargs.pop(in_model) if isinstance(param, Ecore.EObject): if param.eResource: resource = param.eResource else: rset = context.resource_set resource = rset.create_resource(URI(in_model)) resource.append(param) elif isinstance(param, Resource): resource = param else: resource = load_model(param) setattr(context.inputs, in_model, resource) params[in_model] = resource if in_model in self.inouts: setattr(context.outputs, in_model, resource) params[in_model] = resource except KeyError as e: raise type( e)(str(e) + ' is a missing input model'.format(in_model)) from None for out_model in list(set(self.outputs_def) - set(self.inouts)): resource = context.resource_set.create_resource(URI(out_model)) setattr(context.outputs, out_model, resource) params[out_model] = resource context.primary_output = context.outputs[0] self._main(**params) if clean_mappings_cache: for mapping in self.registed_mapping: mapping.cache.cache_clear() return context