KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > SOFA > SOFAnet > Repository > XMLStorageItem


1 /*
2  * XMLStorageItem.java
3  *
4  * Created on 1. prosinec 2003, 21:21
5  */

6
7 package SOFA.SOFAnet.Repository;
8
9 import java.io.*;
10 import java.util.*;
11 import SOFA.Util.XML;
12 import org.w3c.dom.*;
13 import org.xml.sax.SAXException JavaDoc;
14 import SOFA.SOFAnet.Core.Reporter;
15
16 /**
17  * Implementation of storage item (StorageItem interface) as XML file.
18  *
19  * @author Ladislav Sobr
20  */

21 public abstract class XMLStorageItem implements StorageItem, Serializable
22 {
23   protected String JavaDoc name;
24   protected File file;
25   protected boolean loaded;
26   protected String JavaDoc rootTag;
27   
28   /** Creates a new instance of XMLStorageItem */
29   public XMLStorageItem(String JavaDoc name, File file, String JavaDoc rootTag)
30   {
31     loaded = false;
32     this.name = name;
33     this.file = file;
34     this.rootTag = rootTag;
35   }
36   
37   public boolean isLoaded()
38   {
39     return loaded;
40   }
41   
42   public void setLoaded(boolean loaded)
43   {
44     if (this.loaded != loaded)
45     {
46       this.loaded = loaded;
47       reset();
48       if (loaded) loadFromStorage();
49     }
50   }
51   
52   public void loadFromStorage()
53   {
54     try
55     {
56       Document doc = XML.parse(file);
57       Element root = doc.getDocumentElement();
58       loadFromXML(root);
59       loaded = true;
60     }
61     catch (IOException e)
62     {
63       Reporter.error("Load of '" + rootTag + "' XML format from file '" + file + "' failed", e);
64       reset();
65       loaded = false;
66     }
67     catch (SAXException JavaDoc e)
68     {
69       Reporter.error("Parsing of '" + rootTag + "' XML format from file '" + file + "' failed" + e);
70       reset();
71       loaded = false;
72     }
73   }
74   
75   public void saveToStorage()
76   {
77     loaded = true;
78     if (file == null) return;
79     try
80     {
81       Document doc = XML.newDocument();
82       Element root = doc.createElement(rootTag);
83       doc.appendChild(root);
84
85       saveToXML(root);
86
87       XML.dump(file, root);
88     }
89     catch (IOException e)
90     {
91       Reporter.error("Saving of '" + rootTag + "' XML format to file '" + file + "' failed", e);
92     }
93   }
94   
95   public void deleteFromStorage()
96   {
97     file.delete();
98   }
99   
100   public boolean toBeDeleted()
101   {
102     return false;
103   }
104
105   public String JavaDoc getName()
106   {
107     return name;
108   }
109   
110   public File getFile()
111   {
112     return file;
113   }
114   
115   public abstract void loadFromXML(Element element) throws SAXException JavaDoc;
116   public abstract void saveToXML(Element element);
117   protected abstract void reset();
118 }
119
Popular Tags