1 2 3 package com.db4odoc.f1.serialize; 4 5 import java.io.File ; 6 import java.io.FileReader ; 7 import java.io.FileWriter ; 8 9 import com.db4o.Db4o; 10 import com.db4o.ObjectContainer; 11 import com.db4o.ObjectSet; 12 import com.db4odoc.f1.Util; 13 import com.thoughtworks.xstream.XStream; 14 import com.thoughtworks.xstream.io.xml.DomDriver; 15 16 17 public class SerializeExample extends Util { 18 19 public static String XMLFILENAME = "formula1.xml"; 20 21 public static void main(String [] args) { 22 setObjects(); 23 exportToXml(); 24 importFromXml(); 25 } 26 28 public static void setObjects(){ 29 new File (Util.YAPFILENAME).delete(); 30 ObjectContainer db = Db4o.openFile(Util.YAPFILENAME); 31 try { 32 Car car = new Car("BMW", new Pilot("Rubens Barrichello")); 33 db.set(car); 34 car = new Car("Ferrari", new Pilot("Michael Schumacher")); 35 db.set(car); 36 } finally { 37 db.close(); 38 } 39 } 40 42 public static void exportToXml() 43 { 44 XStream xstream = new XStream(new DomDriver()); 45 try { 46 FileWriter xmlFile = new FileWriter (XMLFILENAME); 47 ObjectContainer db = Db4o.openFile(Util.YAPFILENAME); 48 try 49 { 50 ObjectSet result = db.query(Car.class); 51 Car[] cars = new Car[result.size()]; 52 for (int i = 0; i < result.size(); i++) 53 { 54 Car car = (Car)result.next(); 55 cars[i] = car; 56 } 57 String xml = xstream.toXML(cars); 58 xmlFile.write("<?xml version=\"1.0\"?>\n"+xml); 59 xmlFile.close(); 60 } 61 finally 62 { 63 db.close(); 64 } 65 } catch (Exception ex){ 66 System.out.println(ex.getMessage()); 67 } 68 } 69 71 public static void importFromXml() { 72 new File (Util.YAPFILENAME).delete(); 73 XStream xstream = new XStream(new DomDriver()); 74 try { 75 FileReader xmlReader = new FileReader (XMLFILENAME); 76 Car[] cars = (Car[]) xstream.fromXML(xmlReader); 77 ObjectContainer db; 78 for (int i = 0; i < cars.length; i++) { 79 db = Db4o.openFile(Util.YAPFILENAME); 80 try { 81 Car car = (Car) cars[i]; 82 db.set(car); 83 } finally { 84 db.close(); 85 } 86 } 87 db = Db4o.openFile(Util.YAPFILENAME); 88 try { 89 ObjectSet result = db.query(Pilot.class); 90 listResult(result); 91 result = db.query(Car.class); 92 listResult(result); 93 } finally { 94 db.close(); 95 } 96 xmlReader.close(); 97 } catch (Exception ex) { 98 System.out.println(ex.getMessage()); 99 } 100 } 101 103 public static void listResult(ObjectSet result) { 104 System.out.println(result.size()); 105 while(result.hasNext()) { 106 System.out.println(result.next()); 107 } 108 } 109 111 } 112 | Popular Tags |