Skip to content

Instantly share code, notes, and snippets.

@pvlasov
Last active December 14, 2016 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pvlasov/dec50db2d0e8e33aac19f7f18e6e081e to your computer and use it in GitHub Desktop.
Save pvlasov/dec50db2d0e8e33aac19f7f18e6e081e to your computer and use it in GitHub Desktop.
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