1 | package de.uka.ipd.sdq.scheduler.tools; |
2 | |
3 | import java.io.File; |
4 | import java.io.IOException; |
5 | import java.util.Collections; |
6 | |
7 | import org.eclipse.emf.common.util.URI; |
8 | import org.eclipse.emf.ecore.EObject; |
9 | import org.eclipse.emf.ecore.resource.Resource; |
10 | import org.eclipse.emf.ecore.resource.ResourceSet; |
11 | import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; |
12 | import org.eclipse.emf.ecore.util.EcoreUtil; |
13 | import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; |
14 | |
15 | import scheduler.SchedulerPackage; |
16 | |
17 | public class SchedulerTools { |
18 | |
19 | @SuppressWarnings("unchecked") |
20 | public static EObject loadFromXMI(String fileName) { |
21 | // Create a resource set to hold the resources. |
22 | ResourceSet resourceSet = new ResourceSetImpl(); |
23 | |
24 | // Register the appropriate resource factory to handle all file |
25 | // extentions. |
26 | resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() |
27 | .put(Resource.Factory.Registry.DEFAULT_EXTENSION, |
28 | new XMIResourceFactoryImpl()); |
29 | |
30 | // Register the package to ensure it is available during loading. |
31 | resourceSet.getPackageRegistry().put(SchedulerPackage.eNS_URI, |
32 | SchedulerPackage.eINSTANCE); |
33 | |
34 | // Construct the URI for the instance file. |
35 | // The argument is treated as a file path only if it denotes an existing |
36 | // file. Otherwise, it's directly treated as a URL. |
37 | File file = new File(fileName); |
38 | URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()) |
39 | : URI.createURI(fileName); |
40 | |
41 | // Demand load resource for this file. |
42 | Resource resource = resourceSet.getResource(uri, true); |
43 | System.out.println("Loaded " + uri); |
44 | |
45 | EObject eObject = (EObject) resource.getContents().iterator().next(); |
46 | return EcoreUtil.getRootContainer(eObject); |
47 | } |
48 | |
49 | @SuppressWarnings("unchecked") |
50 | public static void saveToXMI(EObject objectToSave, String fileName) { |
51 | // Create a resource set. |
52 | ResourceSet resourceSet = new ResourceSetImpl(); |
53 | |
54 | // Register the default resource factory -- only needed for stand-alone! |
55 | resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap() |
56 | .put(Resource.Factory.Registry.DEFAULT_EXTENSION, |
57 | new XMIResourceFactoryImpl()); |
58 | |
59 | // Get the URI of the model file. |
60 | URI fileURI = URI.createFileURI(new File(fileName).getAbsolutePath()); |
61 | |
62 | // Create a resource for this file. |
63 | Resource resource = resourceSet.createResource(fileURI); |
64 | |
65 | // Add the book and writer objects to the contents. |
66 | resource.getContents().add(objectToSave); |
67 | |
68 | // Save the contents of the resource to the file system. |
69 | try { |
70 | resource.save(Collections.EMPTY_MAP); |
71 | } catch (IOException e) { |
72 | } |
73 | } |
74 | |
75 | } |