Loading an Ecore model without initializing all necessary packages or schemas

Here’s a small snippet of code to load an Ecore resource without having to initialize all the necessary packages needed to read all elements. This is useful if we’re interested in only a subset of the schema elements that are present in the Ecore model.

public static EList open(File file) throws IOException {
	ResourceSet resourceSet = new ResourceSetImpl();
 
	//Initialize the FSML Package information (ie. URI)
	MyPackageImpl.init();
 
	//Set OPTION_RECORD_UNKNOWN_FEATURE prior to calling getResource
	Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put(
		"*", new EcoreResourceFactoryImpl() {
			@Override
			public Resource createResource(URI uri) {
			XMIResourceImpl resource = (XMIResourceImpl) super.createResource(uri);
			resource.getDefaultLoadOptions().put(XMLResource.OPTION_RECORD_UNKNOWN_FEATURE, Boolean.TRUE);
			return resource;
		}
	});
 
	XMIResource resource = (XMIResource) resourceSet.getResource(
	URI.createFileURI(file.toString()),
	true);
 
	//Unknown elements will appear in this map
	System.out.println(resource.getEObjectToExtensionMap());
 
	resource.load(Collections.EMPTY_MAP);
	return resource.getContents();
}

Be aware that any unrecognized elements will be null in the retrieved Ecore model.

Leave a Comment

(required)
(will not be published) (required)
Comment Preview