Last active
December 14, 2016 15:39
-
-
Save pvlasov/dec50db2d0e8e33aac19f7f18e6e081e to your computer and use it in GitHub Desktop.
Loading/Storing Ecore model to/from XMI file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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