1 20 package org.openi.xml; 21 22 import com.thoughtworks.xstream.XStream; 23 import com.thoughtworks.xstream.converters.ConversionException; 24 import org.apache.log4j.LogManager; 25 import org.apache.log4j.Logger; 26 import java.io.File ; 27 import java.io.FileNotFoundException ; 28 import java.io.FileReader ; 29 import java.io.FileWriter ; 30 import java.io.IOException ; 31 import java.io.Writer ; 32 33 34 40 public class BeanStorage { 41 private static Logger logger = LogManager.getLogger(BeanStorage.class); 42 private XStream dataBinder; 43 44 public BeanStorage() { 45 this.dataBinder = new XStream(); 46 } 47 48 public String toXmlString(Object bean) { 49 return this.dataBinder.toXML(bean); 50 } 51 52 public synchronized void saveBeanToFile(String filename, Object bean) 54 throws IOException { 55 logger.debug("trying to save bean: to file: " + filename); 57 58 File file = new File (filename); 59 60 if (!file.exists()) { 61 File parentDir = file.getParentFile(); 62 63 if (!parentDir.exists()) { 64 parentDir.mkdirs(); 65 } 66 } 67 68 FileWriter writer = new FileWriter (file); 69 saveBean(writer, bean); 70 writer.flush(); 71 writer.close(); 72 } 73 74 public synchronized void saveBean(Writer writer, Object bean) 76 throws IOException { 77 logger.debug("saveBean: " + bean.getClass().getName() + " to writer"); 78 this.dataBinder.toXML(bean, writer); 79 } 80 81 87 public Object restoreBeanFromFile(String filename) 88 throws IOException { 89 logger.debug("restoring bean from file: " + filename); 90 91 File analysisConfigFile = new File (filename); 92 93 if (!analysisConfigFile.exists()) { 94 throw new FileNotFoundException ("could not find at: " + filename); 95 } 96 97 FileReader reader = new FileReader (analysisConfigFile); 98 Object obj = null; 99 100 try { 101 obj = this.dataBinder.fromXML(reader); 102 reader.close(); 103 } catch (ConversionException e) { 104 throw new IOException ( 110 "Trouble restoring bean, caught ConversionException: " 111 + e.getMessage()); 112 } 113 114 return obj; 115 } 116 117 125 public Object restoreBeanFromFile(String filename, Object root) 126 throws IOException { 127 logger.debug("restoring bean from file: " + filename); 128 129 File analysisConfigFile = new File (filename); 130 131 if (!analysisConfigFile.exists()) { 132 throw new FileNotFoundException ("could not find at: " + filename); 133 } 134 135 FileReader reader = new FileReader (analysisConfigFile); 136 Object obj = null; 137 138 try { 139 obj = this.dataBinder.fromXML(reader, root); 140 reader.close(); 141 } catch (ConversionException e) { 142 throw new IOException ( 148 "Trouble restoring bean, caught ConversionException: " 149 + e.getMessage()); 150 } 151 152 return obj; 153 } 154 155 public synchronized void deleteFile(String filename) { 157 logger.info("trying to delete file: " + filename); 158 159 File file = new File (filename); 160 161 if (file.exists()) { 162 logger.debug("delete result: " + file.delete()); 163 } 164 } 165 } 166 | Popular Tags |