View Javadoc

1   /*
2    * Copyright (c) 2006-2007 Creative Sphere Limited.
3    * All rights reserved. This program and the accompanying materials
4    * are made available under the terms of the Eclipse Public License v1.0
5    * which accompanies this distribution, and is available at
6    * http://www.eclipse.org/legal/epl-v10.html
7    *
8    * Contributors:
9    *
10   *   Creative Sphere - initial API and implementation
11   *
12   */
13  package org.abstracthorizon.danube.webdav.fs;
14  
15  import org.abstracthorizon.danube.webdav.lock.Lock;
16  import org.abstracthorizon.danube.webdav.lock.impl.SimpleInMemoryLockingMechanism;
17  
18  import java.io.File;
19  import java.io.IOException;
20  import java.io.RandomAccessFile;
21  import java.util.Collection;
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  /**
26   * <p>
27   * Locking mechanism that locks files on the file system by using
28   * {@link RandomAccessFile} to open the file with &quot;rw&quot;
29   * attributes. Unlocking is done by closing that file.
30   * </p>
31   *
32   * <p>
33   * Note: So far it is confirmed that it works only on Windows machines
34   * </p>
35   *
36   * @author Daniel Sendula
37   */
38  public class FSLockingMechanism extends SimpleInMemoryLockingMechanism {
39  
40      /** Map of locks */
41      protected Map<Object, RandomAccessFile> fsLocks = new HashMap<Object, RandomAccessFile>();
42  
43      /**
44       * Constructor
45       */
46      public FSLockingMechanism() {
47      }
48  
49      /**
50       * Locks the file
51       * @param lock lock
52       * @param resource a file
53       * @return <code>true</code> if file is locked
54       */
55      @Override
56      public synchronized boolean lockResource(Lock lock, Object resource) {
57          if (super.lockResource(lock, resource)) {
58              try {
59                  File file = (File)resource;
60                  RandomAccessFile raf = new RandomAccessFile(file, "rw");
61                  fsLocks.put(resource, raf);
62              } catch (IOException ignore) {
63              }
64              return true;
65          } else {
66              return false;
67          }
68      }
69  
70      /**
71       * Unlocks the file
72       * @param lock lock
73       */
74      public synchronized void unlockResources(Lock lock) {
75          Collection<Object> resources = lockResources.get(lock);
76          if ((resources != null) && (resources.size() > 0)) {
77              for (Object resource : resources) {
78                  RandomAccessFile raf = fsLocks.remove(resource);
79                  if (raf != null) {
80                      try {
81                          raf.close();
82                      } catch (IOException ignore) {
83                      }
84                  }
85              }
86          }
87          super.unlockResources(lock);
88      }
89  }