1 package hudson; 2 3 import com.thoughtworks.xstream.XStream; 4 import com.thoughtworks.xstream.converters.ConversionException; 5 import com.thoughtworks.xstream.converters.Converter; 6 import com.thoughtworks.xstream.io.StreamException; 7 import com.thoughtworks.xstream.io.xml.XppReader; 8 import hudson.model.Descriptor; 9 import hudson.util.AtomicFileWriter; 10 import hudson.util.IOException2; 11 import hudson.util.XStream2; 12 13 import java.io.BufferedReader ; 14 import java.io.File ; 15 import java.io.FileInputStream ; 16 import java.io.IOException ; 17 import java.io.InputStreamReader ; 18 import java.io.Reader ; 19 import java.util.logging.Logger ; 20 21 70 public final class XmlFile { 71 private final XStream xs; 72 private final File file; 73 74 public XmlFile(File file) { 75 this(DEFAULT_XSTREAM,file); 76 } 77 78 public XmlFile(XStream xs, File file) { 79 this.xs = xs; 80 this.file = file; 81 } 82 83 public File getFile() { 84 return file; 85 } 86 87 90 public Object read() throws IOException { 91 LOGGER.fine("Reading "+file); 92 Reader r = new BufferedReader (new InputStreamReader (new FileInputStream (file), "UTF-8")); 93 try { 94 return xs.fromXML(r); 95 } catch(StreamException e) { 96 throw new IOException2("Unable to read "+file,e); 97 } catch(ConversionException e) { 98 throw new IOException2("Unable to read "+file,e); 99 } finally { 100 r.close(); 101 } 102 } 103 104 111 public Object unmarshal( Object o ) throws IOException { 112 Reader r = new BufferedReader (new InputStreamReader (new FileInputStream (file),"UTF-8")); 113 try { 114 return xs.unmarshal(new XppReader(r),o); 115 } catch (StreamException e) { 116 throw new IOException2(e); 117 } catch(ConversionException e) { 118 throw new IOException2("Unable to read "+file,e); 119 } finally { 120 r.close(); 121 } 122 } 123 124 public void write( Object o ) throws IOException { 125 AtomicFileWriter w = new AtomicFileWriter(file); 126 try { 127 w.write("<?xml version='1.0' encoding='UTF-8'?>\n"); 128 xs.toXML(o,w); 129 w.commit(); 130 } catch(StreamException e) { 131 throw new IOException2(e); 132 } finally { 133 w.close(); 134 } 135 } 136 137 public boolean exists() { 138 return file.exists(); 139 } 140 141 public void mkdirs() { 142 file.getParentFile().mkdirs(); 143 } 144 145 public String toString() { 146 return file.toString(); 147 } 148 149 152 private static final XStream DEFAULT_XSTREAM = new XStream2(); 153 154 private static final Logger LOGGER = Logger.getLogger(XmlFile.class.getName()); 155 } 156 | Popular Tags |