1 package org.ozoneDB.adminGui.feature.data; 9 10 import org.ozoneDB.ExternalDatabase; 11 import org.ozoneDB.ExternalTransaction; 12 import org.ozoneDB.adminGui.main.AdminGui; 13 import org.ozoneDB.xml.util.SAXChunkConsumer; 14 import org.ozoneDB.xml.util.SAXChunkProducer; 15 import org.ozoneDB.xml.util.SAXChunkProducerDelegate; 16 import org.ozoneDB.core.admin.Admin; 17 import org.apache.xml.serialize.XMLSerializer; 18 import org.apache.xml.serialize.OutputFormat; 19 import org.xml.sax.InputSource ; 20 import org.xml.sax.helpers.ParserAdapter ; 21 22 import javax.xml.parsers.SAXParserFactory ; 23 import javax.xml.parsers.SAXParser ; 24 import java.io.*; 25 26 29 public final class BackupWorker { 30 31 public static void backup(File backupFile) throws Exception { 32 ExternalDatabase db = AdminGui.instance().getDb(); 33 Admin admin = db.admin(); 34 35 ExternalTransaction tx = db.newTransaction(); 36 tx.begin(); 37 38 try { 39 admin.beginBackup(); 40 41 if (backupFile.exists() && !backupFile.canWrite()) { 42 throw new Exception ("File " + backupFile.getAbsolutePath() + " exists and is not writable"); 43 } 44 45 OutputStream out = new FileOutputStream(backupFile); 46 OutputFormat outputFormat = new OutputFormat("xml", "UTF-8", true); 47 XMLSerializer serializer = new XMLSerializer(out, outputFormat); 49 SAXChunkConsumer consumer = new SAXChunkConsumer(serializer.asContentHandler()); 51 52 byte[] bytes = null; 53 int i = 0; 54 while ((bytes = admin.nextBackupChunk()) != null) { 55 System.out.println("writing chunk " + ++i); 56 consumer.processChunk(bytes); 57 } 58 out.flush(); 59 out.close(); 60 tx.commit(); 61 System.out.println("done"); 62 } catch (Exception e) { 63 tx.rollback(); 64 throw e; 65 } 66 67 } 68 69 public static void restore(File backupFile) throws Exception { 70 ExternalDatabase db = AdminGui.instance().getDb(); 71 final Admin admin = db.admin(); 72 ExternalTransaction tx = db.newTransaction(); 73 tx.begin(); 74 75 try { 76 77 if (!backupFile.exists() || !backupFile.canRead()) { 78 throw new Exception ("File " + backupFile.getAbsolutePath() + " is not accessible"); 79 } 80 81 admin.beginRestore(); 82 83 try { 84 InputStream in = new FileInputStream(backupFile); 85 InputSource xmlSource = new InputSource (in); 86 SAXChunkProducer producer = new SAXChunkProducer(new SAXChunkProducerDelegate() { 87 public void processChunk(SAXChunkProducer producer) throws Exception { 88 admin.processRestoreChunk(producer.chunkStream().toByteArray()); 89 } 90 }); 91 SAXParserFactory parserFactory = SAXParserFactory.newInstance(); 92 SAXParser parser = parserFactory.newSAXParser(); 93 ParserAdapter adapter = new ParserAdapter (parser.getParser()); 94 adapter.setContentHandler(producer); 95 adapter.parse(xmlSource); 96 tx.commit(); 97 } finally { 98 admin.processRestoreChunk(null); 99 } 100 } catch (Exception e) { 101 tx.rollback(); 102 throw e; 103 } 104 } 105 } 106 | Popular Tags |