KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > test > OpenCmsTestCase


1 /*
2  * File : $Source: /usr/local/cvs/opencms/test/org/opencms/test/OpenCmsTestCase.java,v $
3  * Date : $Date: 2006/09/21 09:34:47 $
4  * Version: $Revision: 1.93 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (c) 2005 Alkacon Software GmbH (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software GmbH, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.test;
33
34 import org.opencms.db.CmsDbPool;
35 import org.opencms.file.CmsFile;
36 import org.opencms.file.CmsGroup;
37 import org.opencms.file.CmsObject;
38 import org.opencms.file.CmsProject;
39 import org.opencms.file.CmsProperty;
40 import org.opencms.file.CmsPropertyDefinition;
41 import org.opencms.file.CmsResource;
42 import org.opencms.file.CmsResourceFilter;
43 import org.opencms.file.CmsUser;
44 import org.opencms.file.types.CmsResourceTypeBinary;
45 import org.opencms.file.types.CmsResourceTypeFolder;
46 import org.opencms.file.types.CmsResourceTypePlain;
47 import org.opencms.lock.CmsLock;
48 import org.opencms.main.CmsException;
49 import org.opencms.main.CmsShell;
50 import org.opencms.main.CmsSystemInfo;
51 import org.opencms.main.OpenCms;
52 import org.opencms.report.CmsShellReport;
53 import org.opencms.security.CmsAccessControlEntry;
54 import org.opencms.security.CmsAccessControlList;
55 import org.opencms.security.CmsPermissionSet;
56 import org.opencms.setup.CmsSetupDb;
57 import org.opencms.util.CmsDateUtil;
58 import org.opencms.util.CmsFileUtil;
59 import org.opencms.util.CmsPropertyUtils;
60 import org.opencms.util.CmsUUID;
61
62 import java.io.File JavaDoc;
63 import java.io.FileInputStream JavaDoc;
64 import java.io.IOException JavaDoc;
65 import java.util.ArrayList JavaDoc;
66 import java.util.HashMap JavaDoc;
67 import java.util.Iterator JavaDoc;
68 import java.util.List JavaDoc;
69 import java.util.Map JavaDoc;
70 import java.util.Vector JavaDoc;
71
72 import junit.framework.TestCase;
73
74 import org.apache.commons.collections.ExtendedProperties;
75
76 import org.dom4j.Document;
77 import org.dom4j.Node;
78 import org.dom4j.util.NodeComparator;
79
80 /**
81  * Extends the JUnit standard with methods to handle an OpenCms database
82  * test instance.<p>
83  *
84  * The required configuration files are located in the
85  * <code>${test.data.path}/WEB-INF</code> folder structure.<p>
86  *
87  * To run this test you might have to change the database connection
88  * values in the provided <code>${test.data.path}/WEB-INF/config/opencms.properties</code> file.<p>
89  *
90  * @author Alexander Kandzior
91  *
92  * @version $Revision: 1.93 $
93  *
94  * @since 6.0.0
95  */

96 public class OpenCmsTestCase extends TestCase {
97
98     /** Class to bundle the connection information. */
99     protected class ConnectionData {
100
101         /** The name of the database. */
102         public String JavaDoc m_dbName;
103
104         /** The database driver. */
105         public String JavaDoc m_jdbcDriver;
106
107         /** The database url. */
108         public String JavaDoc m_jdbcUrl;
109
110         /** Additional database params. */
111         public String JavaDoc m_jdbcUrlParams;
112
113         /** The name of the user. */
114         public String JavaDoc m_userName;
115
116         /** The password of the user. */
117         public String JavaDoc m_userPassword;
118     }
119
120     /**
121      * Extension of <code>NodeComparator</code> to store unequal nodes.<p>
122      */

123     class InternalNodeComparator extends NodeComparator {
124
125         /** Unequal node1. */
126         public Node m_node1 = null;
127
128         /** Unequal node2. */
129         public Node m_node2 = null;
130
131         /**
132          * @see org.dom4j.util.NodeComparator#compare(org.dom4j.Node, org.dom4j.Node)
133          */

134         public int compare(Node n1, Node n2) {
135
136             int result = super.compare(n1, n2);
137             if (result != 0 && m_node1 == null) {
138                 m_node1 = n1;
139                 m_node2 = n2;
140             }
141             return result;
142         }
143     }
144
145     /** Key for tests on MySql database. */
146     public static final String JavaDoc DB_MYSQL = "mysql";
147
148     /** Key for tests on Oracle database. */
149     public static final String JavaDoc DB_ORACLE = "oracle";
150
151     /** The OpenCms/database configuration. */
152     public static ExtendedProperties m_configuration = null;
153
154     /** DB product used for the tests. */
155     public static String JavaDoc m_dbProduct = DB_MYSQL;
156
157     /** Name of the default tablespace (oracle only). */
158     public static String JavaDoc m_defaultTablespace;
159
160     /** Name of the index tablespace (oracle only). */
161     public static String JavaDoc m_indexTablespace;
162
163     /** The internal storages. */
164     public static HashMap JavaDoc m_resourceStorages;
165
166     /** Name of the temporary tablespace (oracle only). */
167     public static String JavaDoc m_tempTablespace;
168
169     /** Additional connection data. */
170     protected static ConnectionData m_additionalConnection;
171
172     /** The user connection data. */
173     protected static ConnectionData m_defaultConnection;
174
175     /** The setup connection data. */
176     protected static ConnectionData m_setupConnection;
177
178     /** The additional connection name. */
179     private static String JavaDoc m_additionalConnectionName = "additional";
180
181     /** The file date of the configuration files. */
182     private static long[] m_dateConfigFiles;
183
184     /** The path to the default setup data files. */
185     private static String JavaDoc m_setupDataPath;
186
187     /** The initialized OpenCms shell instance. */
188     private static CmsShell m_shell;
189
190     /** The list of paths to the additional test data files. */
191     private static List m_testDataPath;
192
193     /** The current resource storage. */
194     public OpenCmsTestResourceStorage m_currentResourceStrorage;
195
196     /**
197      * Default JUnit constructor.<p>
198      *
199      * @param arg0 JUnit parameters
200      */

201     public OpenCmsTestCase(String JavaDoc arg0) {
202
203         this(arg0, true);
204     }
205
206     /**
207      * JUnit constructor.<p>
208      * @param arg0 JUnit parameters
209      * @param initialize indicates if the configuration will be initialized
210      */

211     public OpenCmsTestCase(String JavaDoc arg0, boolean initialize) {
212
213         super(arg0);
214         if (initialize) {
215             OpenCmsTestLogAppender.setBreakOnError(false);
216             if (m_resourceStorages == null) {
217                 m_resourceStorages = new HashMap JavaDoc();
218             }
219
220             // initialize configuration
221
initConfiguration();
222
223             // set "OpenCmsLog" system property to enable the logger
224
OpenCmsTestLogAppender.setBreakOnError(true);
225         }
226     }
227
228     /**
229      * Generates a sub tree of folders with files.<p>
230      *
231      * @param cms the cms context
232      * @param vfsFolder where to create the subtree
233      * @param maxWidth an upper bound for the number of subfolder a folder should have
234      * @param maxDepth an upper bound for depth of the genearted subtree
235      * @param maxProps upper bound for number of properties to create for each resource
236      * @param propertyDistribution a percentage: x% shared props and (1-x)% individuals props
237      * @param maxNumberOfFiles upper bound for the number of files in each folder
238      * @param fileTypeDistribution a percentage: x% binary files and (1-x)% text files
239      *
240      * @return the number of really written files
241      *
242      * @throws Exception if something goes wrong
243      */

244     public static int generateContent(
245         CmsObject cms,
246         String JavaDoc vfsFolder,
247         int maxWidth,
248         int maxDepth,
249         int maxProps,
250         double propertyDistribution,
251         int maxNumberOfFiles,
252         double fileTypeDistribution) throws Exception JavaDoc {
253
254         int fileNameLength = 10;
255         int propValueLength = 10;
256
257         // end recursion
258
if (maxDepth < 1) {
259             return 0;
260         }
261         if (!vfsFolder.endsWith("/")) {
262             vfsFolder += "/";
263         }
264
265         int writtenFiles = 0;
266
267         int width = (int)(maxWidth * Math.random()) + 1;
268         int depth = maxDepth - (int)(2 * Math.random());
269         for (int i = 0; i < width; i++) {
270             // generate folder
271
String JavaDoc vfsName = vfsFolder + generateName(fileNameLength) + i;
272             List props = generateProperties(cms, maxProps, propValueLength, propertyDistribution);
273             cms.createResource(vfsName, CmsResourceTypeFolder.getStaticTypeId(), new byte[0], props);
274             cms.unlockResource(vfsName);
275
276             int numberOfFiles = (int)(maxNumberOfFiles * Math.random()) + 1;
277             // generate binary files
278
int numberOfBinaryFiles = (int)(numberOfFiles * fileTypeDistribution);
279             writtenFiles += generateResources(
280                 cms,
281                 "org/opencms/search/pdf-test-112.pdf",
282                 vfsName,
283                 numberOfBinaryFiles,
284                 CmsResourceTypeBinary.getStaticTypeId(),
285                 maxProps,
286                 propertyDistribution);
287
288             // generate text files
289
writtenFiles += generateResources(cms, "org/opencms/search/extractors/test1.html", vfsName, numberOfFiles
290                 - numberOfBinaryFiles, CmsResourceTypePlain.getStaticTypeId(), maxProps, propertyDistribution);
291
292             // in depth recursion
293
writtenFiles += generateContent(
294                 cms,
295                 vfsName,
296                 maxWidth,
297                 depth - 1,
298                 maxProps,
299                 propertyDistribution,
300                 maxNumberOfFiles,
301                 fileTypeDistribution);
302
303             System.out.println("" + writtenFiles + " files written in Folder " + vfsName);
304         }
305         return writtenFiles;
306     }
307
308     /**
309      * Generates a sub tree of folders with files.<p>
310      *
311      * @param cms the cms context
312      * @param vfsFolder name of the folder
313      * @param numberOfFiles the number of files to generate
314      * @param fileTypeDistribution a percentage: x% binary files and (1-x)% text files
315      *
316      * @return the number of files generated
317      *
318      * @throws Exception if something goes wrong
319      */

320     public static int generateContent(CmsObject cms, String JavaDoc vfsFolder, int numberOfFiles, double fileTypeDistribution)
321     throws Exception JavaDoc {
322
323         int maxProps = 10;
324         double propertyDistribution = 0.0;
325         int writtenFiles = 0;
326
327         int numberOfBinaryFiles = (int)(numberOfFiles * fileTypeDistribution);
328
329         // generate binary files
330
writtenFiles += generateResources(
331             cms,
332             "org/opencms/search/pdf-test-112.pdf",
333             vfsFolder,
334             numberOfBinaryFiles,
335             CmsResourceTypeBinary.getStaticTypeId(),
336             maxProps,
337             propertyDistribution);
338
339         // generate text files
340
writtenFiles += generateResources(cms, "org/opencms/search/extractors/test1.html", vfsFolder, numberOfFiles
341             - numberOfBinaryFiles, CmsResourceTypePlain.getStaticTypeId(), maxProps, propertyDistribution);
342
343         System.out.println("" + writtenFiles + " files written in Folder " + vfsFolder);
344
345         return writtenFiles;
346     }
347
348     /**
349      * Generates n new resources in a given folder.<p>
350      *
351      * @param cms the cms context
352      * @param rfsName the rfs file for the content
353      * @param vfsFolder the folder to create the resources in
354      * @param n number of resources to generate
355      * @param type the type of the resource
356      * @param maxProps upper bound for number of properties to create for each resource
357      * @param propertyDistribution a percentage: x% shared props and (1-x)% individuals props
358      *
359      * @return the number of really written files
360      *
361      * @throws Exception if something goes wrong
362      */

363     public static int generateResources(
364         CmsObject cms,
365         String JavaDoc rfsName,
366         String JavaDoc vfsFolder,
367         int n,
368         int type,
369         int maxProps,
370         double propertyDistribution) throws Exception JavaDoc {
371
372         int fileNameLength = 10;
373         int propValueLength = 10;
374
375         if (!vfsFolder.endsWith("/")) {
376             vfsFolder += "/";
377         }
378         int writtenFiles = 0;
379         System.out.println("Importing files");
380         for (int i = 0; i < n; i++) {
381             String JavaDoc vfsName = vfsFolder + generateName(fileNameLength) + i;
382             if (rfsName.lastIndexOf('.') > 0) {
383                 vfsName += rfsName.substring(rfsName.lastIndexOf('.'));
384             }
385
386             List props = generateProperties(cms, maxProps, propValueLength, propertyDistribution);
387             try {
388                 OpenCmsTestCase.importTestResource(cms, rfsName, vfsName, type, props);
389                 writtenFiles++;
390             } catch (Exception JavaDoc e) {
391                 System.out.println("error! " + e.getMessage());
392             }
393         }
394         return writtenFiles;
395     }
396
397     /**
398      * Generate a new random name.<p>
399      *
400      * @param maxLen upper bound for the length of the name
401      *
402      * @return a random name
403      */

404     public static String JavaDoc generateName(int maxLen) {
405
406         String JavaDoc name = "";
407         int len = (int)(maxLen * Math.random()) + 1;
408         for (int j = 0; j < len; j++) {
409             name += (char)(25 * Math.random() + 97);
410         }
411         return name;
412     }
413
414     /**
415      * Generates random properties.<p>
416      *
417      * @param cms the cms context
418      * @param maxProps upper bound for number of properties to create for each resource
419      * @param propValueLength upper bound for the number of char for the values
420      * @param propertyDistribution a percentage: x% shared props and (1-x)% individuals props
421      *
422      * @return a list of <code>{@link CmsProperty}</code> objects
423      *
424      * @throws CmsException if something goes wrong
425      */

426     public static List generateProperties(CmsObject cms, int maxProps, int propValueLength, double propertyDistribution)
427     throws CmsException {
428
429         List propList = cms.readAllPropertyDefinitions();
430
431         List props = new ArrayList JavaDoc();
432         if (maxProps > propList.size()) {
433             maxProps = propList.size();
434         }
435         int propN = (int)(Math.random() * maxProps) + 1;
436         for (int j = 0; j < propN; j++) {
437             CmsPropertyDefinition propDef = (CmsPropertyDefinition)propList.get((int)(Math.random() * propList.size()));
438             propList.remove(propDef);
439             if (Math.random() < propertyDistribution) {
440                 // only resource prop
441
props.add(new CmsProperty(propDef.getName(), null, generateName(propValueLength)));
442             } else {
443                 // resource and structure props
444
props.add(new CmsProperty(
445                     propDef.getName(),
446                     generateName(propValueLength),
447                     generateName(propValueLength)));
448             }
449         }
450
451         return props;
452     }
453
454     /**
455      * Generates n new users for a given group.<p>
456      *
457      * @param cms the cms context
458      * @param groupName the group name, group will be creating if group does not exists
459      * @param n number of users to generate
460      *
461      * @throws CmsException if something goes wrong
462      */

463     public static void generateUsers(CmsObject cms, String JavaDoc groupName, int n) throws CmsException {
464
465         CmsGroup group = null;
466         try {
467             group = cms.readGroup(groupName);
468         } catch (Exception JavaDoc e) {
469             // ignore
470
}
471         if (group == null) {
472             group = cms.createGroup(groupName, groupName, 0, null);
473         }
474         for (int i = 0; i < n; i++) {
475             String JavaDoc name = generateName(10) + i;
476             cms.createUser(name, "pwd" + i, "test user " + i, null);
477             cms.addUserToGroup(name, groupName);
478         }
479     }
480
481     /**
482      * Returns the currently used database/configuration.<p>
483      *
484      * @return he currently used database/configuration
485      */

486     public static String JavaDoc getDbProduct() {
487
488         return m_dbProduct;
489     }
490
491     /**
492      * Initializes the path to the test data configuration files
493      * using the default path.<p>
494      */

495     public static synchronized void initTestDataPath() {
496
497         if (m_testDataPath == null) {
498             m_testDataPath = new ArrayList JavaDoc(4);
499
500             // test wether we are instantiated within the
501
// AllTest suite and therefore the OpenCmsTestProperties are
502
// already set up:
503
try {
504                 OpenCmsTestProperties.getInstance();
505             } catch (RuntimeException JavaDoc rte) {
506                 OpenCmsTestProperties.initialize(org.opencms.test.AllTests.TEST_PROPERTIES_PATH);
507             }
508             // set data path
509
addTestDataPath(OpenCmsTestProperties.getInstance().getTestDataPath());
510         }
511     }
512
513     /**
514      * Removes the initialized OpenCms database and all
515      * temporary files created during the test run.<p>
516      */

517     public static void removeOpenCms() {
518
519         // ensure logging does not throw exceptions
520
OpenCmsTestLogAppender.setBreakOnError(false);
521
522         // output a message
523
m_shell.printPrompt();
524         System.out.println("----- Test cases finished -----");
525
526         // exit the shell
527
m_shell.exit();
528
529         // remove the database
530
removeDatabase();
531
532         // copy the configuration files to re-create the original configuration
533
String JavaDoc configFolder = getTestDataPath("WEB-INF" + File.separator + "config." + m_dbProduct + File.separator);
534         copyConfiguration(configFolder);
535
536         // remove potentially created "classes, "lib", "backup" etc. folder
537
String JavaDoc path;
538         path = getTestDataPath("WEB-INF/classes/");
539         if (path != null) {
540             CmsFileUtil.purgeDirectory(new File(path));
541         }
542         path = getTestDataPath("WEB-INF/lib/");
543         if (path != null) {
544             CmsFileUtil.purgeDirectory(new File(path));
545         }
546         path = getTestDataPath("WEB-INF/" + CmsSystemInfo.FOLDER_CONFIG + "backup/");
547         if (path != null) {
548             CmsFileUtil.purgeDirectory(new File(path));
549         }
550         path = getTestDataPath("WEB-INF/index/");
551         if (path != null) {
552             CmsFileUtil.purgeDirectory(new File(path));
553         }
554         path = getTestDataPath("export/");
555         if (path != null) {
556             CmsFileUtil.purgeDirectory(new File(path));
557         }
558
559         try {
560             // sleep 0.5 seconds - sometimes other Threads need to finish before the next test case can start
561
Thread.sleep(500);
562         } catch (InterruptedException JavaDoc e) {
563             // ignore
564
}
565     }
566
567     /**
568      * Restarts the OpenCms shell.<p>
569      */

570     public static void restartOpenCms() {
571
572         // turn off exceptions after error logging during setup (won't work otherwise)
573
OpenCmsTestLogAppender.setBreakOnError(false);
574         // output a message
575
System.out.println("\n\n\n----- Restarting OpenCms -----");
576
577         // kill any old shell that might have remained from a previous test
578
if (m_shell != null) {
579             try {
580                 m_shell.exit();
581                 m_shell = null;
582             } catch (Throwable JavaDoc t) {
583                 // ignore
584
}
585         }
586
587         // create a shell instance
588
m_shell = new CmsShell(getTestDataPath("WEB-INF" + File.separator), null, null, "${user}@${project}>", null);
589
590         // turn on exceptions after error logging
591
OpenCmsTestLogAppender.setBreakOnError(true);
592     }
593
594     /**
595      * Sets the additional connection name.<p>
596      *
597      * @param additionalConnectionName the additional connection name
598      */

599     public static void setConnectionName(String JavaDoc additionalConnectionName) {
600
601         m_additionalConnectionName = additionalConnectionName;
602     }
603
604     /**
605      * Sets up a complete OpenCms instance with configuration from the config-ori folder,
606      * creating the usual projects, and importing a default database.<p>
607      *
608      * @param importFolder the folder to import in the "real" FS
609      * @param targetFolder the target folder of the import in the VFS
610      * @return an initialized OpenCms context with "Admin" user in the "Offline" project with the site root set to "/"
611      */

612     public static CmsObject setupOpenCms(String JavaDoc importFolder, String JavaDoc targetFolder) {
613
614         return setupOpenCms(importFolder, targetFolder, getTestDataPath("WEB-INF/config." + m_dbProduct + "/"), true);
615     }
616
617     /**
618      * Sets up a complete OpenCms instance with configuration from the config-ori folder,
619      * creating the usual projects, and importing a default database.<p>
620      *
621      * @param importFolder the folder to import in the "real" FS
622      * @param targetFolder the target folder of the import in the VFS
623      * @param publish flag to signalize if the publish script should be called
624      * @return an initialized OpenCms context with "Admin" user in the "Offline" project with the site root set to "/"
625      */

626     public static CmsObject setupOpenCms(String JavaDoc importFolder, String JavaDoc targetFolder, boolean publish) {
627
628         return setupOpenCms(importFolder, targetFolder, getTestDataPath("WEB-INF/config." + m_dbProduct + "/"), publish);
629     }
630
631     /**
632      * Sets up a complete OpenCms instance, creating the usual projects,
633      * and importing a default database.<p>
634      *
635      * @param importFolder the folder to import in the "real" FS
636      * @param targetFolder the target folder of the import in the VFS
637      * @param configFolder the folder to copy the configuration files
638      * @param publish TODO:
639      *
640      * @return an initialized OpenCms context with "Admin" user in the "Offline" project with the site root set to "/"
641      */

642     public static CmsObject setupOpenCms(String JavaDoc importFolder, String JavaDoc targetFolder, String JavaDoc configFolder, boolean publish) {
643
644         // intialize a new resource storage
645
m_resourceStorages = new HashMap JavaDoc();
646
647         // turn off exceptions after error logging during setup (won't work otherwise)
648
OpenCmsTestLogAppender.setBreakOnError(false);
649         // output a message
650
System.out.println("\n\n\n----- Starting test case: Importing OpenCms VFS data -----");
651
652         // kill any old shell that might have remained from a previous test
653
if (m_shell != null) {
654             try {
655                 m_shell.exit();
656                 m_shell = null;
657             } catch (Throwable JavaDoc t) {
658                 // ignore
659
}
660         }
661
662         // copy the configuration files
663
copyConfiguration(configFolder);
664
665         // create a new database first
666
setupDatabase();
667
668         // create a shell instance
669
m_shell = new CmsShell(getTestDataPath("WEB-INF" + File.separator), null, null, "${user}@${project}>", null);
670
671         // open the test script
672
File script;
673         FileInputStream JavaDoc stream = null;
674         CmsObject cms = null;
675
676         try {
677             // start the shell with the base script
678
script = new File(getTestDataPath("scripts/script_base.txt"));
679             stream = new FileInputStream JavaDoc(script);
680             m_shell.start(stream);
681
682             // add the default folders by script
683
script = new File(getTestDataPath("scripts/script_default_folders.txt"));
684             stream = new FileInputStream JavaDoc(script);
685             m_shell.start(stream);
686
687             // log in the Admin user and switch to the setup project
688
cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest());
689             cms.loginUser("Admin", "admin");
690             cms.getRequestContext().setCurrentProject(cms.readProject("_setupProject"));
691
692             if (importFolder != null) {
693                 // import the "simpletest" files
694
importResources(cms, importFolder, targetFolder);
695             }
696
697             // create the default projects by script
698
script = new File(getTestDataPath("scripts/script_default_projects.txt"));
699             stream = new FileInputStream JavaDoc(script);
700             m_shell.start(stream);
701
702             if (publish) {
703                 // publish the current project by script
704
script = new File(getTestDataPath("scripts/script_publish.txt"));
705                 stream = new FileInputStream JavaDoc(script);
706                 m_shell.start(stream);
707             } else {
708                 cms.unlockProject(cms.readProject("_setupProject").getId());
709             }
710
711             // switch to the "Offline" project
712
cms.getRequestContext().setCurrentProject(cms.readProject("Offline"));
713             cms.getRequestContext().setSiteRoot("/sites/default/");
714
715             // output a message
716
System.out.println("----- Starting test cases -----");
717         } catch (Throwable JavaDoc t) {
718             t.printStackTrace(System.err);
719             fail("Unable to setup OpenCms\n" + CmsException.getStackTraceAsString(t));
720         }
721         // turn on exceptions after error logging
722
OpenCmsTestLogAppender.setBreakOnError(true);
723         // return the initialized cms context Object
724
return cms;
725     }
726
727     /**
728      * Adds an additional path to the list of test data configuration files.<p>
729      *
730      * @param dataPath the path to add
731      */

732     protected static synchronized void addTestDataPath(String JavaDoc dataPath) {
733
734         // check if the db data folder is available
735
File testDataFolder = new File(dataPath);
736         if (!testDataFolder.exists()) {
737             fail("DB setup data not available at " + testDataFolder.getAbsolutePath());
738         }
739         m_testDataPath.add(CmsFileUtil.normalizePath(testDataFolder.getAbsolutePath() + File.separator));
740     }
741
742     /**
743      * Check the setup DB for errors that might have occured.<p>
744      *
745      * @param setupDb the setup DB object to check
746      */

747     protected static void checkErrors(CmsSetupDb setupDb) {
748
749         if (!setupDb.noErrors()) {
750             Vector JavaDoc errors = setupDb.getErrors();
751             for (Iterator JavaDoc i = errors.iterator(); i.hasNext();) {
752                 String JavaDoc error = (String JavaDoc)i.next();
753                 System.out.println(error);
754             }
755             fail((String JavaDoc)setupDb.getErrors().get(0));
756         }
757     }
758
759     /**
760      * Returns an initialized replacer map.<p>
761      *
762      * @param connectionData the connection data to derive the replacer information
763      *
764      * @return an initialized replacer map
765      */

766     protected static Map JavaDoc getReplacer(ConnectionData connectionData) {
767
768         Map JavaDoc replacer = new HashMap JavaDoc();
769         replacer.put("${database}", connectionData.m_dbName);
770         replacer.put("${user}", connectionData.m_userName);
771         replacer.put("${password}", connectionData.m_userPassword);
772         replacer.put("${defaultTablespace}", m_defaultTablespace);
773         replacer.put("${indexTablespace}", m_indexTablespace);
774         replacer.put("${temporaryTablespace}", m_tempTablespace);
775
776         return replacer;
777     }
778
779     /**
780      * Returns the path to the data files used by the setup wizard.<p>
781      *
782      * Whenever possible use this path to ensure that the files
783      * used for testing are actually the same as for the setup.<p>
784      *
785      * @return the path to the data files used by the setup wizard
786      */

787     protected static synchronized String JavaDoc getSetupDataPath() {
788
789         if (m_setupDataPath == null) {
790             // check if the db setup files are available
791
File setupDataFolder = new File(OpenCmsTestProperties.getInstance().getTestWebappPath());
792             if (!setupDataFolder.exists()) {
793                 fail("DB setup data not available at " + setupDataFolder.getAbsolutePath());
794             }
795             m_setupDataPath = setupDataFolder.getAbsolutePath() + File.separator;
796         }
797         // return the path name
798
return m_setupDataPath;
799     }
800
801     /**
802      * Returns an initialized DB setup object.<p>
803      *
804      * @param connection the connection data
805      *
806      * @return the initialized setup DB object
807      */

808     protected static CmsSetupDb getSetupDb(ConnectionData connection) {
809
810         // create setup DB instance
811
CmsSetupDb setupDb = new CmsSetupDb(getSetupDataPath());
812
813         // connect to the DB
814
setupDb.setConnection(
815             connection.m_jdbcDriver,
816             connection.m_jdbcUrl,
817             connection.m_jdbcUrlParams,
818             connection.m_userName,
819             connection.m_userPassword);
820
821         // check for errors
822
if (!DB_ORACLE.equals(m_dbProduct)) {
823             checkErrors(setupDb);
824         }
825
826         return setupDb;
827     }
828
829     /**
830      * Returns the path to a file in the test data configuration,
831      * or <code>null</code> if the given file can not be found.<p>
832      *
833      * This methods searches the given file in all configured test data paths.
834      * It returns the file found first.<p>
835      *
836      * @param filename the file name to look up
837      * @return the path to a file in the test data configuration
838      */

839     protected static String JavaDoc getTestDataPath(String JavaDoc filename) {
840
841         for (int i = 0; i < m_testDataPath.size(); i++) {
842
843             String JavaDoc path = (String JavaDoc)m_testDataPath.get(i);
844             File file = new File(path + filename);
845             if (file.exists()) {
846                 if (file.isDirectory()) {
847                     return file.getAbsolutePath() + File.separator;
848                 } else {
849                     return file.getAbsolutePath();
850                 }
851             }
852         }
853
854         return null;
855     }
856
857     /**
858      * Imports a resource into the Cms.<p>
859      *
860      * @param cms an initialized CmsObject
861      * @param importFile the name (absolute Path) of the import resource (zip or folder)
862      * @param targetPath the name (absolute Path) of the target folder in the VFS
863      * @throws CmsException if something goes wrong
864      */

865     protected static void importResources(CmsObject cms, String JavaDoc importFile, String JavaDoc targetPath) throws CmsException {
866
867         OpenCms.getImportExportManager().importData(
868             cms,
869             getTestDataPath(File.separator + "imports" + File.separator + importFile),
870             targetPath,
871             new CmsShellReport(cms.getRequestContext().getLocale()));
872     }
873
874     /**
875      * Imports a resource from the RFS test directories to the VFS.<p>
876      *
877      * The imported resource will be automatically unlocked.<p>
878      *
879      * @param cms the current users OpenCms context
880      * @param rfsPath the RTF path of the resource to import, must be a path accessibly by the current class loader
881      * @param vfsPath the VFS path for the imported resource
882      * @param type the type for the imported resource
883      * @param properties the properties for the imported resource
884      * @return the imported resource
885      *
886      * @throws Exception if the import fails
887      */

888     protected static CmsResource importTestResource(
889         CmsObject cms,
890         String JavaDoc rfsPath,
891         String JavaDoc vfsPath,
892         int type,
893         List properties) throws Exception JavaDoc {
894
895         byte[] content = CmsFileUtil.readFile(rfsPath);
896         CmsResource result = cms.createResource(vfsPath, type, content, properties);
897         cms.unlockResource(vfsPath);
898         return result;
899     }
900
901     /**
902      * Removes the OpenCms database test instance.<p>
903      */

904     protected static void removeDatabase() {
905
906         if (m_defaultConnection != null) {
907             removeDatabase(m_setupConnection, m_defaultConnection, false);
908         }
909         if (m_additionalConnection != null) {
910             removeDatabase(m_setupConnection, m_additionalConnection, false);
911         }
912     }
913
914     /**
915      * Removes the OpenCms database test instance.<p>
916      *
917      * @param setupConnection the setup connection
918      * @param defaultConnection the default connection
919      * @param handleErrors flag to indicate if errors should be handled/checked
920      */

921     protected static void removeDatabase(
922         ConnectionData setupConnection,
923         ConnectionData defaultConnection,
924         boolean handleErrors) {
925
926         CmsSetupDb setupDb = null;
927         boolean noErrors = true;
928
929         try {
930             setupDb = getSetupDb(defaultConnection);
931             setupDb.dropTables(m_dbProduct, getReplacer(defaultConnection), handleErrors);
932             noErrors = setupDb.noErrors();
933         } catch (Exception JavaDoc e) {
934             noErrors = false;
935         } finally {
936             if (setupDb != null) {
937                 setupDb.closeConnection();
938             }
939         }
940
941         if (!handleErrors || noErrors) {
942             try {
943                 setupDb = getSetupDb(setupConnection);
944                 setupDb.dropDatabase(m_dbProduct, getReplacer(defaultConnection), handleErrors);
945                 setupDb.closeConnection();
946             } catch (Exception JavaDoc e) {
947                 noErrors = false;
948             } finally {
949                 if (setupDb != null) {
950                     setupDb.closeConnection();
951                 }
952             }
953         }
954
955         if (handleErrors) {
956             checkErrors(setupDb);
957         }
958     }
959
960     /**
961      * Creates a new OpenCms test database including the tables.<p>
962      *
963      * Any existing instance of the test database is forcefully removed first.<p>
964      */

965     protected static void setupDatabase() {
966
967         if (m_defaultConnection != null) {
968             setupDatabase(m_setupConnection, m_defaultConnection, true);
969         }
970         if (m_additionalConnection != null) {
971             setupDatabase(m_setupConnection, m_additionalConnection, true);
972         }
973     }
974
975     /**
976      * Creates a new OpenCms test database including the tables.<p>
977      *
978      * @param setupConnection the setup connection
979      * @param defaultConnection the default connection
980      * @param handleErrors flag to indicate if errors should be handled/checked
981      */

982     protected static void setupDatabase(
983         ConnectionData setupConnection,
984         ConnectionData defaultConnection,
985         boolean handleErrors) {
986
987         CmsSetupDb setupDb = null;
988         boolean noErrors = true;
989
990         try {
991             setupDb = getSetupDb(setupConnection);
992             setupDb.createDatabase(m_dbProduct, getReplacer(defaultConnection), handleErrors);
993             noErrors = setupDb.noErrors();
994             setupDb.closeConnection();
995         } catch (Exception JavaDoc e) {
996             noErrors = false;
997         } finally {
998             if (setupDb != null) {
999                 setupDb.closeConnection();
1000            }
1001        }
1002
1003        if (!handleErrors || noErrors) {
1004            try {
1005                setupDb = getSetupDb(defaultConnection);
1006                setupDb.createTables(m_dbProduct, getReplacer(defaultConnection), handleErrors);
1007                noErrors = setupDb.noErrors();
1008                setupDb.closeConnection();
1009            } catch (Exception JavaDoc e) {
1010                noErrors = false;
1011            } finally {
1012                if (setupDb != null) {
1013                    setupDb.closeConnection();
1014                }
1015            }
1016        }
1017
1018        if (noErrors) {
1019            return;
1020        } else if (handleErrors) {
1021            removeDatabase(setupConnection, defaultConnection, false);
1022            setupDatabase(setupConnection, defaultConnection, false);
1023        } else {
1024            checkErrors(setupDb);
1025        }
1026    }
1027
1028    /**
1029     * Compares two lists of CmsProperty objects and creates a list of all properties which are
1030     * not included in a seperate exclude list.
1031     * @param cms the CmsObject
1032     * @param resourceName the name of the resource the properties belong to
1033     * @param storedResource the stored resource corresponding to the resourcename
1034     * @param excludeList the list of properies to exclude in the test or null
1035     * @return string of non matching properties
1036     * @throws CmsException if something goes wrong
1037     */

1038    private static String JavaDoc compareProperties(
1039        CmsObject cms,
1040        String JavaDoc resourceName,
1041        OpenCmsTestResourceStorageEntry storedResource,
1042        List excludeList) throws CmsException {
1043
1044        String JavaDoc noMatches = "";
1045        List storedProperties = storedResource.getProperties();
1046        List properties = cms.readPropertyObjects(resourceName, false);
1047        List unmatchedProperties;
1048        unmatchedProperties = OpenCmsTestResourceFilter.compareProperties(storedProperties, properties, excludeList);
1049        if (unmatchedProperties.size() > 0) {
1050            noMatches += "[Properies missing " + unmatchedProperties.toString() + "]\n";
1051        }
1052        unmatchedProperties = OpenCmsTestResourceFilter.compareProperties(properties, storedProperties, excludeList);
1053        if (unmatchedProperties.size() > 0) {
1054            noMatches += "[Properies additional " + unmatchedProperties.toString() + "]\n";
1055        }
1056        return noMatches;
1057    }
1058
1059    /**
1060     * Copies the configuration files from the given folder to the "config" folder.
1061     *
1062     * @param newConfig the folder with the configuration files to copy
1063     */

1064    private static void copyConfiguration(String JavaDoc newConfig) {
1065
1066        File configDir = new File(getTestDataPath("WEB-INF" + File.separatorChar + CmsSystemInfo.FOLDER_CONFIG));
1067        File configOriDir = new File(newConfig);
1068
1069        if (configOriDir.exists()) {
1070            File[] oriFiles = configOriDir.listFiles();
1071            boolean initConfigDates = false;
1072            if (m_dateConfigFiles == null) {
1073                m_dateConfigFiles = new long[oriFiles.length];
1074                initConfigDates = true;
1075            }
1076            for (int i = 0; i < oriFiles.length; i++) {
1077                File source = oriFiles[i];
1078                if (source.isFile()) {
1079                    // only copy files
1080
String JavaDoc sourceName = source.getAbsolutePath();
1081                    File target = new File(configDir, source.getName());
1082                    if (initConfigDates) {
1083                        m_dateConfigFiles[i] = target.lastModified();
1084                    }
1085                    String JavaDoc targetName = target.getAbsolutePath();
1086                    try {
1087                        CmsFileUtil.copy(sourceName, targetName);
1088                        target.setLastModified(m_dateConfigFiles[i]);
1089                    } catch (IOException JavaDoc e) {
1090                        e.printStackTrace();
1091                    }
1092                }
1093            }
1094        }
1095
1096    }
1097
1098    /**
1099     * Compares an access control entry of a resource with a given access control entry.<p>
1100     *
1101     * @param cms the CmsObject
1102     * @param resourceName the name of the resource to compare
1103     * @param ace the access control entry to compare or null if to compare with the stored values
1104     */

1105    public void assertAce(CmsObject cms, String JavaDoc resourceName, CmsAccessControlEntry ace) {
1106
1107        try {
1108
1109            // create the exclude list
1110
List excludeList = new ArrayList JavaDoc();
1111            if (ace != null) {
1112                excludeList.add(ace);
1113            }
1114
1115            // get the stored resource
1116
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
1117
1118            String JavaDoc noMatches = compareAccessEntries(cms, resourceName, storedResource, excludeList);
1119
1120            // now see if we have collected any no-matches
1121
if (noMatches.length() > 0) {
1122                fail("error comparing ace of resource " + resourceName + " with stored values: " + noMatches);
1123            }
1124
1125            if (ace != null) {
1126                List resAces = cms.getAccessControlEntries(resourceName);
1127                boolean notFound = true;
1128                Iterator JavaDoc i = resAces.iterator();
1129                while (i.hasNext()) {
1130                    CmsAccessControlEntry resAce = (CmsAccessControlEntry)i.next();
1131                    if (resAce.getPrincipal().equals(ace.getPrincipal())
1132                        && (resAce.getResource().equals(ace.getResource()))) {
1133                        notFound = false;
1134                        if (!resAce.equals(ace)) {
1135                            fail("[ACE " + ace + " != " + resAce + "]");
1136                        }
1137                    }
1138                }
1139                if (notFound) {
1140                    fail("[ACE not found" + ace + "]");
1141                }
1142            }
1143        } catch (Exception JavaDoc e) {
1144            fail("cannot read resource " + resourceName + " " + e.getMessage());
1145        }
1146    }
1147
1148    /**
1149     * Compares an access control list of a resource with a given access control permission.<p>
1150     *
1151     * @param cms the CmsObject
1152     * @param resourceName the name of the resource to compare
1153     * @param principal the principal of the permission set or null if to compare with the stored values
1154     * @param permission the permission set to compare
1155     */

1156    public void assertAcl(CmsObject cms, String JavaDoc resourceName, CmsUUID principal, CmsPermissionSet permission) {
1157
1158        try {
1159
1160            // create the exclude list
1161
List excludeList = new ArrayList JavaDoc();
1162            if (permission != null) {
1163                excludeList.add(principal);
1164            }
1165
1166            // get the stored resource
1167
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
1168
1169            String JavaDoc noMatches = compareAccessLists(cms, resourceName, storedResource, excludeList);
1170
1171            // now see if we have collected any no-matches
1172
if (noMatches.length() > 0) {
1173                fail("error comparing permission sets of resource "
1174                    + resourceName
1175                    + " with stored values: "
1176                    + noMatches);
1177            }
1178
1179            if (permission != null) {
1180                CmsAccessControlList resAcls = cms.getAccessControlList(resourceName);
1181
1182                Map JavaDoc permissionMap = resAcls.getPermissionMap();
1183                CmsPermissionSet resPermission = (CmsPermissionSet)permissionMap.get(principal);
1184                if (resPermission != null) {
1185                    if (!resPermission.equals(permission)) {
1186                        fail("[Permission set not equal " + principal + ":" + permission + " != " + resPermission + "]");
1187                    }
1188                } else {
1189                    fail("[Permission set not found " + principal + ":" + permission + "]");
1190                }
1191            }
1192        } catch (Exception JavaDoc e) {
1193            fail("cannot read resource " + resourceName + " " + e.getMessage());
1194        }
1195    }
1196
1197    /**
1198     * Compares an access control list of a resource with a given access control permission.<p>
1199     *
1200     * @param cms the CmsObject
1201     * @param modifiedResource the name of the which had its permissions changed
1202     * @param resourceName the name of the resource to compare
1203     * @param principal the principal of the permission set or null if to compare with the stored values
1204     * @param permission the permission set to compare
1205     */

1206    public void assertAcl(
1207        CmsObject cms,
1208        String JavaDoc modifiedResource,
1209        String JavaDoc resourceName,
1210        CmsUUID principal,
1211        CmsPermissionSet permission) {
1212
1213        //TODO: This method does not work correctly so far, it must be completed!
1214

1215        try {
1216            // create the exclude list
1217
List excludeList = new ArrayList JavaDoc();
1218            if (permission != null) {
1219                excludeList.add(principal);
1220            }
1221
1222            //TODO: This is the code to recalculate the pemrission set if necessary. Its not completed yet!
1223

1224            Map JavaDoc parents = getParents(cms, resourceName);
1225            List aceList = cms.getAccessControlEntries(resourceName);
1226            Iterator JavaDoc i = aceList.iterator();
1227            while (i.hasNext()) {
1228                CmsAccessControlEntry ace = (CmsAccessControlEntry)i.next();
1229                if (ace.getPrincipal().equals(principal)) {
1230                    String JavaDoc parent = (String JavaDoc)parents.get(ace.getResource());
1231                    if ((!parent.equals(modifiedResource)) && (parent.length() > modifiedResource.length())) {
1232                        permission = new CmsPermissionSet(ace.getAllowedPermissions(), ace.getDeniedPermissions());
1233                    }
1234                }
1235            }
1236            // get the stored resource
1237
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
1238
1239            String JavaDoc noMatches = compareAccessLists(cms, resourceName, storedResource, excludeList);
1240
1241            // now see if we have collected any no-matches
1242
if (noMatches.length() > 0) {
1243                fail("error comparing permission sets of resource "
1244                    + resourceName
1245                    + " with stored values: "
1246                    + noMatches);
1247            }
1248
1249            if (permission != null) {
1250                CmsAccessControlList resAcls = cms.getAccessControlList(resourceName);
1251
1252                Map JavaDoc permissionMap = resAcls.getPermissionMap();
1253                CmsPermissionSet resPermission = (CmsPermissionSet)permissionMap.get(principal);
1254                if (resPermission != null) {
1255                    if (!resPermission.equals(permission)) {
1256                        fail("[Permission set not equal " + principal + ":" + permission + " != " + resPermission + "]");
1257                    }
1258                } else {
1259                    fail("[Permission set not found " + principal + ":" + permission + "]");
1260                }
1261            }
1262        } catch (Exception JavaDoc e) {
1263            fail("cannot read resource " + resourceName + " " + e.getMessage());
1264        }
1265    }
1266
1267    /**
1268     * Tests if a pattern can be found in a content string.<p>
1269     * Fails if the pattern is not found.
1270     *
1271     * @param content the content string
1272     * @param pattern the pattern to search for
1273     */

1274    public void assertContains(String JavaDoc content, String JavaDoc pattern) {
1275
1276        if (content.toLowerCase().indexOf(pattern.toLowerCase()) == -1) {
1277            fail("pattern '" + pattern + "' not found in content");
1278        }
1279    }
1280
1281    /**
1282     * Tests if a pattern cannot be found in a content string.<p>
1283     * Fails if the pattern is found.
1284     *
1285     * @param content the content string
1286     * @param pattern the pattern to search for
1287     */

1288    public void assertContainsNot(String JavaDoc content, String JavaDoc pattern) {
1289
1290        if (content.toLowerCase().indexOf(pattern.toLowerCase()) != -1) {
1291            fail("pattern '" + pattern + "' found in content");
1292        }
1293    }
1294
1295    /**
1296     * Compares the current content of a (file) resource with a given content.<p>
1297     *
1298     * @param cms the CmsObject
1299     * @param resourceName the name of the resource to compare
1300     * @param content the content to compare
1301     */

1302    public void assertContent(CmsObject cms, String JavaDoc resourceName, byte[] content) {
1303
1304        try {
1305            // get the actual resource from the vfs
1306
CmsFile file = cms.readFile(resourceName, CmsResourceFilter.ALL);
1307
1308            byte[] fileContent = file.getContents();
1309            if (fileContent.length != file.getLength()) {
1310                fail("[Content length stored " + file.getContents().length + " != " + file.getLength() + "]");
1311            }
1312            if (fileContent.length != content.length) {
1313                fail("[Content length compared " + file.getContents().length + " != " + content.length + "]");
1314            }
1315            for (int i = 0; i < content.length; i++) {
1316                if (fileContent[i] != content[i]) {
1317                    fail("[Content compare failed at index " + i + "]");
1318                }
1319            }
1320        } catch (CmsException e) {
1321            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1322        }
1323    }
1324
1325    /**
1326     * Compares the current date created of a resource with a given date.<p>
1327     *
1328     * @param cms the CmsObject
1329     * @param resourceName the name of the resource to compare
1330     * @param dateCreated the creation date
1331     */

1332    public void assertDateCreated(CmsObject cms, String JavaDoc resourceName, long dateCreated) {
1333
1334        try {
1335            // get the actual resource from the vfs
1336
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1337
1338            if (res.getDateCreated() != dateCreated) {
1339                fail("[DateCreated "
1340                    + dateCreated
1341                    + " i.e. "
1342                    + CmsDateUtil.getHeaderDate(dateCreated)
1343                    + " != "
1344                    + res.getDateCreated()
1345                    + " i.e. "
1346                    + CmsDateUtil.getHeaderDate(res.getDateCreated())
1347                    + "]");
1348
1349            }
1350
1351        } catch (CmsException e) {
1352            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1353        }
1354    }
1355
1356    /**
1357     * Tests if the the creation date of a resource is later then a given date.<p>
1358     *
1359     * @param cms the CmsObject
1360     * @param resourceName the name of the resource to compare
1361     * @param dateCreated the creation date
1362     */

1363    public void assertDateCreatedAfter(CmsObject cms, String JavaDoc resourceName, long dateCreated) {
1364
1365        try {
1366            // get the actual resource from the vfs
1367
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1368
1369            if (res.getDateCreated() < dateCreated) {
1370                fail("[DateCreated "
1371                    + dateCreated
1372                    + " i.e. "
1373                    + CmsDateUtil.getHeaderDate(dateCreated)
1374                    + " > "
1375                    + res.getDateCreated()
1376                    + " i.e. "
1377                    + CmsDateUtil.getHeaderDate(res.getDateCreated())
1378                    + "]");
1379            }
1380
1381        } catch (CmsException e) {
1382            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1383        }
1384    }
1385
1386    /**
1387     * Compares the current date last modified of a resource with a given date.<p>
1388     *
1389     * @param cms the CmsObject
1390     * @param resourceName the name of the resource to compare
1391     * @param dateLastModified the last modification date
1392     */

1393    public void assertDateLastModified(CmsObject cms, String JavaDoc resourceName, long dateLastModified) {
1394
1395        try {
1396            // get the actual resource from the vfs
1397
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1398
1399            if (res.getDateLastModified() != dateLastModified) {
1400                fail("[DateLastModified "
1401                    + dateLastModified
1402                    + " i.e. "
1403                    + CmsDateUtil.getHeaderDate(dateLastModified)
1404                    + " != "
1405                    + res.getDateLastModified()
1406                    + " i.e. "
1407                    + CmsDateUtil.getHeaderDate(res.getDateLastModified())
1408                    + "]");
1409            }
1410
1411        } catch (CmsException e) {
1412            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1413        }
1414    }
1415
1416    /**
1417     * Tests if the the current date last modified of a resource is later then a given date.<p>
1418     *
1419     * @param cms the CmsObject
1420     * @param resourceName the name of the resource to compare
1421     * @param dateLastModified the last modification date
1422     */

1423    public void assertDateLastModifiedAfter(CmsObject cms, String JavaDoc resourceName, long dateLastModified) {
1424
1425        try {
1426            // get the actual resource from the vfs
1427
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1428
1429            if (res.getDateLastModified() < dateLastModified) {
1430                fail("[DateLastModified "
1431                    + dateLastModified
1432                    + " i.e. "
1433                    + CmsDateUtil.getHeaderDate(dateLastModified)
1434                    + " > "
1435                    + res.getDateLastModified()
1436                    + " i.e. "
1437                    + CmsDateUtil.getHeaderDate(res.getDateLastModified())
1438                    + "]");
1439            }
1440
1441        } catch (CmsException e) {
1442            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1443        }
1444    }
1445
1446    /**
1447     * Tests if the given exceptions are equal (or both null).<p>
1448     *
1449     * @param e1 first exception to compare
1450     * @param e2 second exception to compare
1451     */

1452    public void assertEquals(CmsException e1, CmsException e2) {
1453
1454        if (e1 == null && e2 == null) {
1455            return;
1456        }
1457
1458        if ((e1 == null && e2 != null) || (e1 != null && e2 == null)) {
1459            fail("Exceptions not equal (not both null)");
1460        }
1461
1462        if (!(e1.getClass().equals(e2.getClass()))) {
1463            fail("Exception " + e1.toString() + " does not equal " + e2.toString());
1464        }
1465
1466        if (!(e1.getMessageContainer().getKey().equals(e2.getMessageContainer().getKey()))) {
1467            fail("Exception " + e1.toString() + " does not equal " + e2.toString());
1468        }
1469    }
1470
1471    /**
1472     * Tests if the given xml document objects are equals (or both null).<p>
1473     *
1474     * @param d1 first document to compare
1475     * @param d2 second document to compare
1476     */

1477    public void assertEquals(Document d1, Document d2) {
1478
1479        if (d1 == null && d2 == null) {
1480            return;
1481        }
1482
1483        if ((d1 == null && d2 != null) || (d1 != null && d2 == null)) {
1484            fail("Documents not equal (not both null)");
1485        }
1486
1487        InternalNodeComparator comparator = new InternalNodeComparator();
1488        if (comparator.compare((Node)d1, (Node)d2) != 0) {
1489            fail("Comparison of documents failed: "
1490                + "name = "
1491                + d1.getName()
1492                + ", "
1493                + "path = "
1494                + comparator.m_node1.getUniquePath());
1495        }
1496    }
1497
1498    /**
1499     * Compares a given resource to its stored version containing the state before a CmsObject
1500     * method was called.<p>
1501     *
1502     * @param cms the CmsObject
1503     * @param resource the resource to compare
1504     * @param filter the filter contianing the flags defining which attributes to compare
1505     */

1506    public void assertFilter(CmsObject cms, CmsResource resource, OpenCmsTestResourceFilter filter) {
1507
1508        try {
1509            // get the stored resource
1510
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resource.getRootPath());
1511
1512            // compare the current resource with the stored resource
1513
assertFilter(cms, storedResource, resource, filter);
1514        } catch (Exception JavaDoc e) {
1515            fail("cannot read resource " + resource.getRootPath() + " " + e.getMessage());
1516        }
1517    }
1518
1519    /**
1520     * Compares a stored Cms resource with another Cms resource instance using a specified filter.<p>
1521     *
1522     * @param cms the current user's Cms object
1523     * @param storedResource a stored Cms resource representing the state before an operation
1524     * @param res a Cms resource representing the state after an operation
1525     * @param filter a filter to compare both resources
1526     */

1527    public void assertFilter(
1528        CmsObject cms,
1529        OpenCmsTestResourceStorageEntry storedResource,
1530        CmsResource res,
1531        OpenCmsTestResourceFilter filter) {
1532
1533        String JavaDoc noMatches = null;
1534        String JavaDoc resourceName = null;
1535
1536        try {
1537            noMatches = "";
1538            resourceName = cms.getRequestContext().removeSiteRoot(res.getRootPath());
1539
1540            // compare the contents if necessary
1541
if (filter.testContents()) {
1542                byte[] contents;
1543                // we only have to do this when comparing files
1544
if (res.isFile()) {
1545                    contents = cms.readFile(resourceName, CmsResourceFilter.ALL).getContents();
1546                    if (!new String JavaDoc(storedResource.getContents()).equals(new String JavaDoc(contents))) {
1547                        noMatches += "[Content does not match]\n";
1548                    }
1549                    contents = null;
1550                }
1551            }
1552            // compare the date created if necessary
1553
if (filter.testDateCreated()) {
1554                if (storedResource.getDateCreated() != res.getDateCreated()) {
1555                    noMatches += "[DateCreated "
1556                        + storedResource.getDateCreated()
1557                        + " i.e. "
1558                        + CmsDateUtil.getHeaderDate(storedResource.getDateCreated())
1559                        + " != "
1560                        + res.getDateCreated()
1561                        + " i.e. "
1562                        + CmsDateUtil.getHeaderDate(res.getDateCreated())
1563                        + "]\n";
1564                }
1565            }
1566            // compare the date expired if necessary
1567
if (filter.testDateExpired()) {
1568                if (storedResource.getDateExpired() != res.getDateExpired()) {
1569                    noMatches += "[DateExpired "
1570                        + storedResource.getDateExpired()
1571                        + " i.e. "
1572                        + CmsDateUtil.getHeaderDate(storedResource.getDateExpired())
1573                        + " != "
1574                        + res.getDateExpired()
1575                        + " i.e. "
1576                        + CmsDateUtil.getHeaderDate(res.getDateExpired())
1577                        + "]\n";
1578                }
1579            }
1580            // compare the date last modified if necessary
1581
if (filter.testDateLastModified()) {
1582                if (storedResource.getDateLastModified() != res.getDateLastModified()) {
1583                    noMatches += "[DateLastModified "
1584                        + storedResource.getDateLastModified()
1585                        + " i.e. "
1586                        + CmsDateUtil.getHeaderDate(storedResource.getDateLastModified())
1587                        + " != "
1588                        + res.getDateLastModified()
1589                        + " i.e. "
1590                        + CmsDateUtil.getHeaderDate(res.getDateLastModified())
1591                        + "]\n";
1592                }
1593            }
1594            // compare the date last released if necessary
1595
if (filter.testDateReleased()) {
1596                if (storedResource.getDateReleased() != res.getDateReleased()) {
1597                    noMatches += "[DateReleased "
1598                        + storedResource.getDateReleased()
1599                        + " i.e. "
1600                        + CmsDateUtil.getHeaderDate(storedResource.getDateReleased())
1601                        + " != "
1602                        + res.getDateReleased()
1603                        + " i.e. "
1604                        + CmsDateUtil.getHeaderDate(res.getDateReleased())
1605                        + "]\n";
1606                }
1607            }
1608            // compare the flags if necessary
1609
if (filter.testFlags()) {
1610                if (storedResource.getFlags() != res.getFlags()) {
1611                    noMatches += "[Flags " + storedResource.getFlags() + " != " + res.getFlags() + "]\n";
1612                }
1613            }
1614            // compare the length if necessary
1615
if (filter.testLength()) {
1616                if (storedResource.getLength() != res.getLength()) {
1617                    noMatches += "[Length " + storedResource.getLength() + " != " + res.getLength() + "]\n";
1618                }
1619            }
1620            // compare the sibling count if necessary
1621
if (filter.testSiblingCount()) {
1622                if (storedResource.getSiblingCount() != res.getSiblingCount()) {
1623                    noMatches += "[SiblingCount "
1624                        + storedResource.getSiblingCount()
1625                        + " != "
1626                        + res.getSiblingCount()
1627                        + "]\n";
1628                }
1629            }
1630            // compare the lockstate if necessary
1631
if (filter.testLock()) {
1632                CmsLock resLock = cms.getLock(res);
1633                if (!storedResource.getLock().equals(resLock)) {
1634                    noMatches += "[Lockstate " + storedResource.getLock() + " != " + resLock + "]\n";
1635                }
1636            }
1637            // compare the name if necessary
1638
if (filter.testName()) {
1639                if (!storedResource.getName().equals(res.getName())) {
1640                    noMatches += "[Name " + storedResource.getName() + " != " + res.getName() + "]\n";
1641                }
1642            }
1643            // compare the project last modified if necessary
1644
if (filter.testProjectLastModified()) {
1645                if (storedResource.getProjectLastModified() != res.getProjectLastModified()) {
1646                    noMatches += "[ProjectLastModified "
1647                        + storedResource.getProjectLastModified()
1648                        + " != "
1649                        + res.getProjectLastModified()
1650                        + "]\n";
1651                }
1652            }
1653            // compare the properties if necessary
1654
if (filter.testProperties()) {
1655                noMatches += compareProperties(cms, resourceName, storedResource, null);
1656            }
1657            // compare the acl if necessary
1658
if (filter.testAcl()) {
1659                // compare the ACLs
1660
noMatches += compareAccessLists(cms, resourceName, storedResource, null);
1661            }
1662            // compare the ace if necessary
1663
if (filter.testAce()) {
1664                // compate the ACEs
1665
noMatches += compareAccessEntries(cms, resourceName, storedResource, null);
1666            }
1667            // compare the resource id if necessary
1668
if (filter.testResourceId()) {
1669                if (!storedResource.getResourceId().equals(res.getResourceId())) {
1670                    noMatches += "[ResourceId " + storedResource.getResourceId() + " != " + res.getResourceId() + "]\n";
1671                }
1672            }
1673            // compare the state if necessary
1674
if (filter.testState()) {
1675                if (storedResource.getState() != res.getState()) {
1676                    noMatches += "[State " + storedResource.getState() + " != " + res.getState() + "]\n";
1677                }
1678            }
1679            // compare the structure id if necessary
1680
if (filter.testStructureId()) {
1681                if (!storedResource.getStructureId().equals(res.getStructureId())) {
1682                    noMatches += "[StructureId "
1683                        + storedResource.getStructureId()
1684                        + " != "
1685                        + res.getStructureId()
1686                        + "]\n";
1687                }
1688            }
1689            // compare the touched flag if necessary
1690
if (filter.testTouched()) {
1691                if (storedResource.isTouched() != res.isTouched()) {
1692                    noMatches += "[Touched " + storedResource.isTouched() + " != " + res.isTouched() + "]\n";
1693                }
1694            }
1695            // compare the type if necessary
1696
if (filter.testType()) {
1697                if (storedResource.getType() != res.getTypeId()) {
1698                    noMatches += "[Type " + storedResource.getType() + " != " + res.getTypeId() + "]\n";
1699                }
1700            }
1701            // compare the user created if necessary
1702
if (filter.testUserCreated()) {
1703                if (!storedResource.getUserCreated().equals(res.getUserCreated())) {
1704                    noMatches += createUserFailMessage(
1705                        cms,
1706                        "UserCreated",
1707                        storedResource.getUserLastModified(),
1708                        res.getUserLastModified());
1709                    noMatches += "\n";
1710                }
1711            }
1712            // compare the user created if necessary
1713
if (filter.testUserLastModified()) {
1714                if (!storedResource.getUserLastModified().equals(res.getUserLastModified())) {
1715                    noMatches += createUserFailMessage(
1716                        cms,
1717                        "UserLastModified",
1718                        storedResource.getUserLastModified(),
1719                        res.getUserLastModified());
1720                    noMatches += "\n";
1721                }
1722            }
1723
1724            // now see if we have collected any no-matches
1725
if (noMatches.length() > 0) {
1726                fail("error comparing resource " + resourceName + " with stored values:\n" + noMatches);
1727            }
1728        } catch (CmsException e) {
1729            fail("cannot assert filter " + resourceName + " " + CmsException.getStackTraceAsString(e));
1730        }
1731    }
1732
1733    /**
1734     * Compares a resource to its stored version containing the state before a CmsObject
1735     * method was called.<p>
1736     *
1737     * @param cms the CmsObject
1738     * @param resourceName the name of the resource to compare
1739     * @param filter the filter contianing the flags defining which attributes to compare
1740     */

1741    public void assertFilter(CmsObject cms, String JavaDoc resourceName, OpenCmsTestResourceFilter filter) {
1742
1743        try {
1744            // get the stored resource
1745
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
1746
1747            // get the actual resource from the vfs
1748
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1749
1750            // compare the current resource with the stored resource
1751
assertFilter(cms, storedResource, res, filter);
1752        } catch (Exception JavaDoc e) {
1753            fail("cannot read resource " + resourceName + " " + e.getMessage());
1754        }
1755    }
1756
1757    /**
1758     * Compares a resource to another given resource using a specified filter.<p>
1759     *
1760     * @param cms the current user's Cms object
1761     * @param resourceName1 resource #1
1762     * @param resourceName2 resource #2
1763     * @param filter the filter contianing the flags defining which attributes to compare
1764     */

1765    public void assertFilter(CmsObject cms, String JavaDoc resourceName1, String JavaDoc resourceName2, OpenCmsTestResourceFilter filter) {
1766
1767        try {
1768            CmsResource res1 = cms.readResource(resourceName1, CmsResourceFilter.ALL);
1769            CmsResource res2 = cms.readResource(resourceName2, CmsResourceFilter.ALL);
1770
1771            // a dummy storage entry gets created here to share existing code
1772
OpenCmsTestResourceStorageEntry dummy = new OpenCmsTestResourceStorageEntry(cms, resourceName2, res2);
1773
1774            assertFilter(cms, dummy, res1, filter);
1775        } catch (CmsException e) {
1776            fail("cannot read either resource "
1777                + resourceName1
1778                + " or resource "
1779                + resourceName2
1780                + " "
1781                + CmsException.getStackTraceAsString(e));
1782        }
1783    }
1784
1785    /**
1786     * Tests whether a resource has currently a specified flag set.<p>
1787     *
1788     * @param cms the CmsObject
1789     * @param resourceName the name of the resource to compare
1790     * @param flag a flag to check
1791     */

1792    public void assertFlags(CmsObject cms, String JavaDoc resourceName, int flag) {
1793
1794        try {
1795            // get the actual resource from the vfs
1796
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1797
1798            // test if the specified flag is set
1799
if (!((res.getFlags() & flag) > 0)) {
1800                fail("[Flags (" + res.getFlags() + ") do not contain flag (" + flag + ")");
1801            }
1802        } catch (CmsException e) {
1803            fail("Error reading resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1804        }
1805    }
1806
1807    /**
1808     * Ensures that the given resource is a folder.<p>
1809     *
1810     * @param cms the CmsObject
1811     * @param resourceName the name of the resource to check for a folder
1812     */

1813    public void assertIsFolder(CmsObject cms, String JavaDoc resourceName) {
1814
1815        try {
1816            // get the actual resource from the vfs
1817
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1818
1819            if (!res.isFolder()) {
1820                fail("[Not a folder: " + resourceName + "]");
1821            }
1822            if (res.getLength() != -1) {
1823                fail("[Folder length not -1: " + resourceName + "]");
1824            }
1825        } catch (CmsException e) {
1826            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1827        }
1828    }
1829
1830    /**
1831     * Tests if the specified object is identical with another object.<p>
1832     *
1833     * @param o1 an object
1834     * @param o2 another object
1835     */

1836    public void assertIsIdentical(Object JavaDoc o1, Object JavaDoc o2) {
1837
1838        if (o1 != o2) {
1839            fail("Object " + o1.toString() + " is not identical to " + o2.toString());
1840        }
1841    }
1842
1843    /**
1844     * Tests if the specified object is not identical with another object.<p>
1845     *
1846     * @param o1 an object
1847     * @param o2 another object
1848     */

1849    public void assertIsNotIdentical(Object JavaDoc o1, Object JavaDoc o2) {
1850
1851        if (o1 == o2) {
1852            fail("Object " + o1.toString() + " is identical to " + o2.toString());
1853        }
1854    }
1855
1856    /**
1857     * Validates if a specified resource is somehow locked to the current user.<p>
1858     *
1859     * @param cms the current user's Cms object
1860     * @param resourceName the name of the resource to validate
1861     */

1862    public void assertLock(CmsObject cms, String JavaDoc resourceName) {
1863
1864        try {
1865            // get the actual resource from the VFS
1866
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1867            CmsLock lock = cms.getLock(res);
1868
1869            if (lock.isNullLock() || !lock.getUserId().equals(cms.getRequestContext().currentUser().getId())) {
1870                fail("[Lock "
1871                    + resourceName
1872                    + " requires must be locked to user "
1873                    + cms.getRequestContext().currentUser().getId()
1874                    + "]");
1875            }
1876        } catch (CmsException e) {
1877            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1878        }
1879    }
1880
1881    /**
1882     * Validates if a specified resource has a lock of a given type for the current user.<p>
1883     *
1884     * @param cms the current user's Cms object
1885     * @param resourceName the name of the resource to validate
1886     * @param lockType the type of the lock
1887     * @see CmsLock#TYPE_EXCLUSIVE
1888     * @see CmsLock#TYPE_INHERITED
1889     * @see CmsLock#TYPE_SHARED_EXCLUSIVE
1890     * @see CmsLock#TYPE_SHARED_INHERITED
1891     * @see CmsLock#TYPE_UNLOCKED
1892     */

1893    public void assertLock(CmsObject cms, String JavaDoc resourceName, int lockType) {
1894
1895        try {
1896            // get the actual resource from the VFS
1897
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1898            CmsLock lock = cms.getLock(res);
1899
1900            if (lockType == CmsLock.TYPE_UNLOCKED) {
1901                if (!lock.isNullLock()) {
1902                    fail("[Lock " + resourceName + " must be unlocked]");
1903                }
1904            } else if (lock.isNullLock()
1905                || lock.getType() != lockType
1906                || !lock.getUserId().equals(cms.getRequestContext().currentUser().getId())) {
1907                fail("[Lock "
1908                    + resourceName
1909                    + " requires a lock of type "
1910                    + lockType
1911                    + " for user "
1912                    + cms.getRequestContext().currentUser().getId()
1913                    + " but has a lock of type "
1914                    + lock.getType()
1915                    + " for user "
1916                    + lock.getUserId()
1917                    + "]");
1918            }
1919        } catch (CmsException e) {
1920            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1921        }
1922    }
1923
1924    /**
1925     * Validates the project status of a resource,
1926     * i.e. if a resource has a "red flag" or not.<p>
1927     *
1928     * @param cms the current user's Cms object
1929     * @param resourceName the name of the resource to validate
1930     * @param shouldHaveRedFlag true, if the resource should currently have a red flag
1931     */

1932    public void assertModifiedInCurrentProject(CmsObject cms, String JavaDoc resourceName, boolean shouldHaveRedFlag) {
1933
1934        boolean hasRedFlag = false;
1935
1936        try {
1937            // get the actual resource from the VFS
1938
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1939
1940            // the current resource has a red flag if it's state is changed/new/deleted
1941
hasRedFlag = (res.getState() != CmsResource.STATE_UNCHANGED);
1942            // and if it was modified in the current project
1943
hasRedFlag &= (res.getProjectLastModified() == cms.getRequestContext().currentProject().getId());
1944            // and if it was modified by the current user
1945
hasRedFlag &= (res.getUserLastModified().equals(cms.getRequestContext().currentUser().getId()));
1946
1947            if (shouldHaveRedFlag && !hasRedFlag) {
1948                // it should have a red flag, but it hasn't
1949
fail("[HasRedFlag " + resourceName + " must have a red flag]");
1950            } else if (hasRedFlag && !shouldHaveRedFlag) {
1951                // it has a red flag, but it shouldn't
1952
fail("[HasRedFlag " + resourceName + " must not have a red flag]");
1953            }
1954        } catch (CmsException e) {
1955            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1956        }
1957    }
1958
1959    /**
1960     * Compares the current project of a resource with a given CmsProject.<p>
1961     *
1962     * @param cms the CmsObject
1963     * @param resourceName the name of the resource to compare
1964     * @param project the project
1965     */

1966    public void assertProject(CmsObject cms, String JavaDoc resourceName, CmsProject project) {
1967
1968        try {
1969            // get the actual resource from the vfs
1970
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
1971
1972            if (res.getProjectLastModified() != project.getId()) {
1973                fail("[ProjectLastModified " + project.getId() + " != " + res.getProjectLastModified() + "]");
1974            }
1975
1976        } catch (CmsException e) {
1977            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
1978        }
1979    }
1980
1981    /**
1982     * Compares the current properties of a resource with the stored values and a given, changed property.<p>
1983     *
1984     * @param cms the CmsObject
1985     * @param resourceName the name of the resource to compare
1986     * @param property the changed property
1987     */

1988    public void assertPropertyChanged(CmsObject cms, String JavaDoc resourceName, CmsProperty property) {
1989
1990        try {
1991            // get the stored resource
1992
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
1993
1994            // create the exclude list
1995
List excludeList = new ArrayList JavaDoc();
1996            excludeList.add(property);
1997
1998            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
1999
2000            // now see if we have collected any no-matches
2001
if (noMatches.length() > 0) {
2002                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2003            }
2004
2005            // test if the property was already in the stored result
2006
List storedProperties = storedResource.getProperties();
2007            if (!storedProperties.contains(property)) {
2008                fail("property not found in stored value: " + property);
2009            }
2010
2011            // test if the values of the changed propertiy is correct.
2012
CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2013            if (!resourceProperty.isIdentical(property)) {
2014                fail("property is not identical :" + property + " != " + resourceProperty);
2015            }
2016        } catch (Exception JavaDoc e) {
2017            fail("cannot read resource " + resourceName + " " + e.getMessage());
2018        }
2019    }
2020
2021    /**
2022     * Compares the current properties of a resource with the stored values and a list of changed property.<p>
2023     *
2024     * @param cms an initialized CmsObject
2025     * @param resourceName the name of the resource to compare
2026     * @param excludeList a list of CmsProperties to exclude
2027     */

2028    public void assertPropertyChanged(CmsObject cms, String JavaDoc resourceName, List excludeList) {
2029
2030        try {
2031            // get the stored resource
2032
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2033
2034            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
2035
2036            // now see if we have collected any no-matches
2037
if (noMatches.length() > 0) {
2038                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2039            }
2040
2041            // test if the values of the changed properties are correct and if the properties
2042
// were already in the stored result
2043

2044            String JavaDoc propertyNoMatches = "";
2045            String JavaDoc storedNotFound = "";
2046            Iterator JavaDoc i = excludeList.iterator();
2047            List storedProperties = storedResource.getProperties();
2048            while (i.hasNext()) {
2049                CmsProperty property = (CmsProperty)i.next();
2050                CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2051                // test if the property has the same value
2052
if (!resourceProperty.isIdentical(property)) {
2053                    propertyNoMatches += "[" + property + " != " + resourceProperty + "]";
2054                }
2055                // test if the property was already in the stored object
2056
if (!storedProperties.contains(property)) {
2057                    storedNotFound += "[" + property + "]";
2058                }
2059            }
2060            // now see if we have collected any property no-matches
2061
if (propertyNoMatches.length() > 0) {
2062                fail("error comparing properties for resource " + resourceName + ": " + propertyNoMatches);
2063            }
2064            // now see if we have collected any property not found in the stored original
2065
if (storedNotFound.length() > 0) {
2066                fail("properties not found in stored value: " + storedNotFound);
2067            }
2068        } catch (Exception JavaDoc e) {
2069            fail("cannot read resource " + resourceName + " " + e.getMessage());
2070        }
2071    }
2072
2073    /**
2074     * Tests if a properetydefintion does exist.<p>
2075     *
2076     * @param cms the CmsObject
2077     * @param propertyDefinition the propertsdefinition
2078     */

2079    public void assertPropertydefinitionExist(CmsObject cms, CmsPropertyDefinition propertyDefinition) {
2080
2081        try {
2082            CmsPropertyDefinition prop = cms.readPropertyDefinition(propertyDefinition.getName());
2083            if (prop != null) {
2084                if (!prop.getName().equals(propertyDefinition.getName())) {
2085                    fail("propertsdefinitions do not match: " + prop + " != " + propertyDefinition);
2086                }
2087            } else {
2088                fail("cannot read propertydefitnion" + propertyDefinition);
2089            }
2090        } catch (CmsException e) {
2091            fail("cannot read propertydefitnion" + propertyDefinition + " " + CmsException.getStackTraceAsString(e));
2092        }
2093    }
2094
2095    /**
2096     * Tests the list the propertydefinitions are identical to a given list except one exlclude propertydefintion.<p>
2097     *
2098     * @param cms the CmsObject
2099     * @param propertyDefintions the list of propertydefintions
2100     * @param exclude the exclude propertydefinition
2101     */

2102    public void assertPropertydefinitions(CmsObject cms, List propertyDefintions, CmsPropertyDefinition exclude) {
2103
2104        try {
2105            String JavaDoc noMatches = "";
2106            List allPropertydefintions = cms.readAllPropertyDefinitions();
2107            noMatches += comparePropertydefintions(propertyDefintions, allPropertydefintions, exclude);
2108            noMatches += comparePropertydefintions(allPropertydefintions, propertyDefintions, exclude);
2109            if (noMatches.length() > 0) {
2110                fail("missig propertydefintions: " + noMatches);
2111            }
2112        } catch (CmsException e) {
2113            fail("cannot read propertydefitnions " + CmsException.getStackTraceAsString(e));
2114        }
2115    }
2116
2117    /**
2118     * Compares the current properties of a resource with the stored values.<p>
2119     *
2120     * @param cms the CmsObject
2121     * @param resourceName the name of the resource to compare
2122     */

2123    public void assertPropertyEqual(CmsObject cms, String JavaDoc resourceName) {
2124
2125        try {
2126            // get the stored resource
2127
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2128            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, null);
2129
2130            // now see if we have collected any no-matches
2131
if (noMatches.length() > 0) {
2132                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2133            }
2134
2135        } catch (Exception JavaDoc e) {
2136            fail("cannot read resource " + resourceName + " " + e.getMessage());
2137        }
2138    }
2139
2140    /**
2141     * Compares the current properties of a resource with the stored values and a given, new property.<p>
2142     *
2143     * @param cms the CmsObject
2144     * @param resourceName the name of the resource to compare
2145     * @param property the changed property
2146     */

2147    public void assertPropertyNew(CmsObject cms, String JavaDoc resourceName, CmsProperty property) {
2148
2149        try {
2150            // get the stored resource
2151
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2152
2153            // create the exclude list
2154
List excludeList = new ArrayList JavaDoc();
2155            excludeList.add(property);
2156
2157            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
2158
2159            // now see if we have collected any no-matches
2160
if (noMatches.length() > 0) {
2161                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2162            }
2163
2164            // test if the property was already in the stored result
2165
List storedProperties = storedResource.getProperties();
2166            if (storedProperties.contains(property)) {
2167                fail("property already found in stored value: " + property);
2168            }
2169
2170            // test if the values of the changed propertiy is correct.
2171
CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2172            if (!resourceProperty.isIdentical(property)) {
2173                fail("property is not identical :" + property + " != " + resourceProperty);
2174            }
2175        } catch (Exception JavaDoc e) {
2176            fail("cannot read resource " + resourceName + " " + e.getMessage());
2177        }
2178    }
2179
2180    /**
2181     * Compares the current properties of a resource with the stored values and a list of new property.<p>
2182     *
2183     * @param cms an initialized CmsObject
2184     * @param resourceName the name of the resource to compare
2185     * @param excludeList a list of CmsProperties to exclude
2186     */

2187    public void assertPropertyNew(CmsObject cms, String JavaDoc resourceName, List excludeList) {
2188
2189        try {
2190            // get the stored resource
2191
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2192
2193            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
2194
2195            // now see if we have collected any no-matches
2196
if (noMatches.length() > 0) {
2197                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2198            }
2199
2200            // test if the values of the changed properties are correct and if the properties
2201
// were already in the stored result
2202

2203            String JavaDoc propertyNoMatches = "";
2204            String JavaDoc storedFound = "";
2205            Iterator JavaDoc i = excludeList.iterator();
2206            List storedProperties = storedResource.getProperties();
2207            while (i.hasNext()) {
2208                CmsProperty property = (CmsProperty)i.next();
2209                CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2210                // test if the property has the same value
2211
if (!resourceProperty.isIdentical(property)) {
2212                    propertyNoMatches += "[" + property + " != " + resourceProperty + "]";
2213                }
2214                // test if the property was already in the stored object
2215
if (storedProperties.contains(property)) {
2216                    storedFound += "[" + property + "]";
2217                }
2218            }
2219            // now see if we have collected any property no-matches
2220
if (propertyNoMatches.length() > 0) {
2221                fail("error comparing properties for resource " + resourceName + ": " + propertyNoMatches);
2222            }
2223            // now see if we have collected any property not found in the stored original
2224
if (storedFound.length() > 0) {
2225                fail("properties already found in stored value: " + storedFound);
2226            }
2227        } catch (Exception JavaDoc e) {
2228            fail("cannot read resource " + resourceName + " " + e.getMessage());
2229        }
2230    }
2231
2232    /**
2233     * Compares the current properties of a resource with the stored values and a given, deleted property.<p>
2234     *
2235     * @param cms the CmsObject
2236     * @param resourceName the name of the resource to compare
2237     * @param property the deleted property
2238     */

2239    public void assertPropertyRemoved(CmsObject cms, String JavaDoc resourceName, CmsProperty property) {
2240
2241        try {
2242
2243            // create the exclude list
2244
List excludeList = new ArrayList JavaDoc();
2245            excludeList.add(property);
2246
2247            // get the stored resource
2248
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2249
2250            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
2251
2252            // now see if we have collected any no-matches
2253
if (noMatches.length() > 0) {
2254                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2255            }
2256
2257            // test if the property was already in the stored result
2258
List storedProperties = storedResource.getProperties();
2259            if (!storedProperties.contains(property)) {
2260                fail("property not found in stored value: " + property);
2261            }
2262
2263            // test if the values of the changed propertiy is correct.
2264
CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2265            if (resourceProperty != CmsProperty.getNullProperty()) {
2266                fail("property is not removed :" + property + " != " + resourceProperty);
2267            }
2268        } catch (Exception JavaDoc e) {
2269            fail("cannot read resource " + resourceName + " " + e.getMessage());
2270        }
2271    }
2272
2273    /**
2274     * Compares the current properties of a resource with the stored values and a list of deleted properties.<p>
2275     *
2276     * @param cms an initialized CmsObject
2277     * @param resourceName the name of the resource to compare
2278     * @param excludeList a list of CmsProperties to exclude
2279     */

2280    public void assertPropertyRemoved(CmsObject cms, String JavaDoc resourceName, List excludeList) {
2281
2282        try {
2283            // get the stored resource
2284
OpenCmsTestResourceStorageEntry storedResource = m_currentResourceStrorage.get(resourceName);
2285
2286            String JavaDoc noMatches = compareProperties(cms, resourceName, storedResource, excludeList);
2287
2288            // now see if we have collected any no-matches
2289
if (noMatches.length() > 0) {
2290                fail("error comparing resource " + resourceName + " with stored values: " + noMatches);
2291            }
2292
2293            // test if the values of the changed properties are correct and if the properties
2294
// were already in the stored result
2295

2296            String JavaDoc propertyNotDeleted = "";
2297            String JavaDoc storedNotFound = "";
2298            Iterator JavaDoc i = excludeList.iterator();
2299            List storedProperties = storedResource.getProperties();
2300            List resourceProperties = cms.readPropertyObjects(resourceName, false);
2301
2302            while (i.hasNext()) {
2303                CmsProperty property = (CmsProperty)i.next();
2304                // test if the property has the same value
2305
if (resourceProperties.contains(property)) {
2306                    CmsProperty resourceProperty = cms.readPropertyObject(resourceName, property.getName(), false);
2307                    propertyNotDeleted += "[" + property + " != " + resourceProperty + "]";
2308                }
2309                // test if the property was already in the stored object
2310
if (!storedProperties.contains(property)) {
2311                    storedNotFound += "[" + property + "]";
2312                }
2313            }
2314            // now see if we have collected any property no-matches
2315
if (propertyNotDeleted.length() > 0) {
2316                fail("properties not deleted for " + resourceName + ": " + propertyNotDeleted);
2317            }
2318            // now see if we have collected any property not found in the stored original
2319
if (storedNotFound.length() > 0) {
2320                fail("properties not found in stored value: " + storedNotFound);
2321            }
2322        } catch (Exception JavaDoc e) {
2323            fail("cannot read resource " + resourceName + " " + e.getMessage());
2324        }
2325    }
2326
2327    /**
2328     * Ensures that the given resource is of a certain type.<p>
2329     *
2330     * @param cms the CmsObject
2331     * @param resourceName the name of the resource to check
2332     * @param resourceType the resource type to check for
2333     */

2334    public void assertResourceType(CmsObject cms, String JavaDoc resourceName, int resourceType) {
2335
2336        try {
2337            // get the actual resource from the vfs
2338
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2339
2340            if (res.getTypeId() != resourceType) {
2341                fail("[ResourceType " + res.getTypeId() + " != " + resourceType + "]");
2342            }
2343        } catch (CmsException e) {
2344            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2345        }
2346    }
2347
2348    /**
2349     * Validates if the current sibling count of a resource matches the given number.<p>
2350     *
2351     * @param cms the current user's Cms object
2352     * @param resourceName the name of the resource to compare
2353     * @param count the number of additional siblings
2354     */

2355    public void assertSiblingCount(CmsObject cms, String JavaDoc resourceName, int count) {
2356
2357        try {
2358            // get the current resource from the VFS
2359
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2360            if (res.getSiblingCount() != count) {
2361                fail("[SiblingCount " + res.getSiblingCount() + " != " + count + "]");
2362            }
2363
2364        } catch (CmsException e) {
2365            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2366        }
2367    }
2368
2369    /**
2370     * Validates if the current sibling count of a resource has been incremented
2371     * compared to it's previous sibling count.<p>
2372     *
2373     * @param cms the current user's Cms object
2374     * @param resourceName the name of the resource to compare
2375     * @param increment the number of additional siblings compared to the original state
2376     */

2377    public void assertSiblingCountIncremented(CmsObject cms, String JavaDoc resourceName, int increment) {
2378
2379        try {
2380            // get the current resource from the VFS
2381
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2382
2383            // get the previous resource from resource storage
2384
OpenCmsTestResourceStorageEntry entry = m_currentResourceStrorage.get(resourceName);
2385
2386            if (res.getSiblingCount() != (entry.getSiblingCount() + increment)) {
2387                fail("[SiblingCount "
2388                    + res.getSiblingCount()
2389                    + " != "
2390                    + entry.getSiblingCount()
2391                    + "+"
2392                    + increment
2393                    + "]");
2394            }
2395
2396        } catch (Exception JavaDoc e) {
2397            fail("cannot read resource " + resourceName + " " + e.getMessage());
2398        }
2399    }
2400
2401    /**
2402     * Compares the current state of a resource with a given state.<p>
2403     *
2404     * @param cms the CmsObject
2405     * @param resourceName the name of the resource to compare
2406     * @param state the state
2407     */

2408    public void assertState(CmsObject cms, String JavaDoc resourceName, int state) {
2409
2410        try {
2411            // get the actual resource from the vfs
2412
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2413
2414            if (res.getState() != state) {
2415                fail("[State " + state + " != " + res.getState() + "]");
2416            }
2417
2418        } catch (CmsException e) {
2419            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2420        }
2421    }
2422
2423    /**
2424     * Compares the current type of a resource with a given type.<p>
2425     *
2426     * @param cms the CmsObject
2427     * @param resourceName the name of the resource to compare
2428     * @param type the type
2429     */

2430    public void assertType(CmsObject cms, String JavaDoc resourceName, int type) {
2431
2432        try {
2433            // get the actual resource from the vfs
2434
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2435
2436            if (res.getTypeId() != type) {
2437                fail("[State " + type + " != " + res.getTypeId() + "]");
2438            }
2439
2440        } catch (CmsException e) {
2441            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2442        }
2443    }
2444
2445    /**
2446     * Compares the user who created a resource with a given user.<p>
2447     *
2448     * @param cms the CmsObject
2449     * @param resourceName the name of the resource to compare
2450     * @param user the last modification user
2451     */

2452    public void assertUserCreated(CmsObject cms, String JavaDoc resourceName, CmsUser user) {
2453
2454        try {
2455            // get the actual resource from the vfs
2456
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2457
2458            if (!res.getUserCreated().equals(user.getId())) {
2459                fail(createUserFailMessage(cms, "UserCreated", user.getId(), res.getUserLastModified()));
2460            }
2461
2462        } catch (CmsException e) {
2463            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2464        }
2465    }
2466
2467    /**
2468     * Compares the current user last modified of a resource with a given user.<p>
2469     *
2470     * @param cms the CmsObject
2471     * @param resourceName the name of the resource to compare
2472     * @param user the last modification user
2473     */

2474    public void assertUserLastModified(CmsObject cms, String JavaDoc resourceName, CmsUser user) {
2475
2476        try {
2477            // get the actual resource from the vfs
2478
CmsResource res = cms.readResource(resourceName, CmsResourceFilter.ALL);
2479
2480            if (!res.getUserLastModified().equals(user.getId())) {
2481                fail(createUserFailMessage(cms, "UserLastModified", user.getId(), res.getUserLastModified()));
2482            }
2483
2484        } catch (CmsException e) {
2485            fail("cannot read resource " + resourceName + " " + CmsException.getStackTraceAsString(e));
2486        }
2487    }
2488
2489    /**
2490     * Creates a new storage object.<p>
2491     * @param name the name of the storage
2492     */

2493    public void createStorage(String JavaDoc name) {
2494
2495        OpenCmsTestResourceStorage storage = new OpenCmsTestResourceStorage(name);
2496        m_resourceStorages.put(name, storage);
2497    }
2498
2499    /**
2500     * Returns the name of the database product.<p>
2501     *
2502     * @return returns either oracle or mysql
2503     */

2504    public String JavaDoc getDatabaseProduct() {
2505
2506        return m_dbProduct;
2507    }
2508
2509    /**
2510     * Gets an precalculate resource state from the storage.<p>
2511     *
2512     * @param resourceName the name of the resource to get the state
2513     * @return precalculated resource state
2514     * @throws Exception in case something goes wrong
2515     */

2516    public int getPreCalculatedState(String JavaDoc resourceName) throws Exception JavaDoc {
2517
2518        return m_currentResourceStrorage.getPreCalculatedState(resourceName);
2519    }
2520
2521    /**
2522     * Resets the mapping for resourcenames.<p>
2523     */

2524    public void resetMapping() {
2525
2526        m_currentResourceStrorage.resetMapping();
2527    }
2528
2529    /**
2530     * Sets the mapping for resourcenames.<p>
2531     *
2532     * @param source the source resource name
2533     * @param target the target resource name
2534     */

2535    public void setMapping(String JavaDoc source, String JavaDoc target) {
2536
2537        m_currentResourceStrorage.setMapping(source, target);
2538    }
2539
2540    /**
2541     * Stores the state (e.g. attributes, properties, content, lock state and ACL) of
2542     * a resource in the internal resource storage.<p>
2543     *
2544     * If the resourceName is the name of a folder in the vfs, all subresoruces are stored as well.
2545     *
2546     * @param cms an initialized CmsObject
2547     * @param resourceName the name of the resource in the vfs
2548     */

2549    public void storeResources(CmsObject cms, String JavaDoc resourceName) {
2550
2551        storeResources(cms, resourceName, true);
2552    }
2553
2554    /**
2555     * Stores the state (e.g. attributes, properties, content, lock state and ACL) of
2556     * a resource in the internal resource storage.<p>
2557     *
2558     * If the resourceName is the name of a folder in the vfs and storeSubresources is true,
2559     * all subresoruces are stored as well.
2560     *
2561     * @param cms an initialized CmsObject
2562     * @param resourceName the name of the resource in the vfs
2563     * @param storeSubresources indicates to store subresources of folders
2564     */

2565    public void storeResources(CmsObject cms, String JavaDoc resourceName, boolean storeSubresources) {
2566
2567        String JavaDoc resName = "";
2568
2569        try {
2570            CmsResource resource = cms.readResource(resourceName, CmsResourceFilter.ALL);
2571            // test if the name belongs to a file or folder
2572
if (resource.isFile()) {
2573                m_currentResourceStrorage.add(cms, resourceName, resource);
2574            } else {
2575                // this is a folder, so first add the folder itself to the storeage
2576
m_currentResourceStrorage.add(cms, resourceName
2577                    + (resourceName.charAt(resourceName.length() - 1) != '/' ? "/" : ""), resource);
2578
2579                if (!storeSubresources) {
2580                    return;
2581                }
2582
2583                // now get all subresources and add them as well
2584
List resources = cms.readResources(resourceName, CmsResourceFilter.ALL);
2585                Iterator JavaDoc i = resources.iterator();
2586                while (i.hasNext()) {
2587                    CmsResource res = (CmsResource)i.next();
2588                    resName = cms.getSitePath(res);
2589                    m_currentResourceStrorage.add(cms, resName, res);
2590                }
2591            }
2592        } catch (CmsException e) {
2593            fail("cannot read resource "
2594                + resourceName
2595                + " or "
2596                + resName
2597                + " "
2598                + CmsException.getStackTraceAsString(e));
2599        }
2600    }
2601
2602    /**
2603     * Switches the internal resource storage.<p>
2604     * @param name the name of the storage
2605     * @throws CmsException if the storage was not found
2606     */

2607    public void switchStorage(String JavaDoc name) throws CmsException {
2608
2609        OpenCmsTestResourceStorage storage = (OpenCmsTestResourceStorage)m_resourceStorages.get(name);
2610        if (storage != null) {
2611            m_currentResourceStrorage = storage;
2612        } else {
2613            throw new CmsException(Messages.get().container(Messages.ERR_RESOURCE_STORAGE_NOT_FOUND_0));
2614        }
2615    }
2616
2617    /**
2618     * Writes a message to the current output stream.<p>
2619     *
2620     * @param message the message to write
2621     */

2622    protected void echo(String JavaDoc message) {
2623
2624        try {
2625            System.out.println();
2626            m_shell.printPrompt();
2627            System.out.println(message);
2628        } catch (Throwable JavaDoc t) {
2629            throw new RuntimeException JavaDoc(t);
2630        }
2631    }
2632
2633    /**
2634     * Returns an initialized CmsObject with admin user permissions,
2635     * running in the "/sites/default" site root.<p>
2636     *
2637     * @return an initialized CmsObject with admin user permissions
2638     * @throws CmsException in case of OpenCms access errors
2639     */

2640    protected CmsObject getCmsObject() throws CmsException {
2641
2642        // log in the Admin user and switch to the setup project
2643
CmsObject cms = OpenCms.initCmsObject(OpenCms.getDefaultUsers().getUserGuest());
2644        cms.loginUser("Admin", "admin");
2645        // switch to the "Offline" project
2646
cms.getRequestContext().setCurrentProject(cms.readProject("Offline"));
2647        cms.getRequestContext().setSiteRoot("/sites/default/");
2648
2649        // init the storage
2650
createStorage(OpenCmsTestResourceStorage.DEFAULT_STORAGE);
2651        switchStorage(OpenCmsTestResourceStorage.DEFAULT_STORAGE);
2652
2653        // return the initialized cms context Object
2654
return cms;
2655    }
2656
2657    /**
2658     * Removes and deletes a storage object.<p>
2659     * @param name the name of the storage
2660     */

2661    protected void removeStorage(String JavaDoc name) {
2662
2663        OpenCmsTestResourceStorage storage = (OpenCmsTestResourceStorage)m_resourceStorages.get(name);
2664        if (storage != null) {
2665            m_resourceStorages.remove(name);
2666            storage = null;
2667        }
2668    }
2669
2670    /**
2671     * Restarts the cms.<p>
2672     */

2673    protected void restart() {
2674
2675        OpenCmsTestLogAppender.setBreakOnError(false);
2676
2677        // output a message
2678
System.out.println("\n\n\n----- Restarting shell -----");
2679
2680        m_shell.exit();
2681
2682        m_shell = new CmsShell(getTestDataPath("WEB-INF" + File.separator), null, null, "${user}@${project}>", null);
2683
2684        OpenCmsTestLogAppender.setBreakOnError(true);
2685    }
2686
2687    /**
2688     * Compares two vectors of access entries and creates a list of all access control entries which are
2689     * not matching and are not included in a seperate exclude list.
2690     * @param cms the CmsObject
2691     * @param resourceName the name of the resource the properties belong to
2692     * @param storedResource the stored resource corresponding to the resourcename
2693     * @param excludeList the list of ccess entries to exclude in the test or null
2694     * @return string of non matching access entries
2695     * @throws CmsException if something goes wrong
2696     */

2697    private String JavaDoc compareAccessEntries(
2698        CmsObject cms,
2699        String JavaDoc resourceName,
2700        OpenCmsTestResourceStorageEntry storedResource,
2701        List excludeList) throws CmsException {
2702
2703        String JavaDoc noMatches = "";
2704        List resAce = cms.getAccessControlEntries(resourceName);
2705        List storedAce = storedResource.getAccessControlEntries();
2706        List unmatchedAce;
2707        unmatchedAce = compareAce(resAce, storedAce, excludeList);
2708        if (unmatchedAce.size() > 0) {
2709            noMatches += "[ACE missing " + unmatchedAce.toString() + "]\n";
2710        }
2711        unmatchedAce = compareAce(storedAce, resAce, excludeList);
2712        if (unmatchedAce.size() > 0) {
2713            noMatches += "[ACE missing " + unmatchedAce.toString() + "]\n";
2714        }
2715        return noMatches;
2716    }
2717
2718    /**
2719     * Compares two access lists and creates a list of permission sets which are
2720     * not matching and are not included in a seperate exclude list.
2721     * @param cms the CmsObject
2722     * @param resourceName the name of the resource the properties belong to
2723     * @param storedResource the stored resource corresponding to the resourcename
2724     * @param excludeList the list of permission sets to exclude in the test or null
2725     * @return string of non matching access list entries
2726     * @throws CmsException if something goes wrong
2727     */

2728    private String JavaDoc compareAccessLists(
2729        CmsObject cms,
2730        String JavaDoc resourceName,
2731        OpenCmsTestResourceStorageEntry storedResource,
2732        List excludeList) throws CmsException {
2733
2734        String JavaDoc noMatches = "";
2735        CmsAccessControlList resList = cms.getAccessControlList(resourceName);
2736        CmsAccessControlList storedList = storedResource.getAccessControlList();
2737        List unmatchedList;
2738        unmatchedList = compareList(resList, storedList, excludeList);
2739        if (unmatchedList.size() > 0) {
2740            noMatches += "[ACL differences " + unmatchedList.toString() + "]\n";
2741        }
2742        unmatchedList = compareList(storedList, resList, excludeList);
2743        if (unmatchedList.size() > 0) {
2744            noMatches += "[ACL differences " + unmatchedList.toString() + "]\n";
2745        }
2746        return noMatches;
2747    }
2748
2749    /**
2750     * Compares two vectors of access control entires.<p>
2751     *
2752     * @param source the source vector to compare
2753     * @param target the destination vector to compare
2754     * @param exclude the exclude list
2755     * @return list of non matching access control entires
2756     */

2757    private List compareAce(List source, List target, List exclude) {
2758
2759        List result = new ArrayList JavaDoc();
2760        Iterator JavaDoc i = source.iterator();
2761        while (i.hasNext()) {
2762            CmsAccessControlEntry ace = (CmsAccessControlEntry)i.next();
2763            if (!target.contains(ace)) {
2764                result.add(ace);
2765            }
2766        }
2767        // finally match the result list with the exclude list
2768
if (exclude != null) {
2769            Iterator JavaDoc l = exclude.iterator();
2770            while (l.hasNext()) {
2771                CmsAccessControlEntry excludeAce = (CmsAccessControlEntry)l.next();
2772                if (result.contains(excludeAce)) {
2773                    result.remove(excludeAce);
2774                }
2775            }
2776        }
2777        return result;
2778    }
2779
2780    /**
2781     * Compares two lists of permission sets.<p>
2782     * @param source the source list to compare
2783     * @param target the destination list to compare
2784     * @param exclude the exclude list
2785     * @return list of non matching permission sets
2786     */

2787    private List compareList(CmsAccessControlList source, CmsAccessControlList target, List exclude) {
2788
2789        HashMap JavaDoc result = new HashMap JavaDoc();
2790
2791        HashMap JavaDoc destinationMap = target.getPermissionMap();
2792        HashMap JavaDoc sourceMap = source.getPermissionMap();
2793
2794        Iterator JavaDoc i = sourceMap.keySet().iterator();
2795        while (i.hasNext()) {
2796            CmsUUID key = (CmsUUID)i.next();
2797            CmsPermissionSet value = (CmsPermissionSet)sourceMap.get(key);
2798            if (destinationMap.containsKey(key)) {
2799                CmsPermissionSet destValue = (CmsPermissionSet)destinationMap.get(key);
2800                if (!destValue.equals(value)) {
2801                    result.put(key, key + " " + value + " != " + destValue);
2802                }
2803            } else {
2804                result.put(key, "missing " + key);
2805            }
2806        }
2807
2808        // finally match the result list with the exclude list
2809
if (exclude != null) {
2810            Iterator JavaDoc l = exclude.iterator();
2811            while (l.hasNext()) {
2812                CmsUUID excludeUUID = (CmsUUID)l.next();
2813                if (result.containsKey(excludeUUID)) {
2814                    result.remove(excludeUUID);
2815                }
2816            }
2817        }
2818        return new ArrayList JavaDoc(result.values());
2819    }
2820
2821    /**
2822     * Compares two lists of propertydefintions excluding an exclude propertydefintion.
2823     * @param source the source list of propertydefintions
2824     * @param target the target list of propertydefintions
2825     * @param exclude the exclude propertydefintion
2826     * @return String of missing propertydefinitions
2827     */

2828    private String JavaDoc comparePropertydefintions(List source, List target, CmsPropertyDefinition exclude) {
2829
2830        String JavaDoc noMatches = "";
2831        Iterator JavaDoc i = source.iterator();
2832        while (i.hasNext()) {
2833            CmsPropertyDefinition prop = (CmsPropertyDefinition)i.next();
2834            if ((!target.contains(prop)) && (!prop.getName().equals(exclude.getName()))) {
2835                noMatches += "[" + prop + "]";
2836            }
2837        }
2838        return noMatches;
2839    }
2840
2841    /**
2842     * Creates a user compare fail message.<p>
2843     *
2844     * @param cms the current OpenCms user context
2845     * @param message the message to show
2846     * @param user1 the id of the first (expected) user
2847     * @param user2 the id of the second (found) user
2848     * @return a user compare fail message
2849     *
2850     * @throws CmsException if one of the users can't be read
2851     */

2852    private String JavaDoc createUserFailMessage(CmsObject cms, String JavaDoc message, CmsUUID user1, CmsUUID user2)
2853    throws CmsException {
2854
2855        StringBuffer JavaDoc result = new StringBuffer JavaDoc();
2856        result.append("[");
2857        result.append(message);
2858        result.append(" (");
2859        result.append(cms.readUser(user1).getName());
2860        result.append(") ");
2861        result.append(user1);
2862        result.append(" != (");
2863        result.append(cms.readUser(user2).getName());
2864        result.append(") ");
2865        result.append(user1);
2866        result.append("]");
2867        return result.toString();
2868    }
2869
2870    /**
2871     * Creates a map of all parent resources of a OpenCms resource.<p>
2872     * The resource UUID is used as key, the full resource path is used as the value.
2873     *
2874     * @param cms the CmsObject
2875     * @param resourceName the name of the resource to get the parent map from
2876     * @return HashMap of parent resources
2877     */

2878    private Map JavaDoc getParents(CmsObject cms, String JavaDoc resourceName) {
2879
2880        HashMap JavaDoc parents = new HashMap JavaDoc();
2881        List parentResources = new ArrayList JavaDoc();
2882        try {
2883            // get all parent folders of the current file
2884
parentResources = cms.readPath(resourceName, CmsResourceFilter.IGNORE_EXPIRATION);
2885        } catch (CmsException e) {
2886            // ignore
2887
}
2888        Iterator JavaDoc k = parentResources.iterator();
2889        while (k.hasNext()) {
2890            // add the current folder to the map
2891
CmsResource curRes = (CmsResource)k.next();
2892            parents.put(curRes.getResourceId(), curRes.getRootPath());
2893        }
2894        return parents;
2895    }
2896
2897    /**
2898     * Initializies the OpenCms/database configuration
2899     * by reading the appropriate values from opencms.properties.<p>
2900     */

2901    private void initConfiguration() {
2902
2903        if (m_configuration == null) {
2904            initTestDataPath();
2905            m_configuration = OpenCmsTestProperties.getInstance().getConfiguration();
2906            m_dbProduct = OpenCmsTestProperties.getInstance().getDbProduct();
2907            int index = 0;
2908            boolean cont;
2909            do {
2910                cont = false;
2911                if (m_configuration.containsKey("test.data.path." + index)) {
2912                    addTestDataPath(m_configuration.getString("test.data.path." + index));
2913                    cont = true;
2914                    index++;
2915                }
2916            } while (cont);
2917
2918            try {
2919                String JavaDoc propertyFile = getTestDataPath("WEB-INF/config." + m_dbProduct + "/opencms.properties");
2920                m_configuration = CmsPropertyUtils.loadProperties(propertyFile);
2921            } catch (IOException JavaDoc e) {
2922                fail(e.toString());
2923                return;
2924            }
2925
2926            String JavaDoc key = "setup";
2927            m_setupConnection = new ConnectionData();
2928            m_setupConnection.m_dbName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2929                + "."
2930                + key
2931                + "."
2932                + "dbName");
2933            m_setupConnection.m_jdbcUrl = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2934                + "."
2935                + key
2936                + "."
2937                + "jdbcUrl");
2938            m_setupConnection.m_userName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2939                + "."
2940                + key
2941                + "."
2942                + "user");
2943            m_setupConnection.m_userPassword = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2944                + "."
2945                + key
2946                + "."
2947                + "password");
2948            m_setupConnection.m_jdbcDriver = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2949                + "."
2950                + key
2951                + "."
2952                + CmsDbPool.KEY_JDBC_DRIVER);
2953            m_setupConnection.m_jdbcUrl = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2954                + "."
2955                + key
2956                + "."
2957                + CmsDbPool.KEY_JDBC_URL);
2958            m_setupConnection.m_jdbcUrlParams = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2959                + "."
2960                + key
2961                + "."
2962                + CmsDbPool.KEY_JDBC_URL_PARAMS);
2963
2964            key = "default";
2965            m_defaultConnection = new ConnectionData();
2966            m_defaultConnection.m_dbName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2967                + "."
2968                + key
2969                + "."
2970                + "dbName");
2971            m_defaultConnection.m_userName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2972                + "."
2973                + key
2974                + "."
2975                + CmsDbPool.KEY_USERNAME);
2976            m_defaultConnection.m_userPassword = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2977                + "."
2978                + key
2979                + "."
2980                + CmsDbPool.KEY_PASSWORD);
2981            m_defaultConnection.m_jdbcDriver = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2982                + "."
2983                + key
2984                + "."
2985                + CmsDbPool.KEY_JDBC_DRIVER);
2986            m_defaultConnection.m_jdbcUrl = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2987                + "."
2988                + key
2989                + "."
2990                + CmsDbPool.KEY_JDBC_URL);
2991            m_defaultConnection.m_jdbcUrlParams = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
2992                + "."
2993                + key
2994                + "."
2995                + CmsDbPool.KEY_JDBC_URL_PARAMS);
2996
2997            key = m_additionalConnectionName;
2998            if (m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL + "." + key + "." + "dbName") != null) {
2999                m_additionalConnection = new ConnectionData();
3000                m_additionalConnection.m_dbName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3001                    + "."
3002                    + key
3003                    + "."
3004                    + "dbName");
3005                m_additionalConnection.m_userName = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3006                    + "."
3007                    + key
3008                    + "."
3009                    + CmsDbPool.KEY_USERNAME);
3010                m_additionalConnection.m_userPassword = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3011                    + "."
3012                    + key
3013                    + "."
3014                    + CmsDbPool.KEY_PASSWORD);
3015                m_additionalConnection.m_jdbcDriver = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3016                    + "."
3017                    + key
3018                    + "."
3019                    + CmsDbPool.KEY_JDBC_DRIVER);
3020                m_additionalConnection.m_jdbcUrl = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3021                    + "."
3022                    + key
3023                    + "."
3024                    + CmsDbPool.KEY_JDBC_URL);
3025                m_additionalConnection.m_jdbcUrlParams = m_configuration.getString(CmsDbPool.KEY_DATABASE_POOL
3026                    + "."
3027                    + key
3028                    + "."
3029                    + CmsDbPool.KEY_JDBC_URL_PARAMS);
3030            }
3031
3032            m_defaultTablespace = m_configuration.getString("db.oracle.defaultTablespace");
3033            m_indexTablespace = m_configuration.getString("db.oracle.indexTablespace");
3034            m_tempTablespace = m_configuration.getString("db.oracle.temporaryTablespace");
3035
3036            System.out.println("----- Starting tests on database "
3037                + m_dbProduct
3038                + " ("
3039                + m_setupConnection.m_jdbcUrl
3040                + ") "
3041                + "-----");
3042        }
3043    }
3044
3045}
Popular Tags