01: /*
02: $Header: /cvsroot/xorm/xorm/src/org/xorm/datastore/xml/DocumentHolder.java,v 1.2 2003/07/15 22:53:10 wbiggs Exp $
03:
04: This file is part of XORM.
05:
06: XORM is free software; you can redistribute it and/or modify
07: it under the terms of the GNU General Public License as published by
08: the Free Software Foundation; either version 2 of the License, or
09: (at your option) any later version.
10:
11: XORM is distributed in the hope that it will be useful,
12: but WITHOUT ANY WARRANTY; without even the implied warranty of
13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: GNU General Public License for more details.
15:
16: You should have received a copy of the GNU General Public License
17: along with XORM; if not, write to the Free Software
18: Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19: */
20: package org.xorm.datastore.xml;
21:
22: import java.io.FileOutputStream;
23: import java.io.IOException;
24: import java.io.OutputStream;
25:
26: import java.net.URL;
27: import java.net.URLConnection;
28: import java.net.MalformedURLException;
29:
30: import org.jdom.Document;
31: import org.jdom.JDOMException;
32: import org.jdom.input.SAXBuilder;
33: import org.jdom.output.XMLOutputter;
34:
35: /**
36: * Wraps a JDOM Document and allows transactional access.
37: *
38: * @author Wes Biggs
39: */
40: public class DocumentHolder {
41: private URL url;
42: private Document document;
43:
44: public DocumentHolder(URL url) {
45: this .url = url;
46: try {
47: document = new SAXBuilder().build(url);
48: } catch (JDOMException e) {
49: e.printStackTrace();
50: } catch (IOException e) {
51: e.printStackTrace();
52: }
53: }
54:
55: /**
56: * Returns a cloned copy of the document.
57: */
58: public Document checkout() {
59: return (Document) document.clone();
60: }
61:
62: /**
63: * Accepts the changes from the document. If possible, rewrites
64: * the content. Changes are synchronized but not checked; if two
65: * concurrent threads make different changes, the last one to call
66: * checkin() will win. This effectively gives the process a
67: * transaction isolation level equivalent to TRANSACTION_READ_COMMITTED.
68: */
69: public void checkin(Document document) {
70: this .document = document;
71:
72: synchronized (url) {
73: OutputStream outputStream = null;
74: try {
75: if ("file".equals(url.getProtocol())) {
76: outputStream = new FileOutputStream(url.getFile());
77: } else {
78: // Try to set "doOutput", may not work
79: URLConnection connection = url.openConnection();
80: connection.setDoOutput(true);
81: outputStream = connection.getOutputStream();
82: }
83: new XMLOutputter(" ", true).output(document,
84: outputStream);
85: outputStream.flush();
86: outputStream.close();
87: } catch (IOException e) {
88: e.printStackTrace();
89: }
90: } // synchronized
91: }
92: }
|