javaemf

Saving an EMF Model


I m new to EMF and trying to save an EMF Model as Follows:-

public void saveData(File file, Device device) throws IOException {  

        final ResourceSet resourceSet = new ResourceSetImpl();

        // Use XMI resource
        System.out.println("file path in  saveData " +file.getPath());          
        Resource xmiResource = resourceSet.createResource(URI.createFileURI(file.getPath() + ".xmi"));
        xmiResource.getContents().add(device);
        xmiResource.save(null);

        // Use XML resource instead
        Resource xmlResource = resourceSet.createResource(URI.createFileURI(file.getPath() + ".xml"));
        xmlResource.getContents().add(device);
        xmlResource.save(null);

        }

But no file is created in the designated Path. Code for Loading is:-

public Device loadData(String fileName) {


        final ResourceSet resourceSet = new ResourceSetImpl();


            // Use XMI resource

            Resource xmiResource;
            System.out.println("filename" + fileName);
            try {
            xmiResource = resourceSet.getResource(URI.createFileURI(fileName + ".xmi"),true);

                xmiResource.load(null);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            return (Device)xmiResource.getContents().get(0);

        }

which gives the following Error: java.lang.RuntimeException: Cannot create a resource for 'file:/C:/Users/Desktop/filename.xmi'; a registered resource factory is needed


Solution

  • Used XMiResourceImpl.It is Working fine for Now.

    XMIResourceImpl resource = new XMIResourceImpl();
     File source = new File(fileName);
     resource.load( new FileInputStream(source), new HashMap<Object,Object>());
     Data data = (Data)resource.getContents().get(0);
    

    for saving the model

    Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
    Map<String, Object> m = reg.getExtensionToFactoryMap();
    m.put("key", new XMIResourceFactoryImpl());
    ResourceSet resSet = new ResourceSetImpl();
    Resource resource = resSet.createResource(URI.createFileURI(fileName));
    resource.getContents().add(data);
    resource.save(Collections.EMPTY_MAP);