package exercises; import java.io.File; import java.io.IOException; import java.util.Iterator; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.ResourceSet; import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; import com.example.po.DocumentRoot; import com.example.po.Item; import com.example.po.POPackage; import com.example.po.PurchaseOrder; import com.example.po.USAddress; import com.example.po.util.POResourceFactoryImpl; public class Exercise2 { public static void main(String[] args) throws IOException { // Create a resource set to hold the resources. // ResourceSet resourceSet = new ResourceSetImpl(); // Register the appropriate resource factory to handle all file extentions. // resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put( Resource.Factory.Registry.DEFAULT_EXTENSION, new POResourceFactoryImpl()); // Register the package to ensure it is available during loading. // resourceSet.getPackageRegistry().put(POPackage.eNS_URI, POPackage.eINSTANCE); // Create a resource and load an existing po.xml file using an absolute URI. // If you know the actual path, the URI could be something simpler like: // URI uri = URI.createFileURI("/home/data/po.xml"); // URI uri = URI.createFileURI(new File("data/po.xml").getAbsolutePath()); Resource resource = resourceSet.createResource(uri); resource.load(null); // Retrieve the order. // DocumentRoot document = (DocumentRoot)resource.getContents().get(0); PurchaseOrder order = document.getOrder(); // Retrieve the shipTo address from the order and print out the address data. // USAddress address = order.getShipTo(); System.out.println("name: " + address.getName()); System.out.println("street: " + address.getStreet()); System.out.println("city: " + address.getCity()); System.out.println("state: " + address.getState()); System.out.println("zip: " + address.getZip()); // Remove the discontinued item with SKU 'STV999876' from the order. // Item removedItem = null; for (Iterator iter = order.getItems().iterator(); iter.hasNext();) { Item item = (Item)iter.next(); if ("STV999876".equals(item.getPartNum())) { removedItem = item; iter.remove(); } } // Change the order's comment to indicate that the discontinued item has been removed. // if (removedItem != null) { order.setComment(removedItem.getProductName() + " (" + removedItem.getPartNum() + ") is discontinued and has been removed from the order."); } // Serialize the updated content to the console, then to a "po-updated.xml" file. // resource.save(System.out, null); resource = resourceSet.createResource(URI.createFileURI("po-updated.xml").resolve(uri)); resource.getContents().add(document); resource.save(null); } }