"Registered factory needed" exception when loading resource

paul picture paul · Jul 4, 2011 · Viewed 7.5k times · Source

I get the following exception:

 java.lang.RuntimeException: Cannot create a resource for 'file:/home/my_conf.xml'; a registered resource factory is needed

The "explosion" code is like this and stops at: resource = resourceSet.....

    ResourceSet resourceSet = new ResourceSetImpl();
    Resource resource = null;

    File f = new File(filename); 
    URI uri = URI.createFileURI(f.getAbsolutePath());

    if (!f.exists()) {
        throw new Exception(filename + " does not exist");

    } else {
        resource = resourceSet.getResource(uri, true);
        mapPrepConfiguration = (MapPrepConfiguration) resource.getContents().get(0);
    }

Is there anyone that has a clue?

Answer

greydet picture greydet · Jul 4, 2011

If you are running in standalone mode, you will have to manually register the factories to your resource set factory registry.
Add the following line after the creation of your resource set instance:

resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xml", new XMLResourceFactoryImpl());

Please see http://wiki.eclipse.org/EMF-FAQ#How_do_I_use_EMF_in_standalone_applications_.28such_as_an_ordinary_main.29.3F

For the Package not found issue there is two possibilities depending of your case:

  • If you are using a static metamodel (a java implementation is generated from your ecore model), you only have to access the corresponding Package instance for it to be loaded and registered into the global EMF package registry.

YourPackage packageInstance = YourPackage.eInstance;

  • If you are using a dynamic metamodel (no java code generated), you have to register it manually.
resourceSet.getPackageRegistry().put(yourPackage.getNsURI(), yourPackage);

With the previous code, you will have to previously retrieve the EPackage from your ecore model programmatically.