KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibm > webdav > fileSystem > PropertiesManager


1 package com.ibm.webdav.fileSystem;
2
3 /*
4  * (C) Copyright IBM Corp. 2000 All rights reserved.
5  *
6  * The program is provided "AS IS" without any warranty express or
7  * implied, including the warranty of non-infringement and the implied
8  * warranties of merchantibility and fitness for a particular purpose.
9  * IBM will not be liable for any damages suffered by you as a result
10  * of using the Program. In no event will IBM be liable for any
11  * special, indirect or consequential damages or lost profits even if
12  * IBM has been advised of the possibility of their occurrence. IBM
13  * will not be liable for any third party claims against you.
14  *
15  * Portions Copyright (C) Simulacra Media Ltd, 2004.
16  */

17 import java.io.*;
18 import java.util.*;
19
20 import javax.xml.parsers.*;
21
22 import org.w3c.dom.*;
23
24 import com.ibm.webdav.*;
25 import com.ibm.webdav.impl.*;
26
27
28 /** PropertiesManager extends CachedProperties to implements its repository
29  * specific abstract methods.
30  * @author Jim Amsden <jamsden@us.ibm.com>
31  */

32 public class PropertiesManager extends CachedPropertiesManager {
33
34     public static String JavaDoc propertiesSuffix = ".wdp"; // a WebDAV properties file
35

36     protected Document cachedPropertiesDocument = null;
37     protected long cacheTimeStamp = 0;
38     private static final int bufferSize = 8192;
39    public PropertiesManager()
40    {
41    }
42    // Constructors:
43

44    public PropertiesManager(ResourceImpl resource,
45                             com.ibm.webdav.impl.NamespaceManager namespaceManager)
46    {
47       super(resource, namespaceManager);
48    }
49 /** Delete all properties. Delete the properties file and
50 * flush the cache.
51 * @exception com.ibm.webdav.WebDAVException
52 *
53 */

54 public void deleteProperties() throws WebDAVException {
55     File propertiesFile = new File(getPropertiesFileName());
56     propertiesFile.delete();
57     cachedPropertiesDocument = null;
58 }
59 /** Get the name of the properties file. The file name is the resource
60 * file name concatenated with PropertiesManager.propertiesSuffix.
61 * @return the properties file name
62 * @exception com.ibm.webdav.WebDAVException
63 */

64 private String JavaDoc getPropertiesFileName() throws WebDAVException {
65     String JavaDoc fileName = ResourceFactory.getRealPath(resource.getURL());
66     // if the resource is a collection, strip off any trailing path separator
67
if (fileName.endsWith(File.separator)) {
68         fileName = fileName.substring(0, fileName.length() - 1);
69     }
70
71     // create the properties file name by adding a .properties extension
72
return fileName + PropertiesManager.propertiesSuffix;
73 }
74 public Vector loadPropertyDefinitions() throws WebDAVException {
75   return null;
76 }
77
78 /** Load the properties document from the file system properties file.
79 * Check to see if the cache has expired.
80 * @return an XML document containing a properties element.
81 * @exception com.ibm.webdav.WebDAVException
82 */

83 public Document loadProperties() throws WebDAVException {
84     File propertiesFile = new File(getPropertiesFileName());
85     try {
86         // make sure the user is authorized to read the properties
87
if (propertiesFile.exists() && !propertiesFile.canRead()) {
88             throw new WebDAVException(WebDAVStatus.SC_UNAUTHORIZED, "Insufficient permissions");
89         }
90
91         if (cachedPropertiesDocument != null && propertiesFile.lastModified() <= cacheTimeStamp) {
92             return cachedPropertiesDocument;
93         }
94         cacheTimeStamp = propertiesFile.lastModified();
95
96         // read the properties file and parse it's contents
97
Reader reader = new InputStreamReader(new FileInputStream(propertiesFile), Resource.defaultCharEncoding);
98         Reader is = new BufferedReader(reader);
99         WebDAVErrorHandler errorHandler = new WebDAVErrorHandler(resource.getURL().toString());
100
101         /*Parser xmlParser = new Parser(propertiesFile.getName(), errorListener, null);
102         xmlParser.setWarningNoDoctypeDecl(false);
103         xmlParser.setProcessNamespace(true);
104         cachedPropertiesDocument = xmlParser.readStream(is);*/

105                 DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
106                 docbuilder.setErrorHandler(errorHandler);
107                 cachedPropertiesDocument = docbuilder.parse(new org.xml.sax.InputSource JavaDoc(is));
108         if (errorHandler.getErrorCount() > 0) {
109             throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "Syntax error in properties file");
110         }
111
112         // get the properties element from the document so we can put it
113
// in a MultiStatus
114
Element properties = (Element) cachedPropertiesDocument.getDocumentElement();
115         if (properties == null || !properties.getTagName().equals("properties")) {
116             throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "Bad properties file");
117         }
118     } catch (FileNotFoundException exc) {
119         if (propertiesFile.exists()) {
120             throw new WebDAVException(WebDAVStatus.SC_UNAUTHORIZED, "Insufficient permissions");
121         } else {
122             // we have a resouce that doesn't have any properties yet
123
try {
124                         cachedPropertiesDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
125             } catch(Exception JavaDoc e) {
126                           throw new WebDAVException(WebDAVStatus.SC_PROCESSING,e.getMessage());
127                         }
128                         //cachedPropertiesDocument.setVersion(Resource.XMLVersion);
129
Element properties = cachedPropertiesDocument.createElement("properties");
130             properties.setAttribute("xmlns:D", "DAV:");
131             cachedPropertiesDocument.appendChild(properties);
132         }
133     } catch (SecurityException JavaDoc exc) {
134         throw new WebDAVException(WebDAVStatus.SC_UNAUTHORIZED, "Insufficient permissions");
135     } catch (Exception JavaDoc exc) {
136         exc.printStackTrace();
137         throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "Can't read properties file");
138     }
139     return cachedPropertiesDocument;
140 }
141 /** Remove the live DAV properties from the properties document that
142 * do not need to be saved. There is no reason to save them as long
143 * as they are recalculated each time the properties are loaded. This
144 * method removes the ones that are repository specific.
145 *
146 * @param propertiesDocument an XML document containing a properties element.
147 */

148 public void removeLiveProperties(Document propertiesDocument) {
149     Element properties = propertiesDocument.getDocumentElement();
150     Element p = null;
151     p = (Element)((Element) properties).getElementsByTagNameNS("DAV:", "getcontentlength").item(0);
152     if (p != null)
153         properties.removeChild(p);
154     p = (Element)((Element) properties).getElementsByTagNameNS("DAV:", "resourcetype").item(0);
155     if (p != null)
156         properties.removeChild(p);
157     p = (Element)((Element) properties).getElementsByTagNameNS("DAV:", "getlastmodified").item(0);
158     if (p != null)
159         properties.removeChild(p);
160     // I haven't read this carefully, but getcontent type seems to be
161
// treated as a live property in the other methods, so treat it
162
// as such here. (jlc 991002)
163
p = (Element)((Element) properties).getElementsByTagNameNS("DAV:", "getcontenttype").item(0);
164     if (p != null)
165         properties.removeChild(p);
166 }
167 /** Save the properties to the persistent store.
168 *
169 * @param propertiesDocument an XML document containing a properties element.
170 * @exception com.ibm.webdav.WebDAVException
171 */

172 public void saveProperties(Document propertiesDocument) throws WebDAVException {
173     File propertiesFile = new File(getPropertiesFileName());
174     try {
175         // make sure the user is authorized to read the properties
176
if (propertiesFile.exists() && !propertiesFile.canWrite()) {
177             throw new WebDAVException(WebDAVStatus.SC_UNAUTHORIZED, "Insufficient permissions");
178         }
179
180         // write the properties file
181
Writer writer = new OutputStreamWriter(new FileOutputStream(propertiesFile), Resource.defaultCharEncoding);
182         PrintWriter pout = new PrintWriter(writer, false);
183         pout.print(XMLUtility.printNode(propertiesDocument.getDocumentElement()));
184                 //propertiesDocument.print(pout);
185
pout.close();
186     } catch (Exception JavaDoc exc) {
187         exc.printStackTrace();
188         throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR, "Can't write properties file");
189     }
190 }
191 /** Update the live properties that are unique to the
192 * repository implementation
193 *
194 * @param document an XML document containing a properties to update.
195 * @exception com.ibm.webdav.WebDAVException
196 */

197 public void updateLiveProperties(Document document) throws WebDAVException {
198     Element properties = document.getDocumentElement();
199
200     // update the repository specific live properties
201
Element getContentLength = document.createElement("D:getcontentlength");
202     long length = 0;
203     File file = new File(ResourceFactory.getRealPath(resource.getURL()));
204     if (file.exists()) {
205         length = file.length();
206     }
207     // TODO: this doesn't account for the content length for text files
208
// which are encoded. The content length is therefore client specific
209
// because it depends on the encoding the client requests
210
getContentLength.appendChild(document.createTextNode(new Long JavaDoc(length).toString()));
211     properties.appendChild(getContentLength);
212     Element resourceType = document.createElement("D:resourcetype");
213     if (file.exists() && file.isDirectory()) {
214         resourceType.appendChild(document.createElement("D:collection"));
215     }
216     properties.appendChild(resourceType);
217     Element lastModifiedDate = document.createElement("D:getlastmodified");
218     // TODO: bug, we can't assume that the value returned from file.lastModified can be used in the Date constructor. See the java.io.File.lastModified() documentation.
219
// TODO: we actually are supposed to insure that this is the same value returned by the main server in response to GET. I don't know if that's possible right now. It may return nothing at all. Check later.
220
String JavaDoc cdstring = new SimpleRFC1123DateFormat().format(new Date(file.lastModified()));
221     lastModifiedDate.appendChild(document.createTextNode(cdstring));
222     properties.appendChild(lastModifiedDate);
223
224     Element contentType = document.createElement("D:getcontenttype");
225     String JavaDoc mimetype = com.ibm.webdav.fileSystem.NamespaceManager.guessAtContentTypeForName(ResourceFactory.getRealPath(resource.getURL()));
226     contentType.appendChild(document.createTextNode(mimetype));
227     properties.appendChild(contentType);
228 }
229 }
230
Popular Tags