Programmatically load an Application.e4xmi

In case you were wondering or struggling, just like me, how one could possibly load an Application.e4xmi file out of a standalone Java application, here goes some code for you 🙂

import org.eclipse.e4.ui.internal.workbench.E4XMIResourceFactory;
 import org.eclipse.e4.ui.model.application.MApplication;
 import org.eclipse.e4.ui.model.application.impl.ApplicationPackageImpl;
 import org.eclipse.emf.common.util.URI;
 import org.eclipse.emf.ecore.resource.Resource;
 import org.eclipse.emf.ecore.resource.ResourceSet;
 import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;

public class LoadAppModel {

private static ResourceSet resourceSet = new ResourceSetImpl();

public static void main(String[] args) {
 ApplicationPackageImpl.init();
 URI uri = URI
 .createURI("file:///Users/marco/git/pharmacy_at/at.medevit.ecrit.pharmacy_at.application/Application.e4xmi");

resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
 .put("e4xmi", new E4XMIResourceFactory());

Resource res = resourceSet.getResource(uri, true);
 MApplication app = (MApplication) res.getContents().get(0);
 System.out.println(app.getElementId());
 }
 }

res.unload();

Be sure to include all the required bundles, especially in the OSGI context.

Update I just came up to a nasty problem: If you repeatedly iterate your application model, while modifying it, you need to be sure to unload the model each time you are done, otherwise lazy loading will not pick up the changes, as the model is already loaded.

To depict this I added the unload method to the code sample.