KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > webdav > LockMethod


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.repo.webdav;
18
19 import java.util.List JavaDoc;
20
21 import javax.servlet.http.HttpServletResponse JavaDoc;
22
23 import org.alfresco.model.ContentModel;
24 import org.alfresco.service.cmr.lock.LockService;
25 import org.alfresco.service.cmr.lock.LockStatus;
26 import org.alfresco.service.cmr.lock.LockType;
27 import org.alfresco.service.cmr.model.FileFolderService;
28 import org.alfresco.service.cmr.model.FileInfo;
29 import org.alfresco.service.cmr.model.FileNotFoundException;
30 import org.alfresco.service.cmr.repository.NodeRef;
31 import org.dom4j.io.XMLWriter;
32
33 /**
34  * Implements the WebDAV LOCK method
35  *
36  * @author gavinc
37  */

38 public class LockMethod extends WebDAVMethod
39 {
40     private String JavaDoc m_strLockToken = null;
41     private int m_timeoutDuration = WebDAV.DEPTH_INFINITY;
42
43     /**
44      * Default constructor
45      */

46     public LockMethod()
47     {
48     }
49
50     /**
51      * Check if the lock token is valid
52      *
53      * @return boolean
54      */

55     protected final boolean hasLockToken()
56     {
57         return m_strLockToken != null ? true : false;
58     }
59
60     /**
61      * Return the lock token of an existing lock
62      *
63      * @return String
64      */

65     protected final String JavaDoc getLockToken()
66     {
67         return m_strLockToken;
68     }
69
70     /**
71      * Return the lock timeout, in minutes
72      *
73      * @return int
74      */

75     protected final int getLockTimeout()
76     {
77         return m_timeoutDuration;
78     }
79
80     /**
81      * Parse the request headers
82      *
83      * @exception WebDAVServerException
84      */

85     protected void parseRequestHeaders() throws WebDAVServerException
86     {
87         // Get the lock token, if any
88

89         m_strLockToken = parseIfHeader();
90
91         // Get the lock timeout value
92

93         String JavaDoc strTimeout = m_request.getHeader(WebDAV.HEADER_TIMEOUT);
94
95         // If the timeout header starts with anything other than Second
96
// leave the timeout as the default
97

98         if (strTimeout != null && strTimeout.startsWith(WebDAV.SECOND))
99         {
100             try
101             {
102                 // Some clients send header as Second-180 Seconds so we need to
103
// look for the space
104

105                 int idx = strTimeout.indexOf(" ");
106
107                 if (idx != -1)
108                 {
109                     // Get the bit after Second- and before the space
110

111                     strTimeout = strTimeout.substring(WebDAV.SECOND.length(), idx);
112                 }
113                 else
114                 {
115                     // The string must be in the correct format
116

117                     strTimeout = strTimeout.substring(WebDAV.SECOND.length());
118                 }
119                 m_timeoutDuration = Integer.parseInt(strTimeout);
120             }
121             catch (Exception JavaDoc e)
122             {
123                 // Warn about the parse failure and leave the timeout as the
124
// default
125

126                 logger.warn("Failed to parse Timeout header: " + strTimeout);
127             }
128         }
129
130         // DEBUG
131

132         if (logger.isDebugEnabled())
133             logger.debug("Lock lockToken=" + getLockToken() + ", timeout=" + getLockTimeout());
134     }
135
136     /**
137      * Parse the request body
138      *
139      * @exception WebDAVServerException
140      */

141     protected void parseRequestBody() throws WebDAVServerException
142     {
143         // NOTE: There is a body for lock requests which contain the
144
// type of lock to apply and the lock owner but we will
145
// ignore these settings so don't bother reading the body
146
}
147
148     /**
149      * Exceute the request
150      *
151      * @exception WebDAVServerException
152      */

153     protected void executeImpl() throws WebDAVServerException, Exception JavaDoc
154     {
155         FileFolderService fileFolderService = getFileFolderService();
156         String JavaDoc path = getPath();
157         NodeRef rootNodeRef = getRootNodeRef();
158         // Get the active user
159
String JavaDoc userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
160
161         if (logger.isDebugEnabled())
162         {
163             logger.debug("Locking node: \n" +
164                     " user: " + userName + "\n" +
165                     " path: " + path);
166         }
167
168         FileInfo lockNodeInfo = null;
169         try
170         {
171             // Check if the path exists
172
lockNodeInfo = getDAVHelper().getNodeForPath(getRootNodeRef(), getPath(), m_request.getServletPath());
173         }
174         catch (FileNotFoundException e)
175         {
176             // need to create it
177
String JavaDoc[] splitPath = getDAVHelper().splitPath(path);
178             // check
179
if (splitPath[1].length() == 0)
180             {
181                 throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
182             }
183             
184             List JavaDoc<String JavaDoc> dirPathElements = getDAVHelper().splitAllPaths(splitPath[0]);
185             FileInfo dirInfo = fileFolderService.makeFolders(rootNodeRef, dirPathElements, ContentModel.TYPE_FOLDER);
186             if (dirInfo == null)
187             {
188                 throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
189             }
190             // create the file
191
lockNodeInfo = fileFolderService.create(dirInfo.getNodeRef(), splitPath[1], ContentModel.TYPE_CONTENT);
192             
193             if (logger.isDebugEnabled())
194             {
195                 logger.debug("Created new node for lock: \n" +
196                         " path: " + path + "\n" +
197                         " node: " + lockNodeInfo);
198             }
199         }
200
201
202         // Check if this is a new lock or a refresh
203
if (hasLockToken())
204         {
205             // Refresh an existing lock
206
refreshLock(lockNodeInfo.getNodeRef(), userName);
207         }
208         else
209         {
210             // Create a new lock
211
createLock(lockNodeInfo.getNodeRef(), userName);
212         }
213
214         // We either created a new lock or refreshed an existing lock, send back the lock details
215
generateResponse(lockNodeInfo.getNodeRef(), userName);
216     }
217
218     /**
219      * Create a new lock
220      *
221      * @param lockNode NodeRef
222      * @param userName String
223      * @exception WebDAVServerException
224      */

225     private final void createLock(NodeRef lockNode, String JavaDoc userName) throws WebDAVServerException
226     {
227         LockService lockService = getLockService();
228
229         // Check the lock status of the node
230
LockStatus lockSts = lockService.getLockStatus(lockNode);
231
232         // DEBUG
233
if (logger.isDebugEnabled())
234             logger.debug("Create lock status=" + lockSts);
235
236         if (lockSts == LockStatus.LOCKED || lockSts == LockStatus.LOCK_OWNER)
237         {
238             // Indicate that the resource is already locked
239
throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
240         }
241
242         // Lock the node
243
lockService.lock(lockNode, LockType.WRITE_LOCK, getLockTimeout());
244     }
245
246     /**
247      * Refresh an existing lock
248      *
249      * @param lockNode NodeRef
250      * @param userName String
251      * @exception WebDAVServerException
252      */

253     private final void refreshLock(NodeRef lockNode, String JavaDoc userName) throws WebDAVServerException
254     {
255         LockService lockService = getLockService();
256
257         // Check the lock status of the node
258
LockStatus lockSts = lockService.getLockStatus(lockNode);
259
260         // DEBUG
261
if (logger.isDebugEnabled())
262             logger.debug("Refresh lock status=" + lockSts);
263
264         if (lockSts != LockStatus.LOCK_OWNER)
265         {
266             // Indicate that the resource is already locked
267
throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
268         }
269
270         // Update the expiry for the lock
271
lockService.lock(lockNode, LockType.WRITE_LOCK, getLockTimeout());
272     }
273
274     /**
275      * Generates the XML lock discovery response body
276      */

277     private void generateResponse(NodeRef lockNode, String JavaDoc userName) throws Exception JavaDoc
278     {
279         XMLWriter xml = createXMLWriter();
280
281         xml.startDocument();
282
283         String JavaDoc nsdec = generateNamespaceDeclarations(null);
284         xml.startElement(WebDAV.DAV_NS, WebDAV.XML_MULTI_STATUS + nsdec, WebDAV.XML_NS_MULTI_STATUS + nsdec,
285                 getDAVHelper().getNullAttributes());
286
287         // Output the lock details
288
generateLockDiscoveryXML(xml, lockNode);
289
290         // Close off the XML
291
xml.endElement(WebDAV.DAV_NS, WebDAV.XML_MULTI_STATUS, WebDAV.XML_NS_MULTI_STATUS);
292
293         // Send the XML back to the client
294
m_response.setStatus(HttpServletResponse.SC_OK);
295         xml.flush();
296     }
297 }
298
Popular Tags