Creating EMF Model instances programmatically
Goal: You have an EMF Ecore meta-model and now you want to create model instances programmatically and save them into files.
We illustrate this using the SISSy GAST Model.
You need the following imports:
import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
Here we import Root class and its factory (adapt this to import your own Root class and factory!):
import de.fzi.gast.core.Root; import de.fzi.gast.core.coreFactory;
The following method describes the steps for setting up of ResourceSet, Resource, Root, etc.:
public void setupAndSaveEMFInstanceResource() {
ResourceSet rs = new ResourceSetImpl();
// Here the resource is created, with fileextensions "gast" and "xml" (adapt this to use your own file extension).
Resource gastResource = createAndAddResource("C:/file.gast", new String[] {"gast", "xml"}, rs);
// The root object is created by using (adapt this to create your own root object)
Root root = coreFactory.eINSTANCE.createRoot();
gastResource.getContents().add(root);
saveResource(gastResource);
}
The following two methods can be used as helper methods for resource creation and resource saving.
public static Resource createAndAddResource(String outputFile, String[] fileextensions, ResourceSet rs) {
for (String fileext : fileextensions) {
rs.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileext, new XMLResourceFactoryImpl());
}
URI uri = URI.createFileURI(outputFile);
Resource resource = rs.createResource(uri);
((ResourceImpl)resource).setIntrinsicIDToEObjectMap(new HashMap());
return resource;
}
public static void saveResource(Resource resource) {
Map saveOptions = ((XMLResource)resource).getDefaultSaveOptions();
saveOptions.put(XMLResource.OPTION_CONFIGURATION_CACHE, Boolean.TRUE);
saveOptions.put(XMLResource.OPTION_USE_CACHED_LOOKUP_TABLE, new ArrayList());
try {
resource.save(saveOptions);
} catch (IOException e) {
throw new RuntimeException(e);
}
}