KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > dav > server > managers > HarmoniseLockManager


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19
20
21 package org.openharmonise.dav.server.managers;
22
23 import com.ibm.webdav.*;
24 import com.ibm.webdav.impl.*;
25
26
27 import java.util.*;
28 import java.util.logging.*;
29 import java.util.logging.Level JavaDoc;
30
31 import javax.xml.parsers.*;
32
33 import org.openharmonise.commons.dsi.*;
34 import org.openharmonise.dav.server.utils.*;
35 import org.openharmonise.dav.server.utils.HarmoniseNameResolver;
36 import org.openharmonise.rm.dsi.DataStoreInterfaceFactory;
37 import org.openharmonise.rm.resources.users.*;
38 import org.w3c.dom.*;
39
40
41 /**
42  * Harmonise implementation of <code>LockManager</code> to provide DAV4J with
43  * access to locking functionality of the Harmonise repository.
44  *
45  * @author Michael Bell
46  * @version $Revision: 1.2 $
47  *
48  */

49 public class HarmoniseLockManager implements com.ibm.webdav.impl.LockManager {
50     private ResourceImpl resource = null;
51     private com.ibm.webdav.impl.PropertiesManager propertiesManager = null;
52     private AbstractDataStoreInterface m_dsi = null;
53     
54     private static final Logger m_logger = Logger.getLogger(HarmoniseLockManager.class.getName());
55
56     public HarmoniseLockManager() {
57     }
58
59     /** Create a lock manager for the given resource.
60     * @param resource the resource to manage locks for
61     * @param namespaceManager its namespace manager
62     * @param propertiesManager and its properties manager
63     */

64     public HarmoniseLockManager(ResourceImpl resource,
65                            com.ibm.webdav.impl.NamespaceManager namespaceManager,
66                            com.ibm.webdav.impl.PropertiesManager propertiesManager) {
67         initialize(resource, namespaceManager, propertiesManager);
68     }
69
70     /** Get the lockdiscovery DAV property for the resource.
71     *
72     * @return an Element with tag name D:lockdiscovery
73     * @exception com.ibm.webdav.WebDAVException
74     */

75     public Element getLockDiscovery() throws WebDAVException {
76         // get the raw properties from the property manager
77
Document propertiesDocument = propertiesManager.loadProperties();
78         Element properties = propertiesDocument.getDocumentElement();
79         Element lockdiscovery = (Element) ((Element) properties).getElementsByTagNameNS(
80                                                   "DAV:", "lockdiscovery")
81                                                               .item(0);
82
83         // timeout any expired locks by
84
// deleting any locks that have timed out
85
boolean locksHaveChanged = false;
86
87         if (lockdiscovery != null) {
88             NodeList locks = ((Element) lockdiscovery).getElementsByTagNameNS(
89                                      "DAV:", "activelock");
90             Element lock = null;
91             Date now = new Date();
92
93             for (int i = 0; i < locks.getLength(); i++) {
94                 lock = (Element) locks.item(i);
95
96                 ActiveLock activeLock = new ActiveLock(lock);
97
98                 // see if the lock has timed out
99
Date expiration = activeLock.getExpiration();
100
101                 if ((expiration != null) && expiration.before(now)) {
102                     // has timed out, remove the lock
103
locksHaveChanged = true;
104
105                     try {
106                         lockdiscovery.removeChild(lock);
107                     } catch (Exception JavaDoc exc) {
108                         m_logger.log(Level.WARNING, exc.getLocalizedMessage(), exc);
109                     }
110                 }
111             }
112         }
113
114         if (locksHaveChanged) {
115             propertiesManager.saveProperties(propertiesDocument);
116         }
117
118         return lockdiscovery;
119     }
120
121     /** Get the locks that exist on this resource. May be null if the resource
122     * is not locked.
123     *
124     * @return a Vector of ActiveLock objects
125     * @exception com.ibm.webdav.WebDAVException
126     */

127     public Vector getLocks() throws WebDAVException {
128         Element lockdiscovery = (Element) getLockDiscovery();
129         Vector allLocks = new Vector();
130
131         if (lockdiscovery != null) {
132             NodeList activeLocks = ((Element) lockdiscovery).getElementsByTagNameNS(
133                                            "DAV:", "activelock");
134             Element activeLock = null;
135
136             for (int i = 0; i < activeLocks.getLength(); i++) {
137                 activeLock = (Element) activeLocks.item(i);
138                 allLocks.addElement(new ActiveLock(activeLock));
139             }
140         }
141
142         return allLocks;
143     }
144
145     /** Get information about locks supported by this resource.
146     *
147     * @return an Element with tag name D:supportedlock
148     */

149     public Element getSupportedLock() {
150         org.w3c.dom.Document JavaDoc document = null;
151
152         try {
153             document = DocumentBuilderFactory.newInstance()
154                                              .newDocumentBuilder()
155                                              .newDocument();
156         } catch (Exception JavaDoc e) {
157             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
158         }
159
160         Element supportedlock = document.createElementNS("DAV:",
161                                                          "D:supportedlock");
162
163         Element lockentry = document.createElementNS("DAV:", "D:lockentry");
164
165         supportedlock.appendChild(lockentry);
166
167         Element lockscope = document.createElementNS("DAV:", "D:lockscope");
168
169         Element lockexclusive = document.createElementNS("DAV:", "D:exclusive");
170
171         lockscope.appendChild(lockexclusive);
172         lockentry.appendChild(lockscope);
173
174         Element locktype = document.createElementNS("DAV:", "D:locktype");
175
176         Element lockwrite = document.createElementNS("DAV:", "D:write");
177
178         locktype.appendChild(lockwrite);
179         lockentry.appendChild(locktype);
180         lockentry = document.createElementNS("DAV:", "D:lockentry");
181
182         supportedlock.appendChild(lockentry);
183         lockscope = document.createElementNS("DAV:", "D:lockscope");
184
185         Element lockshare = document.createElementNS("DAV:", "D:shared");
186
187         lockscope.appendChild(lockshare);
188         lockentry.appendChild(lockscope);
189         locktype = document.createElementNS("DAV:", "D:locktype");
190
191         lockwrite = document.createElementNS("DAV:", "D:write");
192
193         locktype.appendChild(lockwrite);
194         lockentry.appendChild(locktype);
195
196         return supportedlock;
197     }
198
199     /** Initialize an this LockManager instance.
200     * @param resource the resource to manage locks for
201     * @param namespaceManager its namespace manager
202     * @param propertiesManager its properties manager
203     */

204     public void initialize(ResourceImpl resource,
205                            com.ibm.webdav.impl.NamespaceManager namespaceManager,
206                            com.ibm.webdav.impl.PropertiesManager propertiesManager) {
207         this.resource = resource;
208         this.propertiesManager = propertiesManager;
209
210         try {
211             this.m_dsi = DataStoreInterfaceFactory.getDataStoreInterface();
212         } catch (Exception JavaDoc e) {
213             throw new RuntimeException JavaDoc(
214                     "Datastore interface not started properly.");
215         }
216     }
217
218     /** Lock this resource Using the given activeLock.
219     *
220     * @param activeLock the lock to activate (i.e., persist)
221     *
222     * @return a MultiStatus containing a lockdiscovery property indicating
223     * the results of the lock operation.
224     * @exception com.ibm.webdav.WebDAVException
225     */

226     public MultiStatus lock(ActiveLock activeLock) throws WebDAVException {
227         String JavaDoc lockToken = "";
228
229         try {
230             lockToken = getLockToken(resource.getURL().getFile(),
231                                                 resource.getContext()
232                                                         .getRequestContext()
233                                                         .getAuthorizationId());
234         } catch (Exception JavaDoc e) {
235             m_logger.log(Level.WARNING, e.getLocalizedMessage(), e);
236             throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
237                                       "Had trouble getting UUID");
238         }
239
240         activeLock.setLockToken(lockToken);
241         
242         
243         try {
244             User usr = ((HarmoniseSessionManager) resource.getUserAuthenticator())
245                                                 .getUser(resource);
246                                                 
247             activeLock.setOwner(HarmoniseNameResolver.getDAVPath(usr));
248         } catch (WebDAVException e) {
249             throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
250                                       e.getLocalizedMessage());
251         } catch (NameResolverException e) {
252             throw new WebDAVException(WebDAVStatus.SC_INTERNAL_SERVER_ERROR,
253                                       e.getLocalizedMessage());
254         }
255
256         Element alockEl = activeLock.asXML();
257
258         org.w3c.dom.Document JavaDoc xmlDoc = alockEl.getOwnerDocument();
259         MultiStatus result = new MultiStatus();
260         PropertyResponse propertyResponse = new PropertyResponse(
261                                                     resource.getURL()
262                                                             .toString());
263         result.addResponse(propertyResponse);
264
265         PropertyValue l = resource.getProperty(PropertyName.pnLockdiscovery);
266         Element lockdiscovery = null;
267
268         if (l == null) {
269             lockdiscovery = xmlDoc.createElementNS("DAV:", "D:lockdiscovery");
270
271             lockdiscovery.setAttribute("xmlns:D", "DAV:");
272         } else {
273             lockdiscovery = (Element) ((Element) l.value).cloneNode(true);
274         }
275         
276         Element lockEl = (Element) lockdiscovery.getOwnerDocument().importNode(alockEl, true);
277
278         lockdiscovery.appendChild(lockEl);
279         propertiesManager.setProperty("DAV:lockdiscovery", lockdiscovery);
280
281         // all lock methods return the lockdiscovery property, even if the lock failed
282
PropertyName propname = PropertyName.createPropertyNameQuietly(
283                                         "DAV:lockdiscovery");
284
285         propertyResponse.addProperty(propname,
286                                      (Element) ((Element) lockdiscovery).cloneNode(
287                                              true), WebDAVStatus.SC_OK);
288
289         return result;
290     }
291     
292     static public String JavaDoc getLockToken(String JavaDoc sFilename, String JavaDoc sUser) throws NameResolverException {
293         return "hislocktoken:" +
294         HarmoniseNameResolver.getUUID(sFilename,sUser);
295     }
296
297     /**
298      * Refresh the lock on this resource by resetting the lock timeout.
299      * The context must contain the proper authorization for the requesting
300      * principal.
301      *
302      * @param activeLock the lock to refresh. Contains the updated timeout
303      * and expiration date.
304      *
305      * @return updated information about the lock status of this resource
306      * @exception com.ibm.webdav.WebDAVException
307      */

308     public MultiStatus refreshLock(ActiveLock activeLock)
309                             throws WebDAVException {
310         Element alockEl = activeLock.asXML();
311         org.w3c.dom.Document JavaDoc xmlDoc = alockEl.getOwnerDocument();
312
313         MultiStatus result = new MultiStatus();
314         PropertyResponse propertyResponse = new PropertyResponse(
315                                                     resource.getURL()
316                                                             .toString());
317         result.addResponse(propertyResponse);
318
319         // get the locks on this resource
320
PropertyValue l = resource.getProperty(PropertyName.pnLockdiscovery);
321         Element lockdiscovery = null;
322
323         if (l == null) {
324             lockdiscovery = xmlDoc.createElementNS("DAV:", "D:lockdiscovery");
325
326             lockdiscovery.setAttribute("xmlns:D", "DAV:");
327         } else {
328             lockdiscovery = (Element) ((Element) l.value).cloneNode(true);
329         }
330
331         // find the lock
332
boolean lockFound = false;
333         NodeList locks = ((Element) lockdiscovery).getElementsByTagNameNS(
334                                  "DAV:", "activelock");
335         Element lock = null;
336
337         for (int i = 0; i < locks.getLength(); i++) {
338             lock = (Element) locks.item(i);
339
340             ActiveLock aLock = new ActiveLock(lock);
341
342             if (aLock.getLockToken().equals(activeLock.getLockToken())) {
343                 lockFound = true;
344                 lockdiscovery.removeChild(lock);
345
346                 break;
347             }
348         }
349
350         if (!lockFound) {
351             throw new WebDAVException(WebDAVStatus.SC_PRECONDITION_FAILED,
352                                       "principal does not own a lock");
353         }
354
355         lockdiscovery.appendChild(alockEl);
356         propertiesManager.setProperty("DAV:lockdiscovery", lockdiscovery);
357
358         PropertyName propname = PropertyName.createPropertyNameQuietly(
359                                         "DAV:lockdiscovery");
360
361
362         // all lock methods return the lockdiscovery property, even if the lock failed
363
propertyResponse.addProperty(propname,
364                                      (Element) ((Element) lockdiscovery).cloneNode(
365                                              true), WebDAVStatus.SC_OK);
366
367         return result;
368     }
369
370     /** Unlock the lock identified by the lockToken on this resource
371     *
372     * @param activeLock the lock to unlock
373     *
374     * @return a MultiStatus containing any responses on resources that could not
375     * be unlocked.
376     * @exception com.ibm.webdav.WebDAVException
377     */

378     public MultiStatus unlock(ActiveLock activeLock) throws WebDAVException {
379         Element alockEl = activeLock.asXML();
380         org.w3c.dom.Document JavaDoc xmlDoc = alockEl.getOwnerDocument();
381
382         MultiStatus result = new MultiStatus();
383         PropertyResponse propertyResponse = new PropertyResponse(
384                                                     resource.getURL()
385                                                             .toString());
386         result.addResponse(propertyResponse);
387
388         // get the locks on this resource
389
PropertyValue l = resource.getProperty(PropertyName.pnLockdiscovery);
390         Element lockdiscovery = null;
391
392         if (l == null) {
393             lockdiscovery = xmlDoc.createElementNS("DAV:", "D:lockdiscovery");
394
395             lockdiscovery.setAttribute("xmlns:D", "DAV:");
396         } else {
397             lockdiscovery = (Element) ((Element) l.value).cloneNode(true);
398         }
399
400         // find the lock
401
ActiveLock lockToRemove = null;
402         NodeList locks = ((Element) lockdiscovery).getElementsByTagNameNS(
403                                  "DAV:", "activelock");
404         Element lock = null;
405
406         for (int i = 0; i < locks.getLength(); i++) {
407             lock = (Element) locks.item(i);
408
409             ActiveLock aLock = new ActiveLock(lock);
410
411             if (aLock.getLockToken().equals(activeLock.getLockToken())) {
412                 lockToRemove = aLock;
413                 lockdiscovery.removeChild(lock);
414
415                 break;
416             }
417         }
418
419         if (lockToRemove == null) {
420             throw new WebDAVException(WebDAVStatus.SC_PRECONDITION_FAILED,
421                                       "resource is not locked with the given lock token");
422         } else {
423             propertiesManager.setProperty("DAV:lockdiscovery", lockdiscovery);
424         }
425
426         // all lock methods return the lockdiscovery property, even if the lock failed
427
PropertyName propname = PropertyName.createPropertyNameQuietly(
428                                         "DAV:lockdiscovery");
429         propertyResponse.addProperty(propname,
430                                      (Element) ((Element) lockdiscovery).cloneNode(
431                                              true), WebDAVStatus.SC_OK);
432
433         return result;
434     }
435 }
Popular Tags