1 56 57 package org.jdom.contrib.beans; 58 59 import java.io.File ; 60 import java.io.IOException ; 61 import java.io.PrintStream ; 62 import java.util.Iterator ; 63 import java.util.*; 64 import org.jdom.Document; 65 import org.jdom.Element; 66 import org.jdom.JDOMException; 67 import org.jdom.input.SAXBuilder; 68 import org.jdom.output.XMLOutputter; 69 70 76 119 public class JDOMBean { 120 121 122 private static final String DEFAULT_PARSER = 123 "org.apache.xerces.parsers.SAXParser"; 124 125 126 private String parser; 127 128 129 private SAXBuilder builder; 130 131 132 private Map files = new HashMap(); 133 134 135 private File fileRoot; 136 137 140 public JDOMBean() { 141 setParser(DEFAULT_PARSER); 142 } 143 144 147 public JDOMBean(String parser) { 148 setParser(parser); 149 } 150 151 159 public void setParser(String parser) { 160 this.parser = parser; 161 builder = new SAXBuilder(parser); 162 } 163 164 167 public String getParser() { 168 return parser; 169 } 170 171 175 public void setFileRoot(String root) { 176 if (!root.endsWith("/")) { 177 root = root + "/"; 178 } 179 this.fileRoot = new File (root); 180 System.out.println("fileroot=" + fileRoot); 181 } 182 183 186 public String getFileRoot() { 187 if (fileRoot == null) return null; 188 else return fileRoot.getAbsolutePath(); 189 } 190 191 209 public Document getDocument(String filename) throws JDOMException, IOException { 210 FileInfo info = (FileInfo) files.get(filename); 211 File file = getFile(filename); 212 if (info == null || 213 info.modified < file.lastModified()) 214 { 215 Document doc = builder.build(file); 216 info = new FileInfo(filename, file.lastModified(), doc); 217 files.put(filename, info); 218 } 219 return info.document; 220 } 221 222 225 public Element getRootElement(String file) throws JDOMException, IOException { 226 Document doc = getDocument(file); 227 if (doc != null) return doc.getRootElement(); 228 return null; 229 } 230 231 private File getFile(String filename) { 232 File file; 233 if (fileRoot == null) { 234 return new File (filename); 235 } 236 else { 237 return new File (fileRoot, filename); 238 } 239 } 240 241 244 class FileInfo { 245 String name; 246 long modified; 247 Document document; 248 public FileInfo(String name, long modified, Document document) { 249 this.name = name; 250 this.modified = modified; 251 this.document = document; 252 } 253 } 254 255 public static void main(String [] args) throws IOException , JDOMException { 258 int i=0; 259 JDOMBean bean; 260 if (args[i].equals("-parser")) { 261 ++i; 262 bean = new JDOMBean(args[i]); 263 i++; 264 } 265 else { 266 bean = new JDOMBean(); 267 } 268 269 XMLOutputter out = new XMLOutputter(); 270 271 for (; i<args.length; ++i) { 272 Document doc = bean.getDocument(args[i]); 273 out.output(doc, System.out); 274 System.out.println(); 275 } 276 } 277 278 } 279 280 | Popular Tags |