1 4 package org.oddjob.persist; 5 6 import java.io.File ; 7 import java.io.FileInputStream ; 8 import java.io.FileNotFoundException ; 9 import java.io.FileOutputStream ; 10 import java.io.IOException ; 11 import java.io.InputStream ; 12 import java.io.ObjectInput ; 13 import java.io.ObjectInputStream ; 14 import java.io.ObjectOutput ; 15 import java.io.ObjectOutputStream ; 16 import java.io.OutputStream ; 17 18 import org.apache.log4j.Logger; 19 20 26 public class SerializePersister extends PersisterBase { 27 private static final Logger logger = Logger.getLogger(SerializePersister.class); 28 29 private final static String EXTENSION = ".ser"; 30 31 36 private File directory; 37 38 43 public void setDir(File dir) { 44 this.directory = dir; 45 } 46 47 52 public File getDir() { 53 return this.directory; 54 } 55 56 60 public void persist(String id, Object o) throws OddjobPersistException { 61 62 File file = fileFor(id); 63 try { 64 OutputStream os = new FileOutputStream (file); 65 ObjectOutput oo = new ObjectOutputStream (os); 66 oo.writeObject(o); 67 oo.close(); 68 logger.debug("Saved [" + o + "], id [" + id 69 + "] to file ][" 70 + file + "]."); 71 } 72 catch (FileNotFoundException e) { 73 throw new OddjobPersistException("Check directory exists!", e); 74 } 75 catch (IOException e) { 76 throw new OddjobPersistException("Failed writing object id [" 77 + id + "], class [" + o.getClass().getName() 78 + "], object [" + o + "]." 79 , e); 80 } 81 } 82 83 87 public void remove(String id) { 88 File f = fileFor(id); 89 if (f.exists()) { 90 f.delete(); 91 } 92 } 93 94 98 public Object restore(String id) throws OddjobPersistException { 99 100 File f = fileFor(id); 101 if (!f.exists()) { 102 return null; 103 } 104 try { 105 InputStream is = new FileInputStream (f); 106 ObjectInput oi = new ObjectInputStream (is); 107 Object o = oi.readObject(); 108 oi.close(); 109 logger.debug("Loaded [" + o + "] from [" + f + "]."); 110 return o; 111 } 112 catch (FileNotFoundException e) { 113 throw new OddjobPersistException("Check file exists!", e); 114 } 115 catch (IOException e) { 116 throw new OddjobPersistException("Failed reading object.", e); 117 } 118 catch (ClassNotFoundException e) { 119 throw new OddjobPersistException("Failed to load object.", e); 120 } 121 } 122 123 File fileFor(String id) { 124 return new File (directory, id + EXTENSION); 125 } 126 } 127 | Popular Tags |