| 1 | package org.axdt.axdoc.model.util; |
|---|
| 2 | |
|---|
| 3 | import java.io.ByteArrayInputStream; |
|---|
| 4 | import java.io.IOException; |
|---|
| 5 | |
|---|
| 6 | import org.axdt.axdoc.model.AXDocFactory; |
|---|
| 7 | import org.axdt.axdoc.model.AXRoot; |
|---|
| 8 | import org.eclipse.emf.common.util.URI; |
|---|
| 9 | import org.eclipse.emf.ecore.EObject; |
|---|
| 10 | import org.eclipse.emf.ecore.resource.Resource; |
|---|
| 11 | import org.eclipse.emf.ecore.resource.ResourceSet; |
|---|
| 12 | |
|---|
| 13 | public class AXUtil { |
|---|
| 14 | private static AXDocXMLProcessor xmlProcessor = new AXDocXMLProcessor(); |
|---|
| 15 | private static AXDocFactory factory = AXDocFactory.eINSTANCE; |
|---|
| 16 | public static Resource createResource(String path) { |
|---|
| 17 | return xmlProcessor.createResourceSet().createResource(URI.createURI(path)); |
|---|
| 18 | } |
|---|
| 19 | public static Resource getOrCreateResource(ResourceSet set, EObject node, String path) { |
|---|
| 20 | Resource resource = node.eResource(); |
|---|
| 21 | if (resource == null) { |
|---|
| 22 | if (set == null) |
|---|
| 23 | set = xmlProcessor.createResourceSet(); |
|---|
| 24 | resource = set.createResource(URI.createURI(path)); |
|---|
| 25 | resource.getContents().add(node); |
|---|
| 26 | } else if (path != null) { |
|---|
| 27 | resource.setURI(URI.createURI(path)); |
|---|
| 28 | } |
|---|
| 29 | return resource; |
|---|
| 30 | } |
|---|
| 31 | public static String writeToString(EObject node) throws IOException { |
|---|
| 32 | ResourceSet set = (node.eResource() != null) ? node.eResource().getResourceSet() : null; |
|---|
| 33 | return writeToString(getOrCreateResource(set, node, null)); |
|---|
| 34 | } |
|---|
| 35 | public static String writeToString(Resource resource) throws IOException { |
|---|
| 36 | if (resource.getContents().isEmpty()) |
|---|
| 37 | return null; |
|---|
| 38 | return xmlProcessor.saveToString(resource, null); |
|---|
| 39 | } |
|---|
| 40 | public static Resource readFromString(String text, String path) throws IOException { |
|---|
| 41 | Resource resource = createResource(path); |
|---|
| 42 | ByteArrayInputStream inputStream = new ByteArrayInputStream(text.getBytes()); |
|---|
| 43 | resource.load(inputStream, null); |
|---|
| 44 | return resource; |
|---|
| 45 | } |
|---|
| 46 | public static AXRoot createRoot(String url, String basePath) { |
|---|
| 47 | return createRoot(null, url, basePath); |
|---|
| 48 | } |
|---|
| 49 | public static AXRoot createRoot(String name, String url, String resourceUrl) { |
|---|
| 50 | AXRoot root = factory.createAXRoot(); |
|---|
| 51 | root.setName(name); |
|---|
| 52 | root.setUrl(url); |
|---|
| 53 | ResourceSet set = xmlProcessor.createResourceSet(); |
|---|
| 54 | getOrCreateResource(set, root, resourceUrl); |
|---|
| 55 | return root; |
|---|
| 56 | } |
|---|
| 57 | } |
|---|