package buzzerproxy; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.concurrent.Semaphore; public class Serialization { private File cacheFile; private Semaphore semaphore = new Semaphore(1); /** * @param filename * @throws IOException */ public Serialization(String filename) throws IOException { if (filename == null) filename = "cache.ser.db"; cacheFile = new File(filename); if (!cacheFile.exists()) { cacheFile.createNewFile(); } } /** * @param filename * @param r */ public synchronized void writeCache( HashMap> c) { try { // Block semaphore.acquire(); try { // use buffering OutputStream file = new FileOutputStream(cacheFile); OutputStream buffer = new BufferedOutputStream(file); ObjectOutput output = new ObjectOutputStream(buffer); try { output.writeObject(c); } finally { output.close(); } } catch (IOException ex) { // Logger.getLogger(Serialization.class.getName()).log( // Level.SEVERE, "CacheWrite Performance Failed", ex); } // FREE semaphore.release(); } catch (Exception e) { e.printStackTrace(); } } /** * @param filename * @return */ @SuppressWarnings("unchecked") public synchronized HashMap> readCache() { HashMap> c = null; try { // Block semaphore.acquire(); try { // use buffering InputStream file = new FileInputStream(cacheFile); InputStream buffer = new BufferedInputStream(file); ObjectInput input = new ObjectInputStream(buffer); try { // deserialize the List c = (HashMap>) input .readObject(); // display its data } finally { input.close(); } } catch (ClassNotFoundException ex) { // Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, // "CacheRead Performance Failed", ex); } catch (IOException ex) { // Logger.getLogger(Serialization.class.getName()).log(Level.SEVERE, // "CacheRead IO Error", ex); } // FREE semaphore.release(); } catch (Exception e) { e.printStackTrace(); } return c; } // public HashMap> readCache(String // filename) { } // static class Serialization {