1 /*** 2 * Ambient - A music player for the Android platform 3 Copyright (C) 2007 Martin Vysny 4 5 This program is free software: you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation, either version 3 of the License, or 8 (at your option) any later version. 9 10 This program is distributed in the hope that it will be useful, 11 but WITHOUT ANY WARRANTY; without even the implied warranty of 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 GNU General Public License for more details. 14 15 You should have received a copy of the GNU General Public License 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 */ 18 package sk.baka.ambient.commons; 19 20 import java.io.File; 21 import java.io.FileOutputStream; 22 import java.io.IOException; 23 import java.io.Serializable; 24 25 26 /*** 27 * Stores objects as files. The file content is composed of a serialized form of 28 * the object. 29 * 30 * @author Martin Vysny 31 */ 32 public final class ObjectStorage extends AbstractFileStorage { 33 /*** 34 * The extension in the form ".ext" 35 */ 36 private final String ext; 37 38 /*** 39 * Creates new playlist storage. 40 * 41 * @param ext 42 * the extension in the form ".ext" 43 */ 44 public ObjectStorage(final String ext) { 45 super(null, ext); 46 this.ext = ext; 47 } 48 49 /*** 50 * Loads (deserializes) a stored playlist. 51 * 52 * @param name 53 * the name 54 * @return deserialized player state. 55 * @throws IOException 56 * if something happens during the deserialization. 57 */ 58 public Serializable loadObject(final String name) throws IOException { 59 final File file = getCacheFile(name); 60 return MiscUtils.deserializeFromFile(file); 61 } 62 63 /*** 64 * Stores (serializes) a stored playlist. 65 * 66 * @param name 67 * the name 68 * @param object 69 * the object to serialize. 70 * @throws IOException 71 * if something happens during the deserialization. 72 */ 73 public void saveObject(final String name, final Serializable object) 74 throws IOException { 75 final FileOutputStream out; 76 final boolean created=!contains(name); 77 if (created) { 78 out = createFile(name, ext); 79 } else { 80 out = new FileOutputStream(getCacheFile(name)); 81 } 82 MiscUtils.serialize(object, out); 83 registerFile(name, ext); 84 } 85 86 /*** 87 * Checks if a playlist with given name is present in the storage. 88 * 89 * @param name 90 * the file name 91 * @return <code>true</code> if such playlist is available, 92 * <code>false</code> otherwise. 93 */ 94 public boolean contains(String name) { 95 return theCache.containsKey(name); 96 } 97 98 /*** 99 * Deletes given playlist. Does nothing if the file does not exist. 100 * 101 * @param name 102 * the file name 103 */ 104 public void delete(final String name) { 105 if (!contains(name)) 106 return; 107 removeFile(getCacheFile(name)); 108 } 109 }