KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > model > filefolder > FileFolderServiceImplTest


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.model.filefolder;
18
19 import java.io.InputStream JavaDoc;
20 import java.io.InputStreamReader JavaDoc;
21 import java.io.Reader JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.List JavaDoc;
24
25 import javax.transaction.UserTransaction JavaDoc;
26
27 import junit.framework.TestCase;
28
29 import org.alfresco.error.AlfrescoRuntimeException;
30 import org.alfresco.model.ContentModel;
31 import org.alfresco.repo.security.authentication.AuthenticationComponent;
32 import org.alfresco.service.ServiceRegistry;
33 import org.alfresco.service.cmr.model.FileExistsException;
34 import org.alfresco.service.cmr.model.FileFolderService;
35 import org.alfresco.service.cmr.model.FileInfo;
36 import org.alfresco.service.cmr.model.FileNotFoundException;
37 import org.alfresco.service.cmr.repository.ContentReader;
38 import org.alfresco.service.cmr.repository.ContentWriter;
39 import org.alfresco.service.cmr.repository.NodeRef;
40 import org.alfresco.service.cmr.repository.NodeService;
41 import org.alfresco.service.cmr.repository.StoreRef;
42 import org.alfresco.service.cmr.view.ImporterService;
43 import org.alfresco.service.cmr.view.Location;
44 import org.alfresco.service.namespace.NamespaceService;
45 import org.alfresco.service.namespace.QName;
46 import org.alfresco.service.transaction.TransactionService;
47 import org.alfresco.util.ApplicationContextHelper;
48 import org.springframework.context.ApplicationContext;
49
50 /**
51  * @see org.alfresco.repo.model.filefolder.FileFolderServiceImpl
52  *
53  * @author Derek Hulley
54  */

55 public class FileFolderServiceImplTest extends TestCase
56 {
57     private static final String JavaDoc IMPORT_VIEW = "filefolder/filefolder-test-import.xml";
58     
59     private static final String JavaDoc NAME_L0_FILE_A = "L0: File A";
60     private static final String JavaDoc NAME_L0_FILE_B = "L0: File B";
61     private static final String JavaDoc NAME_L0_FOLDER_A = "L0: Folder A";
62     private static final String JavaDoc NAME_L0_FOLDER_B = "L0: Folder B";
63     private static final String JavaDoc NAME_L0_FOLDER_C = "L0: Folder C";
64     private static final String JavaDoc NAME_L1_FOLDER_A = "L1: Folder A";
65     private static final String JavaDoc NAME_L1_FOLDER_B = "L1: Folder B";
66     private static final String JavaDoc NAME_L1_FILE_A = "L1: File A";
67     private static final String JavaDoc NAME_L1_FILE_B = "L1: File B";
68     private static final String JavaDoc NAME_L1_FILE_C = "L1: File C (%_)";
69     private static final String JavaDoc NAME_DUPLICATE = "DUPLICATE";
70     
71     private static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
72
73     private TransactionService transactionService;
74     private NodeService nodeService;
75     private FileFolderService fileFolderService;
76     private UserTransaction JavaDoc txn;
77     private NodeRef rootNodeRef;
78     private NodeRef workingRootNodeRef;
79     
80     @Override JavaDoc
81     public void setUp() throws Exception JavaDoc
82     {
83         ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean("ServiceRegistry");
84         transactionService = serviceRegistry.getTransactionService();
85         nodeService = serviceRegistry.getNodeService();
86         fileFolderService = serviceRegistry.getFileFolderService();
87         AuthenticationComponent authenticationComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
88
89         // start the transaction
90
txn = transactionService.getUserTransaction();
91         txn.begin();
92         
93         // authenticate
94
authenticationComponent.setCurrentUser(authenticationComponent.getSystemUserName());
95         
96         // create a test store
97
StoreRef storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, getName() + System.currentTimeMillis());
98         rootNodeRef = nodeService.getRootNode(storeRef);
99         
100         // create a folder to import into
101
workingRootNodeRef = nodeService.createNode(
102                 rootNodeRef,
103                 ContentModel.ASSOC_CHILDREN,
104                 QName.createQName(NamespaceService.ALFRESCO_URI, "working root"),
105                 ContentModel.TYPE_FOLDER).getChildRef();
106         
107         // import the test data
108
ImporterService importerService = serviceRegistry.getImporterService();
109         Location importLocation = new Location(workingRootNodeRef);
110         InputStream JavaDoc is = getClass().getClassLoader().getResourceAsStream(IMPORT_VIEW);
111         if (is == null)
112         {
113             throw new NullPointerException JavaDoc("Test resource not found: " + IMPORT_VIEW);
114         }
115         Reader JavaDoc reader = new InputStreamReader JavaDoc(is);
116         importerService.importView(reader, importLocation, null, null);
117     }
118     
119     public void tearDown() throws Exception JavaDoc
120     {
121         txn.rollback();
122     }
123
124     /**
125      * Checks that the names and numbers of files and folders in the provided list is correct
126      *
127      * @param files the list of files
128      * @param expectedFileCount the number of uniquely named files expected
129      * @param expectedFolderCount the number of uniquely named folders expected
130      * @param expectedNames the names of the files and folders expected
131      */

132     private void checkFileList(List JavaDoc<FileInfo> files, int expectedFileCount, int expectedFolderCount, String JavaDoc[] expectedNames)
133     {
134         int fileCount = 0;
135         int folderCount = 0;
136         List JavaDoc<String JavaDoc> check = new ArrayList JavaDoc<String JavaDoc>(8);
137         for (String JavaDoc filename : expectedNames)
138         {
139             check.add(filename);
140         }
141         for (FileInfo file : files)
142         {
143             if (file.isFolder())
144             {
145                 folderCount++;
146             }
147             else
148             {
149                 fileCount++;
150             }
151             check.remove(file.getName());
152         }
153         assertTrue("Name list was not exact - remaining: " + check, check.size() == 0);
154         assertEquals("Incorrect number of files", expectedFileCount, fileCount);
155         assertEquals("Incorrect number of folders", expectedFolderCount, folderCount);
156     }
157     
158     public void testShallowFilesAndFoldersList() throws Exception JavaDoc
159     {
160         List JavaDoc<FileInfo> files = fileFolderService.list(workingRootNodeRef);
161         // check
162
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L0_FILE_A, NAME_L0_FILE_B, NAME_L0_FOLDER_A, NAME_L0_FOLDER_B, NAME_L0_FOLDER_C};
163         checkFileList(files, 2, 3, expectedNames);
164     }
165     
166     public void testShallowFilesOnlyList() throws Exception JavaDoc
167     {
168         List JavaDoc<FileInfo> files = fileFolderService.listFiles(workingRootNodeRef);
169         // check
170
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L0_FILE_A, NAME_L0_FILE_B};
171         checkFileList(files, 2, 0, expectedNames);
172     }
173     
174     public void testShallowFoldersOnlyList() throws Exception JavaDoc
175     {
176         List JavaDoc<FileInfo> files = fileFolderService.listFolders(workingRootNodeRef);
177         // check
178
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L0_FOLDER_A, NAME_L0_FOLDER_B, NAME_L0_FOLDER_C};
179         checkFileList(files, 0, 3, expectedNames);
180     }
181     
182     public void testShallowFileSearch() throws Exception JavaDoc
183     {
184         List JavaDoc<FileInfo> files = fileFolderService.search(
185                 workingRootNodeRef,
186                 NAME_L0_FILE_B,
187                 true,
188                 false,
189                 false);
190         // check
191
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L0_FILE_B};
192         checkFileList(files, 1, 0, expectedNames);
193     }
194     
195     public void testDeepFilesAndFoldersSearch() throws Exception JavaDoc
196     {
197         List JavaDoc<FileInfo> files = fileFolderService.search(
198                 workingRootNodeRef,
199                 "?1:*",
200                 true,
201                 true,
202                 true);
203         // check
204
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L1_FOLDER_A, NAME_L1_FOLDER_B, NAME_L1_FILE_A, NAME_L1_FILE_B, NAME_L1_FILE_C};
205         checkFileList(files, 3, 2, expectedNames);
206     }
207     
208     public void testDeepFilesOnlySearch() throws Exception JavaDoc
209     {
210         List JavaDoc<FileInfo> files = fileFolderService.search(
211                 workingRootNodeRef,
212                 "?1:*",
213                 true,
214                 false,
215                 true);
216         // check
217
String JavaDoc[] expectedNames = new String JavaDoc[] {NAME_L1_FILE_A, NAME_L1_FILE_B, NAME_L1_FILE_C};
218         checkFileList(files, 3, 0, expectedNames);
219     }
220     
221     /**
222      * Helper to fetch a file or folder by name
223      *
224      * @param name the name of the file or folder
225      * @param isFolder true if we want a folder, otherwise false if we want a file
226      * @return Returns the info for the file or folder
227      */

228     private FileInfo getByName(String JavaDoc name, boolean isFolder) throws Exception JavaDoc
229     {
230         List JavaDoc<FileInfo> results = fileFolderService.search(workingRootNodeRef, name, !isFolder, isFolder, true);
231         if (results.size() > 1)
232         {
233             throw new AlfrescoRuntimeException("Name is not unique in hierarchy: \n" +
234                     " name: " + name + "\n" +
235                     " is folder: " + isFolder);
236         }
237         else if (results.size() == 0)
238         {
239             return null;
240         }
241         else
242         {
243             return results.get(0);
244         }
245     }
246
247     /**
248      * Ensure that an internal method is working - it gets used extensively by following tests
249      *
250      * @see #getByName(String, boolean)
251      */

252     public void testGetByName() throws Exception JavaDoc
253     {
254         FileInfo fileInfo = getByName(NAME_DUPLICATE, true);
255         assertNotNull(fileInfo);
256         assertTrue(fileInfo.isFolder());
257
258         fileInfo = getByName(NAME_DUPLICATE, false);
259         assertNotNull(fileInfo);
260         assertFalse(fileInfo.isFolder());
261     }
262     
263     public void testRenameNormal() throws Exception JavaDoc
264     {
265         FileInfo folderInfo = getByName(NAME_L0_FOLDER_A, true);
266         assertNotNull(folderInfo);
267         // rename normal
268
String JavaDoc newName = "DUPLICATE - renamed";
269         folderInfo = fileFolderService.rename(folderInfo.getNodeRef(), newName);
270         // check it
271
FileInfo checkInfo = getByName(NAME_L0_FOLDER_A, true);
272         assertNull("Folder info should have been renamed away", checkInfo);
273         checkInfo = getByName(newName, true);
274         assertNotNull("Folder info for new name is not present", checkInfo);
275     }
276     
277     public void testRenameDuplicate() throws Exception JavaDoc
278     {
279         FileInfo folderInfo = getByName(NAME_L0_FOLDER_A, true);
280         assertNotNull(folderInfo);
281         // rename duplicate. A file with that name already exists
282
String JavaDoc newName = NAME_L0_FILE_A;
283         try
284         {
285             folderInfo = fileFolderService.rename(folderInfo.getNodeRef(), newName);
286             fail("Existing file not detected");
287         }
288         catch (FileExistsException e)
289         {
290             // expected
291
}
292     }
293     
294     public void testMove() throws Exception JavaDoc
295     {
296         FileInfo folderToMoveInfo = getByName(NAME_L1_FOLDER_A, true);
297         assertNotNull(folderToMoveInfo);
298         NodeRef folderToMoveRef = folderToMoveInfo.getNodeRef();
299         // move it to the root
300
fileFolderService.move(folderToMoveRef, workingRootNodeRef, null);
301         // make sure that it is an immediate child of the root
302
List JavaDoc<FileInfo> checkFileInfos = fileFolderService.search(workingRootNodeRef, NAME_L1_FOLDER_A, false);
303         assertEquals("Folder not moved to root", 1, checkFileInfos.size());
304         // attempt illegal rename (existing)
305
try
306         {
307             fileFolderService.move(folderToMoveRef, null, NAME_L0_FOLDER_A);
308             fail("Existing folder not detected");
309         }
310         catch (FileExistsException e)
311         {
312             // expected
313
}
314         // rename properly
315
FileInfo checkFileInfo = fileFolderService.move(folderToMoveRef, null, "new name");
316         checkFileInfos = fileFolderService.search(workingRootNodeRef, checkFileInfo.getName(), false);
317         assertEquals("Folder not renamed in root", 1, checkFileInfos.size());
318     }
319     
320     public void testCopy() throws Exception JavaDoc
321     {
322         FileInfo folderToCopyInfo = getByName(NAME_L1_FOLDER_A, true);
323         assertNotNull(folderToCopyInfo);
324         NodeRef folderToCopyRef = folderToCopyInfo.getNodeRef();
325         // copy it to the root
326
folderToCopyInfo = fileFolderService.copy(folderToCopyRef, workingRootNodeRef, null);
327         folderToCopyRef = folderToCopyInfo.getNodeRef();
328         // make sure that it is an immediate child of the root
329
List JavaDoc<FileInfo> checkFileInfos = fileFolderService.search(workingRootNodeRef, NAME_L1_FOLDER_A, false);
330         assertEquals("Folder not copied to root", 1, checkFileInfos.size());
331         // attempt illegal copy (existing)
332
try
333         {
334             fileFolderService.copy(folderToCopyRef, null, NAME_L0_FOLDER_A);
335             fail("Existing folder not detected");
336         }
337         catch (FileExistsException e)
338         {
339             // expected
340
}
341         // copy properly
342
FileInfo checkFileInfo = fileFolderService.copy(folderToCopyRef, null, "new name");
343         checkFileInfos = fileFolderService.search(workingRootNodeRef, checkFileInfo.getName(), false);
344         assertEquals("Folder not renamed in root", 1, checkFileInfos.size());
345     }
346     
347     public void testCreateFolder() throws Exception JavaDoc
348     {
349         // we are testing failures as well
350
txn.commit();
351         // start a new one
352
txn = transactionService.getNonPropagatingUserTransaction();
353         txn.begin();
354         
355         FileInfo parentFolderInfo = getByName(NAME_L0_FOLDER_A, true);
356         assertNotNull(parentFolderInfo);
357         NodeRef parentFolderRef = parentFolderInfo.getNodeRef();
358         // create a file that already exists
359
UserTransaction JavaDoc rollbackTxn = null;
360         try
361         {
362             rollbackTxn = transactionService.getNonPropagatingUserTransaction();
363             rollbackTxn.begin();
364             fileFolderService.create(parentFolderRef, NAME_L1_FILE_A, ContentModel.TYPE_CONTENT);
365             fail("Failed to detect duplicate filename");
366         }
367         catch (FileExistsException e)
368         {
369             // expected
370
}
371         finally
372         {
373             rollbackTxn.rollback();
374         }
375         // create folder of illegal type
376
try
377         {
378             rollbackTxn = transactionService.getNonPropagatingUserTransaction();
379             rollbackTxn.begin();
380             fileFolderService.create(parentFolderRef, "illegal folder", ContentModel.TYPE_SYSTEM_FOLDER);
381             fail("Illegal type not detected");
382         }
383         catch (RuntimeException JavaDoc e)
384         {
385             // expected
386
}
387         finally
388         {
389             rollbackTxn.rollback();
390         }
391
392         // create a file
393
FileInfo fileInfo = fileFolderService.create(parentFolderRef, "newFile", ContentModel.TYPE_CONTENT);
394         // check
395
assertTrue("Node not created", nodeService.exists(fileInfo.getNodeRef()));
396         assertFalse("File type expected", fileInfo.isFolder());
397     }
398     
399     public void testCreateFile() throws Exception JavaDoc
400     {
401         
402     }
403     
404     public void testCreateInRoot() throws Exception JavaDoc
405     {
406         fileFolderService.create(rootNodeRef, "New Folder", ContentModel.TYPE_FOLDER);
407     }
408     
409     public void testMakeFolders() throws Exception JavaDoc
410     {
411         // create a completely new path below the root
412
List JavaDoc<String JavaDoc> namePath = new ArrayList JavaDoc<String JavaDoc>(4);
413         namePath.add("A");
414         namePath.add("B");
415         namePath.add("C");
416         namePath.add("D");
417         
418         FileInfo lastFileInfo = fileFolderService.makeFolders(rootNodeRef, namePath, ContentModel.TYPE_FOLDER);
419         assertNotNull("First makeFolder failed", lastFileInfo);
420         // check that a repeat works
421
FileInfo lastFileInfoAgain = fileFolderService.makeFolders(rootNodeRef, namePath, ContentModel.TYPE_FOLDER);
422         assertNotNull("Repeat makeFolders failed", lastFileInfoAgain);
423         assertEquals("Repeat created new leaf", lastFileInfo.getNodeRef(), lastFileInfoAgain.getNodeRef());
424         // check that it worked
425
List JavaDoc<FileInfo> checkInfos = fileFolderService.search(rootNodeRef, "D", false, true, true);
426         assertEquals("Expected to find a result", 1, checkInfos.size());
427         // get the path
428
List JavaDoc<FileInfo> checkPathInfos = fileFolderService.getNamePath(rootNodeRef, checkInfos.get(0).getNodeRef());
429         assertEquals("Path created is incorrect", namePath.size(), checkPathInfos.size());
430         int i = 0;
431         for (FileInfo checkInfo : checkPathInfos)
432         {
433             assertEquals("Path mismatch", namePath.get(i), checkInfo.getName());
434             i++;
435         }
436     }
437     
438     public void testGetNamePath() throws Exception JavaDoc
439     {
440         FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);
441         assertNotNull(fileInfo);
442         NodeRef nodeRef = fileInfo.getNodeRef();
443         
444         List JavaDoc<FileInfo> infoPaths = fileFolderService.getNamePath(workingRootNodeRef, nodeRef);
445         assertEquals("Not enough elements", 2, infoPaths.size());
446         assertEquals("First level incorrent", NAME_L0_FOLDER_A, infoPaths.get(0).getName());
447         assertEquals("Second level incorrent", NAME_L1_FILE_A, infoPaths.get(1).getName());
448         
449         // pass in a null root and make sure that it still works
450
infoPaths = fileFolderService.getNamePath(null, nodeRef);
451         assertEquals("Not enough elements", 3, infoPaths.size());
452         assertEquals("First level incorrent", workingRootNodeRef.getId(), infoPaths.get(0).getName());
453         assertEquals("Second level incorrent", NAME_L0_FOLDER_A, infoPaths.get(1).getName());
454         assertEquals("Third level incorrent", NAME_L1_FILE_A, infoPaths.get(2).getName());
455         
456         // check that a non-aligned path is detected
457
NodeRef startRef = getByName(NAME_L0_FOLDER_B, true).getNodeRef();
458         try
459         {
460             fileFolderService.getNamePath(startRef, nodeRef);
461             fail("Failed to detect non-aligned path from root to target node");
462         }
463         catch (FileNotFoundException e)
464         {
465             // expected
466
}
467     }
468     
469     public void testResolveNamePath() throws Exception JavaDoc
470     {
471         FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);
472         List JavaDoc<String JavaDoc> pathElements = new ArrayList JavaDoc<String JavaDoc>(3);
473         pathElements.add(NAME_L0_FOLDER_A);
474         pathElements.add(NAME_L1_FILE_A);
475         
476         FileInfo fileInfoCheck = fileFolderService.resolveNamePath(workingRootNodeRef, pathElements);
477         assertNotNull("File info not found", fileInfoCheck);
478         assertEquals("Path not resolved to correct node", fileInfo.getNodeRef(), fileInfoCheck.getNodeRef());
479     }
480     
481     public void testGetReaderWriter() throws Exception JavaDoc
482     {
483         // testing a failure
484
txn.commit();
485         txn = transactionService.getUserTransaction();
486         txn.begin();
487         
488         FileInfo dirInfo = getByName(NAME_L0_FOLDER_A, true);
489         
490         UserTransaction JavaDoc rollbackTxn = null;
491         try
492         {
493             rollbackTxn = transactionService.getNonPropagatingUserTransaction();
494             rollbackTxn.begin();
495             fileFolderService.getWriter(dirInfo.getNodeRef());
496             fail("Failed to detect content write to folder");
497         }
498         catch (RuntimeException JavaDoc e)
499         {
500             // expected
501
}
502         finally
503         {
504             rollbackTxn.rollback();
505         }
506         
507         FileInfo fileInfo = getByName(NAME_L1_FILE_A, false);
508         
509         ContentWriter writer = fileFolderService.getWriter(fileInfo.getNodeRef());
510         assertNotNull("Writer is null", writer);
511         // write some content
512
String JavaDoc content = "ABC";
513         writer.putContent(content);
514         // read the content
515
ContentReader reader = fileFolderService.getReader(fileInfo.getNodeRef());
516         assertNotNull("Reader is null", reader);
517         String JavaDoc checkContent = reader.getContentString();
518         assertEquals("Content mismatch", content, checkContent);
519     }
520 }
521
Popular Tags