KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > filesys > smb > server > repo > CifsHelper


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.filesys.smb.server.repo;
18
19 import java.io.FileNotFoundException JavaDoc;
20 import java.io.Serializable JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Collections JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.List JavaDoc;
25 import java.util.Map JavaDoc;
26 import java.util.Stack JavaDoc;
27 import java.util.StringTokenizer JavaDoc;
28
29 import org.alfresco.error.AlfrescoRuntimeException;
30 import org.alfresco.filesys.server.filesys.FileAttribute;
31 import org.alfresco.filesys.server.filesys.FileExistsException;
32 import org.alfresco.filesys.server.filesys.FileInfo;
33 import org.alfresco.filesys.server.filesys.FileName;
34 import org.alfresco.model.ContentModel;
35 import org.alfresco.service.cmr.dictionary.DictionaryService;
36 import org.alfresco.service.cmr.model.FileFolderService;
37 import org.alfresco.service.cmr.repository.ContentData;
38 import org.alfresco.service.cmr.repository.InvalidNodeRefException;
39 import org.alfresco.service.cmr.repository.MimetypeService;
40 import org.alfresco.service.cmr.repository.NodeRef;
41 import org.alfresco.service.cmr.repository.NodeService;
42 import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
43 import org.alfresco.service.cmr.security.AccessStatus;
44 import org.alfresco.service.cmr.security.PermissionService;
45 import org.alfresco.service.namespace.QName;
46 import org.alfresco.util.SearchLanguageConversion;
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49
50 /**
51  * Class with supplying helper methods and potentially acting as a cache for
52  * queries.
53  *
54  * @author derekh
55  */

56 public class CifsHelper
57 {
58     // Logging
59
private static Log logger = LogFactory.getLog(CifsHelper.class);
60     
61     // Services
62
private DictionaryService dictionaryService;
63     private NodeService nodeService;
64     private FileFolderService fileFolderService;
65     private MimetypeService mimetypeService;
66     private PermissionService permissionService;
67     
68     // Mark locked files as offline
69

70     private boolean lockedFilesAsOffline;
71     
72     /**
73      * Class constructor
74      */

75     public CifsHelper()
76     {
77     }
78     
79     public void setDictionaryService(DictionaryService dictionaryService)
80     {
81         this.dictionaryService = dictionaryService;
82     }
83     
84     public void setNodeService(NodeService nodeService)
85     {
86         this.nodeService = nodeService;
87     }
88
89     public void setFileFolderService(FileFolderService fileFolderService)
90     {
91         this.fileFolderService = fileFolderService;
92     }
93     
94     public void setMimetypeService(MimetypeService mimetypeService)
95     {
96         this.mimetypeService = mimetypeService;
97     }
98
99     public void setPermissionService(PermissionService permissionService)
100     {
101         this.permissionService = permissionService;
102     }
103
104     /**
105      * Enable marking of locked files as offline
106      *
107      * @param ena boolean
108      */

109     public final void setMarkLockedFilesAsOffline(boolean ena)
110     {
111         lockedFilesAsOffline = ena;
112     }
113     
114     /**
115      * Check if locked files should be marked as offline
116      *
117      * @return boolean
118      */

119     public final boolean hasLockedFilesAsOffline()
120     {
121         return lockedFilesAsOffline;
122     }
123     
124     /**
125      * @param serviceRegistry for repo connection
126      * @param nodeRef
127      * @return Returns true if the node is a subtype of {@link ContentModel#TYPE_FOLDER folder}
128      * @throws AlfrescoRuntimeException if the type is neither related to a folder or content
129      */

130     public boolean isDirectory(NodeRef nodeRef)
131     {
132         QName nodeTypeQName = nodeService.getType(nodeRef);
133         if (dictionaryService.isSubClass(nodeTypeQName, ContentModel.TYPE_FOLDER))
134         {
135             return true;
136         }
137         else if (dictionaryService.isSubClass(nodeTypeQName, ContentModel.TYPE_CONTENT))
138         {
139             return false;
140         }
141         else
142         {
143             // it is not a directory, but what is it?
144
return false;
145         }
146     }
147
148     /**
149      * Extract a single node's file info, where the node is reference by
150      * a path relative to an ancestor node.
151      *
152      * @param pathRootNodeRef
153      * @param path
154      * @return Returns the existing node reference
155      * @throws FileNotFoundException
156      */

157     public FileInfo getFileInformation(NodeRef pathRootNodeRef, String JavaDoc path) throws FileNotFoundException JavaDoc
158     {
159         // get the node being referenced
160
NodeRef nodeRef = getNodeRef(pathRootNodeRef, path);
161
162         FileInfo fileInfo = getFileInformation(nodeRef);
163
164         return fileInfo;
165     }
166
167     /**
168      * Helper method to extract file info from a specific node.
169      * <p>
170      * This method goes direct to the repo for all information and no data is
171      * cached here.
172      *
173      * @param nodeRef the node that the path is relative to
174      * @param path the path to get info for
175      * @return Returns the file information pertinent to the node
176      * @throws FileNotFoundException if the path refers to a non-existent file
177      */

178     public FileInfo getFileInformation(NodeRef nodeRef) throws FileNotFoundException JavaDoc
179     {
180         // get the file info
181
org.alfresco.service.cmr.model.FileInfo fileFolderInfo = fileFolderService.getFileInfo(nodeRef);
182         
183         // retrieve required properties and create file info
184
FileInfo fileInfo = new FileInfo();
185         
186         // unset all attribute flags
187
int fileAttributes = 0;
188         fileInfo.setFileAttributes(fileAttributes);
189         
190         if (fileFolderInfo.isFolder())
191         {
192             // add directory attribute
193
fileAttributes |= FileAttribute.Directory;
194             fileInfo.setFileAttributes(fileAttributes);
195         }
196         else
197         {
198             Map JavaDoc<QName, Serializable JavaDoc> nodeProperties = fileFolderInfo.getProperties();
199             
200             // Get the file size from the content
201

202             ContentData contentData = (ContentData) nodeProperties.get(ContentModel.PROP_CONTENT);
203             long size = 0L;
204             if (contentData != null)
205             {
206                 size = contentData.getSize();
207             }
208             fileInfo.setSize(size);
209             
210             // Set the allocation size by rounding up the size to a 512 byte block boundary
211

212             if ( size > 0)
213                 fileInfo.setAllocationSize((size + 512L) & 0xFFFFFFFFFFFFFE00L);
214             
215             // Check the lock status of the file
216

217             if ( hasLockedFilesAsOffline())
218             {
219                 String JavaDoc lockTypeStr = (String JavaDoc) nodeProperties.get(ContentModel.PROP_LOCK_TYPE);
220                     
221                 if ( lockTypeStr != null)
222                 {
223                     // File is locked so mark it as offline
224

225                     fileInfo.setFileAttributes(fileInfo.getFileAttributes() + FileAttribute.NTOffline);
226                 }
227             }
228         }
229         
230         // created
231
Date JavaDoc createdDate = fileFolderInfo.getCreatedDate();
232         if (createdDate != null)
233         {
234             long created = DefaultTypeConverter.INSTANCE.longValue(createdDate);
235             fileInfo.setCreationDateTime(created);
236         }
237         // modified
238
Date JavaDoc modifiedDate = fileFolderInfo.getModifiedDate();
239         if (modifiedDate != null)
240         {
241             long modified = DefaultTypeConverter.INSTANCE.longValue(modifiedDate);
242             fileInfo.setModifyDateTime(modified);
243             fileInfo.setAccessDateTime(modified);
244         }
245         // name
246
String JavaDoc name = fileFolderInfo.getName();
247         if (name != null)
248         {
249             fileInfo.setFileName(name);
250         }
251         
252         // Read/write access
253

254         if ( permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.DENIED)
255             fileInfo.setFileAttributes(fileInfo.getFileAttributes() + FileAttribute.ReadOnly);
256
257         // Set the normal file attribute if no other attributes are set
258

259         if ( fileInfo.getFileAttributes() == 0)
260             fileInfo.setFileAttributes(FileAttribute.NTNormal);
261         
262         // Debug
263

264         if (logger.isDebugEnabled())
265         {
266             logger.debug("Fetched file info: \n" +
267                     " info: " + fileInfo);
268         }
269         
270         // Return the file information
271

272         return fileInfo;
273     }
274     
275     /**
276      * Creates a file or directory using the given paths.
277      * <p>
278      * If the directory path doesn't exist, then all the parent directories will be created.
279      * If the file path is <code>null</code>, then the file will not be created
280      *
281      * @param rootNodeRef the root node of the path
282      * @param path the path to a node
283      * @param isFile true if the node to be created must be a file
284      * @return Returns a newly created file or folder node
285      * @throws FileExistsException if the file or folder already exists
286      */

287     public NodeRef createNode(NodeRef rootNodeRef, String JavaDoc path, boolean isFile) throws FileExistsException
288     {
289         // split the path up into its constituents
290
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(path, FileName.DOS_SEPERATOR_STR, false);
291         List JavaDoc<String JavaDoc> folderPathElements = new ArrayList JavaDoc<String JavaDoc>(10);
292         String JavaDoc name = null;
293         while (tokenizer.hasMoreTokens())
294         {
295             String JavaDoc pathElement = tokenizer.nextToken();
296             
297             if (!tokenizer.hasMoreTokens())
298             {
299                 // the last token becomes the name
300
name = pathElement;
301             }
302             else
303             {
304                 // add the path element to the parent folder path
305
folderPathElements.add(pathElement);
306             }
307         }
308         // ensure that the folder path exists
309
NodeRef parentFolderNodeRef = rootNodeRef;
310         if (folderPathElements.size() > 0)
311         {
312             parentFolderNodeRef = fileFolderService.makeFolders(
313                     rootNodeRef,
314                     folderPathElements,
315                     ContentModel.TYPE_FOLDER).getNodeRef();
316         }
317         // add the file or folder
318
QName typeQName = isFile ? ContentModel.TYPE_CONTENT : ContentModel.TYPE_FOLDER;
319         try
320         {
321             NodeRef nodeRef = fileFolderService.create(parentFolderNodeRef, name, typeQName).getNodeRef();
322             
323             // done
324
if (logger.isDebugEnabled())
325             {
326                 logger.debug("Created node: \n" +
327                         " device root: " + rootNodeRef + "\n" +
328                         " path: " + path + "\n" +
329                         " is file: " + isFile + "\n" +
330                         " new node: " + nodeRef);
331             }
332             return nodeRef;
333         }
334         catch (org.alfresco.service.cmr.model.FileExistsException e)
335         {
336             throw new FileExistsException(path);
337         }
338     }
339
340     private void addDescendents(List JavaDoc<NodeRef> pathRootNodeRefs, Stack JavaDoc<String JavaDoc> pathElements, List JavaDoc<NodeRef> results)
341     {
342         if (pathElements.isEmpty())
343         {
344             // if this method is called with an empty path element stack, then the
345
// current context nodes are the results to be added
346
results.addAll(pathRootNodeRefs);
347             return;
348         }
349         
350         // take the first path element off the stack
351
String JavaDoc pathElement = pathElements.pop();
352
353         // iterate over each path root node
354
for (NodeRef pathRootNodeRef : pathRootNodeRefs)
355         {
356             // deal with cyclic relationships by not traversing down any node already in the results
357
if (results.contains(pathRootNodeRef))
358             {
359                 continue;
360             }
361             // get direct descendents along the path
362
List JavaDoc<NodeRef> directDescendents = getDirectDescendents(pathRootNodeRef, pathElement);
363             // recurse onto the descendents
364
addDescendents(directDescendents, pathElements, results);
365         }
366         
367         // restore the path element stack
368
pathElements.push(pathElement);
369     }
370     
371     /**
372      * Performs an XPath query to get the first-level descendents matching the given path
373      *
374      * @param pathRootNodeRef
375      * @param pathElement
376      * @return
377      */

378     private List JavaDoc<NodeRef> getDirectDescendents(NodeRef pathRootNodeRef, String JavaDoc pathElement)
379     {
380         if (logger.isDebugEnabled())
381         {
382             logger.debug("Getting direct descendents: \n" +
383                     " Path Root: " + pathRootNodeRef + "\n" +
384                     " Path Element: " + pathElement);
385         }
386         // escape for the Lucene syntax search
387
String JavaDoc escapedPathElement = SearchLanguageConversion.convertCifsToLucene(pathElement);
388         // do the lookup
389
List JavaDoc<org.alfresco.service.cmr.model.FileInfo> childInfos = fileFolderService.search(
390                 pathRootNodeRef,
391                 escapedPathElement,
392                 false);
393         // convert to noderefs
394
List JavaDoc<NodeRef> results = new ArrayList JavaDoc<NodeRef>(childInfos.size());
395         for (org.alfresco.service.cmr.model.FileInfo info : childInfos)
396         {
397             results.add(info.getNodeRef());
398         }
399         // done
400
return results;
401     }
402
403     /**
404      * Finds the nodes being reference by the given directory and file paths.
405      * <p>
406      * Examples of the path are:
407      * <ul>
408      * <li>\New Folder\New Text Document.txt</li>
409      * <li>\New Folder\Sub Folder</li>
410      * </ul>
411      *
412      * @param searchRootNodeRef the node from which to start the path search
413      * @param path the search path to either a folder or file
414      * @return Returns references to all matching nodes
415      */

416     public List JavaDoc<NodeRef> getNodeRefs(NodeRef pathRootNodeRef, String JavaDoc path)
417     {
418         // tokenize the path and push into a stack in reverse order so that
419
// the root directory gets popped first
420
StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(path, FileName.DOS_SEPERATOR_STR, false);
421         String JavaDoc[] tokens = new String JavaDoc[tokenizer.countTokens()];
422         int count = 0;
423         while(tokenizer.hasMoreTokens())
424         {
425             tokens[count] = tokenizer.nextToken();
426             count++;
427         }
428         Stack JavaDoc<String JavaDoc> pathElements = new Stack JavaDoc<String JavaDoc>();
429         for (int i = tokens.length - 1; i >= 0; i--)
430         {
431             pathElements.push(tokens[i]);
432         }
433         
434         // start with a single parent node
435
List JavaDoc<NodeRef> pathRootNodeRefs = Collections.singletonList(pathRootNodeRef);
436         
437         // result storage
438
List JavaDoc<NodeRef> results = new ArrayList JavaDoc<NodeRef>(5);
439         
440         // kick off the path walking
441
addDescendents(pathRootNodeRefs, pathElements, results);
442         
443         // done
444
if (logger.isDebugEnabled())
445         {
446             logger.debug("Retrieved node references for path: \n" +
447                     " path root: " + pathRootNodeRef + "\n" +
448                     " path: " + path + "\n" +
449                     " results: " + results);
450         }
451         return results;
452     }
453     
454     /**
455      * Attempts to fetch a specific single node at the given path.
456      *
457      * @throws FileNotFoundException if the path can't be resolved to a node
458      *
459      * @see #getNodeRefs(NodeRef, String)
460      */

461     public NodeRef getNodeRef(NodeRef pathRootNodeRef, String JavaDoc path) throws FileNotFoundException JavaDoc
462     {
463         // attempt to get the file/folder node using hierarchy walking
464
List JavaDoc<NodeRef> nodeRefs = getNodeRefs(pathRootNodeRef, path);
465         if (nodeRefs.size() == 0)
466         {
467             throw new FileNotFoundException JavaDoc(path);
468         }
469         else if (nodeRefs.size() > 1)
470         {
471             logger.warn("Multiple matching nodes: \n" +
472                     " search root: " + pathRootNodeRef + "\n" +
473                     " path: " + path);
474         }
475         // take the first one - not sure if it is possible for the path to refer to more than one
476
NodeRef nodeRef = nodeRefs.get(0);
477         // done
478
return nodeRef;
479     }
480
481     /**
482      * Relink the content data from a new node to an existing node to preserve the version history.
483      *
484      * @param oldNodeRef NodeRef
485      * @param newNodeRef NodeRef
486      */

487     public void relinkNode(NodeRef tempNodeRef, NodeRef nodeToMoveRef, NodeRef newParentNodeRef, String JavaDoc newName)
488             throws FileNotFoundException JavaDoc, FileExistsException
489     {
490         // Get the properties for the old and new nodes
491
org.alfresco.service.cmr.model.FileInfo tempFileInfo = fileFolderService.getFileInfo(tempNodeRef);
492         org.alfresco.service.cmr.model.FileInfo fileToMoveInfo = fileFolderService.getFileInfo(nodeToMoveRef);
493         
494         // Save the current name of the old node
495
String JavaDoc tempName = tempFileInfo.getName();
496
497         try
498         {
499             // rename temp file to the new name
500
fileFolderService.rename(tempNodeRef, newName);
501             // rename new file to old name
502
fileFolderService.rename(nodeToMoveRef, tempName);
503         }
504         catch (org.alfresco.service.cmr.model.FileNotFoundException e)
505         {
506             throw new FileNotFoundException JavaDoc(e.getMessage());
507         }
508         catch (org.alfresco.service.cmr.model.FileExistsException e)
509         {
510             throw new FileExistsException(e.getMessage());
511         }
512         
513         if (!tempFileInfo.isFolder() && !fileToMoveInfo.isFolder())
514         {
515             // swap the content between the two
516
ContentData oldContentData = tempFileInfo.getContentData();
517             if (oldContentData == null)
518             {
519                 String JavaDoc mimetype = mimetypeService.guessMimetype(tempName);
520                 oldContentData = ContentData.setMimetype(null, mimetype);
521             }
522             
523             ContentData newContentData = fileToMoveInfo.getContentData();
524
525             // Reset the mime type
526

527             String JavaDoc mimetype = mimetypeService.guessMimetype(newName);
528             newContentData = ContentData.setMimetype(newContentData, mimetype);
529
530             nodeService.setProperty(tempNodeRef, ContentModel.PROP_CONTENT, newContentData);
531             nodeService.setProperty(nodeToMoveRef, ContentModel.PROP_CONTENT, oldContentData);
532         }
533     }
534     
535     /**
536      * Move a node
537      *
538      * @param nodeToMoveRef Node to be moved
539      * @param newParentNodeRef New parent folder node
540      * @param newName New name for the moved node
541      * @throws FileExistsException
542      */

543     public void move(NodeRef nodeToMoveRef, NodeRef newParentNodeRef, String JavaDoc newName) throws FileExistsException
544     {
545         try
546         {
547             fileFolderService.move(nodeToMoveRef, newParentNodeRef, newName);
548         }
549         catch (org.alfresco.service.cmr.model.FileExistsException e)
550         {
551             throw new FileExistsException(newName);
552         }
553         catch (Throwable JavaDoc e)
554         {
555             throw new AlfrescoRuntimeException("Move failed: \n" +
556                     " node to move: " + nodeToMoveRef + "\n" +
557                     " new parent: " + newParentNodeRef + "\n" +
558                     " new name: " + newName,
559                     e);
560         }
561     }
562     
563     /**
564      * Return the file name for a node
565      *
566      * @param node NodeRef
567      * @return String
568      * @throws FileNotFoundException
569      */

570     public String JavaDoc getFileName(NodeRef node)
571     {
572         String JavaDoc fname = null;
573         
574         try
575         {
576             fname = (String JavaDoc) nodeService.getProperty( node, ContentModel.PROP_NAME);
577         }
578         catch (InvalidNodeRefException ex)
579         {
580         }
581         
582         return fname;
583     }
584 }
585
Popular Tags