Instantly share code, notes, and snippets.

Embed
What would you like to do?
Loading/Storing Ecore model to/from XMI file
// Dependencies: org.eclipse.emf.ecore, org.eclipse.emf.ecore.xmi
// Create a resource set to hold the resources.
// Create resource set or use existing
ResourceSet resourceSet = new ResourceSetImpl();
// Register the appropriate resource factory to handle all file extensions.
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
// Register the package to ensure it is available during loading.
resourceSet.getPackageRegistry().put(MyPackage.eNS_URI, MyPackage.eINSTANCE);
// Add custom URI handler(s) if required
URIHandler myURIHandler = new URIHandlerImpl() {
@Override
public boolean canHandle(URI uri) {
return true if handler can handle the uri
}
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
// Implement input stream creation for reading from URI.
return ...;
}
// Override createOutputStream and delete if needed.
};
resourceSet.getURIConverter().getURIHandlers().add(0, myURIHandler);
// Create a new model and output to console
Resource resource = resourceSet.createResource(URI.createURI("http:///My.modelextension"));
MyModelRoot root = MyModelFactory.eINSTANCE.createMyModelRoot();
resource.getContents().add(root);
resource.save(System.out, null);
// Load from file
File file = new File(...);
URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()): URI.createURI(...);
// Demand load resource for this file.
Resource resource = resourceSet.getResource(uri, true);
System.out.println("Loaded " + uri);
// Retrieve contents
for (EObject eObject : resource.getContents()) {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment