Search code examples
loadpersistemfxmi

ClassCastException while loading XMI resource from EMF model


I want to load an EMF model resource which was persistend before from an Eclipse Plug-in Environment. I tried as follows.

// obtain a new resource set

ResourceSet resSet = new ResourceSetImpl();

// get the resource 

resSet.getResource(URI.createURI(location), true);

location is a path relative to the platform, e.g. platform:/resource/Project/default.mymodel

When I try to get the resource using URI.createURI(...) I get a ClassCastException: "MymodelFactoryImpl cannot be cast to org.eclipse.emf.ecore.resource.Resource$Factory".

I cannot explain this. Can somebody please help me?

I already tried URI.createFileURI(location). This results in an IllegalArgumentException: "invalid relative pathName".

Regards

The stack trace looks as follows. java.lang.ClassCastException: de.uka.ipd.sdq.pcm.usagemodel.impl.UsagemodelFactoryImpl cannot be cast to org.eclipse.emf.ecore.resource.Resource$Factory at org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl.convert(ResourceFactoryRegistryImpl.java:94) at org.eclipse.emf.ecore.resource.impl.ResourceSetImpl$2.delegatedGetFactory(ResourceSetImpl.java:458) at org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl.getFactory(ResourceFactoryRegistryImpl.java:145) at org.eclipse.emf.ecore.resource.impl.ResourceFactoryRegistryImpl.getFactory(ResourceFactoryRegistryImpl.java:86) at org.eclipse.emf.ecore.resource.impl.ResourceSetImpl.createResource(ResourceSetImpl.java:431) at org.eclipse.emf.ecore.resource.impl.ResourceSetImpl.demandCreateResource(ResourceSetImpl.java:243) at org.eclipse.emf.ecore.resource.impl.ResourceSetImpl.getResource(ResourceSetImpl.java:400)


Solution

  • This is not supposed to be necessary, because the plug-in environment does it for you, but try to register the resource factory:

    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(fileExtension, new ModelResourceFactoryImpl());
    

    where fileExtension is the file extension of the resource to be loaded and the ModelResourceFactoryImpl should be a generated class extending ResourceFactoryImpl.

    However, after removing the following code, the model can be loaded.

    // Register the XMI resource factory for my extension
    Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
    Map<String, Object> m = reg.getExtensionToFactoryMap();
    m.put("myextension", new XMIResourceFactoryImpl());
    

    It seems this was not the proper registration.