KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > DataLoaderTests > DataObjectTest


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 /*
21  * DataObjectTest.java
22  *
23  * Here are implemented separated tests methos, testing manipulating operations with DataObejcts.
24  * Other classes in this packages use them in the logic chain to create meaningfull testcases.
25  *
26  * Created on June 13, 2001, 1:19 PM
27  */

28
29 package DataLoaderTests.DataObjectTest;
30
31 import java.io.FileNotFoundException JavaDoc;
32 import java.io.StringWriter JavaDoc;
33 import org.openide.filesystems.FileObject;
34 import org.openide.filesystems.FileUtil;
35 import org.openide.loaders.DataObject;
36 import org.openide.loaders.DataShadow;
37 import org.openide.loaders.DataFolder;
38 import org.openide.loaders.DataLoader;
39 import org.openide.loaders.DataNode;
40 import org.openide.util.HelpCtx;
41 import org.openide.util.Lookup;
42
43 import java.io.*;
44 import java.util.Enumeration JavaDoc;
45 import java.util.Properties JavaDoc;
46 import junit.framework.*;
47 import org.netbeans.junit.*;
48 import org.openide.loaders.DataObjectNotFoundException;
49
50
51 public class DataObjectTest extends NbTestCase {
52     
53     DataFolder resources = null;
54     /**
55      * teporary data folder
56      */

57     DataFolder temp = null;
58     
59     /** Creates new DataObjectTest */
60     public DataObjectTest(java.lang.String JavaDoc testName) {
61         super(testName);
62     }
63     
64     boolean successful = true;
65     
66     
67     /**This methods write an output to log stream*/
68     public void writeLog(String JavaDoc text) {
69         log(text);
70         System.out.println(text);
71         if (text.equals(FAILED)) successful = false;
72     }
73     
74     /**This methods write an output to reference stream*/
75     public void writeRef(String JavaDoc text) {
76         ref(text);
77         System.out.println(text);
78         if (text.equals(FAILED)) successful = false;
79     }
80     
81     /**This methods write an output to reference stream and asserts success of the test fragment*/
82     public void writeRef(String JavaDoc text, String JavaDoc inf) {
83         ref(text);
84         System.out.println(text);
85         if (inf.equals(FAILED)) successful = false;
86         assertTrue(text,successful);
87     }
88     
89     /**If enabled, prints exception to the output and to the ref stream*/
90     void printException(Exception JavaDoc e) {
91    // if(PRINT_EXCEPTIONS) {
92
e.printStackTrace();
93             e.printStackTrace(getRef());
94      // }
95
}
96     
97     String JavaDoc exceptionToString(Exception JavaDoc e) {
98         StringWriter JavaDoc writer = new StringWriter JavaDoc();
99         PrintWriter pw = new PrintWriter(writer);
100         e.printStackTrace(pw);
101         pw.close();
102         return writer.toString();
103     }
104
105     /**overrides parent definition of this methot,
106      *so this new works in this way - returns work filed
107      *that should have been set by user of this utility class
108      */

109     public String JavaDoc getWorkDirPath() {
110         if (work == null) fail("Working directory not set!");
111         //always return what a someone else has set
112
return work;
113     }
114     
115     /**
116      *Performs initializing before own tests starts
117      */

118     void prepare() throws Exception JavaDoc {
119             //initializing ide
120

121             //when not in XTest harness -> woring directory will be under actual userdir
122
successful = true;
123
124             String JavaDoc xtestData = System.getProperty("xtest.data");
125             File dataDir = new File (xtestData,"DataObjectTest");
126             assertTrue(dataDir.exists());
127             if (dataDir.exists() == false ) {
128                 throw new FileNotFoundException JavaDoc(dataDir.getPath());
129             }
130             FileObject fo = FileUtil.toFileObject(dataDir);
131             assertNotNull(fo);
132             resources = DataFolder.findFolder(fo);
133             System.err.println("resources:" + resources);
134             
135             temp = DataFolder.findFolder(FileUtil.toFileObject(new File (System.getProperty("xtest.tmpdir"))));
136             assertNotNull("No temporary folder found.",temp);
137     }
138     
139     /**
140      *Performs clean up
141      */

142     void clean() {
143         //Put some cleaning stuff here ...
144
}
145     
146     /**
147      *Performs waiting of current thread for time in millis
148      *@param millist integer number - time in millis to wait
149      */

150     void dummyWait(int millis) {
151         try {
152             Thread.sleep(millis);
153         } catch (Exception JavaDoc ex) {
154             printException(ex);
155         }
156     }
157     
158     DataObject getDataObject(FileObject fo) {
159         DataObject dob = null;
160         try{
161             dob = DataObject.find(fo);
162         }catch(Exception JavaDoc ex){
163             printException(ex);
164             writeRef("DataObject.find has failed!",FAILED);
165             return null;
166         }
167         DataLoader loader = dob.getLoader();
168         
169         return getDataObject(fo,loader.getDisplayName());
170     }
171     
172     DataObject getDataObject(FileObject fo, String JavaDoc moduleName) {
173         writeRef("\nGetting DataObject started ...");
174         DataLoader loader = null;
175         try {
176             loader = new DataLoaderTests.LoaderPoolTest.LoaderPoolTest("x").getDataLoader(moduleName);
177         }catch(Exception JavaDoc ex){
178             //simple do nothing
179
}
180         DataObject do1 = null;
181         try{
182             do1 = DataObject.find(fo);
183         }catch(Exception JavaDoc ex){
184             printException(ex);
185             writeRef("DataObject.find has failed",FAILED);
186             return null;
187         }
188         
189         
190         DataLoader loader2 = do1.getLoader();
191         if ((loader!=null) && (loader2!=null)) {
192             if (! loader.equals(loader2)) {
193                 writeRef("DLs do not equals!",FAILED);
194                 return null;
195             } else {
196                 writeRef(PASSED);
197                 return do1;
198             }
199         } else {
200             if (loader2 != null) {writeRef(PASSED);return do1;}
201         }
202         writeRef("Both DLs null!?!",FAILED);
203         return null;
204     }
205     
206     boolean containsFO(DataObject dob, FileObject fob){
207         writeRef("\nDoes files contain FO ...");
208         java.util.Iterator JavaDoc it = dob.files().iterator();
209         while (it.hasNext()) {
210             if (fob.equals(it.next())) {
211                 writeRef(PASSED);
212                 return true;
213             }
214         }
215         writeRef("Files() doesn't contain the FO!",FAILED);
216         return false;
217     }
218     
219     boolean isInFolder(DataObject dob, DataFolder df){
220         writeRef("\nIs this DO in that DF ...");
221         if (dob.getFolder().equals(df)) {
222             writeRef(PASSED);
223             return true;
224         } else{
225             writeRef("This DO isn't in the DF!",FAILED);
226             return false;
227         }
228     }
229     
230     boolean testHelpCtx(DataObject dob){
231         writeRef("\nAsking for HelpCtx ...");
232         HelpCtx hc = dob.getHelpCtx();
233         assertTrue(dob.isValid());
234         System.out.println(dob.getClass());
235          
236         if ( ( (dob instanceof DataFolder) && hc == null ) ||
237              ( (hc.getHelpID()==null)&&(hc.getHelp()!=null) ) ||
238              ( (hc.getHelpID()!=null)&&(hc.getHelp()==null) ) ) {
239             writeRef(PASSED);
240             return true;
241         } else{
242             writeRef("HelpCtx error!",FAILED);
243             return false;
244         }
245     }
246     
247     void getName(DataObject dob){
248         writeRef("\nGetting name ...");
249         writeRef("\n" + dob.getName());
250         writeRef(PASSED);
251     }
252     
253     void testDelegate(DataObject dob){
254         //very simple test this test tests DO not Nodes ;-)
255
writeRef("\nTesting DataObject's node delegate ...");
256         DataNode dn = (DataNode) dob.getNodeDelegate();
257         
258         DataObjectTest.PChL l = new DataObjectTest.PChL();
259         
260         dob.addPropertyChangeListener(l);
261         
262         writeRef("\nDisplayName: " + dn.getDisplayName());
263         writeRef("Name: " + dn.getName());
264         writeRef("ShortDescription: " + dn.getShortDescription());
265         writeRef("ShowFileExtensions: " + dn.getShowFileExtensions());
266         writeRef("Preferred: " + dn.isPreferred());
267         //writeRef("ParentNode name: " + dn.getParentNode().getName());
268
writeRef("Expert: " + dn.isExpert());
269         writeRef("Hidden: " + dn.isHidden());
270         writeRef("Leaf: " + dn.isLeaf());
271         
272         String JavaDoc dsn = dn.getDisplayName();
273         String JavaDoc n = dn.getName();
274         String JavaDoc sd = dn.getShortDescription();
275         boolean sfe = dn.getShowFileExtensions();
276         boolean p = dn.isPreferred();
277         
278         //new settings
279
dn.setDisplayName("Oleee");
280         dn.setName("Hmmm",true);
281         dn.setShortDescription("A short description.");
282         dn.setShowFileExtensions(true);
283         dn.setPreferred(true);
284         
285         writeRef("\nnew DisplayName: " + dn.getDisplayName());
286         writeRef("new Name: " + dn.getName());
287         writeRef("new ShortDescription: " + dn.getShortDescription());
288         writeRef("new ShowFileExtensions: " + dn.getShowFileExtensions());
289         writeRef("new Preferred: " + dn.isPreferred());
290         
291         dummyWait(1000);
292         
293         dob.removePropertyChangeListener(l);
294         
295         //restoring old settings
296
dn.setDisplayName(dsn);
297         dn.setName(n,true);
298         dn.setShortDescription(sd);
299         dn.setShowFileExtensions(sfe);
300         dn.setPreferred(p);
301         
302         writeRef(PASSED);
303     }
304     
305     class PChL implements java.beans.PropertyChangeListener JavaDoc{
306         public void propertyChange(java.beans.PropertyChangeEvent JavaDoc propertyChangeEvent) {
307             writeRef("\nFrom DO's property listener: " + propertyChangeEvent.getPropertyName() +
308             "(" + propertyChangeEvent.getOldValue() + " -> " +
309             propertyChangeEvent.getNewValue() + ")");
310         }
311     }
312     
313     class VChL implements java.beans.VetoableChangeListener JavaDoc{
314         public void vetoableChange(java.beans.PropertyChangeEvent JavaDoc propertyChangeEvent) throws java.beans.PropertyVetoException JavaDoc {
315             if ( DataObject.PROP_VALID.equals(propertyChangeEvent.getPropertyName()) &&
316             (propertyChangeEvent.getNewValue()== Boolean.FALSE) ) {
317                 writeRef("\nGoing to veto this change ...");
318                 throw new java.beans.PropertyVetoException JavaDoc("This change is not allowed ;-)", propertyChangeEvent);
319             } else {
320                 writeRef("\nNot vetoing this change.");
321             }
322         }
323     }
324     
325     boolean inModifiedContainer(DataObject dob){
326         writeRef("\nShould be in modified container ...");
327         java.util.Iterator JavaDoc it = dob.getRegistry().getModifiedSet().iterator();
328         while (it.hasNext()) {
329             if (dob.equals(it.next())) {
330                 writeRef(PASSED);
331                 return true;
332             }
333         }
334         writeRef("This DO isn't in modified container!",FAILED);
335         return false;
336     }
337     
338     boolean notInModifiedContainer(DataObject dob){
339         writeRef("\nShould not be in modified container ...");
340         java.util.Iterator JavaDoc it = dob.getRegistry().getModifiedSet().iterator();
341         while (it.hasNext()) {
342             if (dob.equals(it.next())) {
343                 writeRef("This DO is in modified container!",FAILED);
344                 return false;
345             }
346         }
347         writeRef(PASSED);
348         return true;
349     }
350     
351     class ChL implements javax.swing.event.ChangeListener JavaDoc{
352         public void stateChanged(javax.swing.event.ChangeEvent JavaDoc e) {
353             writeRef("\nSome change over set of modified DOs!");
354             writeRef("Registry: " + e.getSource().toString());
355         }
356     }
357     
358     public boolean checkModifyAbility(DataObject dob) throws Exception JavaDoc {
359         writeRef("\nChecking modify marking facility ...");
360         javax.swing.event.ChangeListener JavaDoc l = new DataObjectTest.ChL();
361         dob.getRegistry().addChangeListener(l);
362         performDelete(dob);
363         dummyWait(1000);
364         if(!dob.isModified()){
365             if(notInModifiedContainer(dob)){
366                 writeRef("\nMarking as modified ...");
367                 dob.setModified(true);
368                 dummyWait(1000);
369                 if(inModifiedContainer(dob)){
370                     writeRef(PASSED);
371                     writeRef("\nMarking as not modified ...");
372                     dob.setModified(false);
373                 } else {
374                     writeRef("Now should be in modified container but isn't!",FAILED);
375                     return false;
376                 }
377             } else {
378                 writeRef("Modified but not in the modified registry!",FAILED);
379                 return false;
380             }
381         } else {
382             writeRef("I have thought that it shouldn't be in modified registry.!",FAILED);
383             return false;
384         }
385         dummyWait(1000);
386         if(!notInModifiedContainer(dob)){
387             writeRef("Shouldn't be in modified registry!!",FAILED);
388             return false;
389         } else writeRef(PASSED);
390         dummyWait(1000);
391         dob.getRegistry().removeChangeListener(l);
392         writeRef(PASSED);
393         return true;
394     }
395     
396     public void checkValidity(DataObject dob) throws Exception JavaDoc {
397         writeRef("\nTesting validity ...");
398         if (!dob.isValid()) {
399             writeRef("DO have to be valid for this test!!",FAILED);
400             return;
401         }
402         DataObject newDO = null;
403         if (dob.isCopyAllowed()) {
404             newDO = dob.copy(temp);
405         } else {
406             writeRef("\nCopy not allowed!");
407             return;
408         }
409         if (!newDO.isValid()) {
410             writeRef("Newly created working DO have to be valid for this test!",FAILED);
411             return;
412         }
413         DataObjectTest.VChL v = new DataObjectTest.VChL();
414         newDO.addVetoableChangeListener(v);
415         writeRef("\nChecking vetoableChangeListener ...");
416         try{
417             newDO.setValid(false);
418             writeRef("This change should have been vetoed!",FAILED);
419         }catch(Exception JavaDoc ex){
420             writeRef(ex.getMessage());
421             writeRef(PASSED);
422         }
423         dummyWait(2000);
424         newDO.removeVetoableChangeListener(v);
425         if (!newDO.isValid()) {
426             writeRef("setValid(false) should have been vetoed, but isn't, now is newDO invalid, cannot continue!",FAILED);
427             return;
428         }
429         if (newDO.isDeleteAllowed()){
430             try{
431                 newDO.delete();
432             }catch(Exception JavaDoc ex){
433                 printException(ex);
434                 writeRef("Deleting of copied object failed!",FAILED);
435                 return;
436             }
437         } else {
438             writeRef("\nDelete not allowed!");
439             return;
440         }
441         if (newDO.isValid()) {
442             writeRef("newDO should not be valid at the end of this test!",FAILED);
443             return;
444         }
445         writeRef(PASSED);
446     }
447     
448     public boolean performCopy(DataObject dob) throws Exception JavaDoc {
449         writeRef("\nNow copying ...");
450         DataObject newDO = null;
451         if (dob.isCopyAllowed()) {
452                 newDO = dob.copy(temp);
453         } else {
454             writeRef("\nCopy not allowed!");
455             return false;
456         }
457         if (! newDO.getName().equals(dob.getName())) {
458             writeRef("Old and new name differ!",FAILED);
459             return false;
460         }
461         if (newDO.isDeleteAllowed()){
462                 newDO.delete();
463         } else {
464             writeRef("\nDelete not allowed!");
465             return false;
466         }
467         writeRef(PASSED);
468         return true;
469     }
470     
471     public boolean performMove(DataObject dob) throws Exception JavaDoc {
472         writeRef("\nNow moving ...");
473         if (dob.isMoveAllowed()) {
474            
475               for (int i = 0 ; i < 10 ; i++) {
476                   try {
477                     dob.move(temp);
478                     break;
479                   } catch (IOException ioe) {
480                       // on windows the file is locked
481
Thread.currentThread().sleep(500);
482                       if (i == 9) {
483                           throw new Exception JavaDoc(ioe);
484                       }
485                   }
486               }
487
488 // }catch(Exception ex){
489
// printException(ex);
490
// writeRef("Moving failed!",FAILED);
491
// return false;
492
// }
493
} else {
494             writeRef("\nMove not allowed!");
495             return false;
496         }
497         if (dob.isMoveAllowed()){
498             try{
499                 dob.move(resources);
500             }catch(Exception JavaDoc ex){
501                 String JavaDoc str = exceptionToString(ex);
502                 writeRef("Moving back failed! + str" ,FAILED);
503                 return false;
504             }
505         } else {
506             writeRef("\nMove not allowed!");
507             return false;
508         }
509         writeRef(PASSED);
510         return true;
511     }
512     
513     public boolean performRename(DataObject dob){
514         writeRef("\nNow renaming ...");
515         final String JavaDoc newName = "NewName";
516         String JavaDoc oldName = dob.getName();
517         if (dob.isRenameAllowed()) {
518             try{
519                 dob.rename(newName);
520             }catch(Exception JavaDoc ex){
521                 printException(ex);
522                 writeRef("Renaming failed!",FAILED);
523                 return false;
524             }
525         } else {
526             writeRef("\nRename not allowed!");
527             return false;
528         }
529         if (! newName.equals(dob.getName())) {
530             writeRef("New name not set!",FAILED);
531             return false;
532         }
533         if (dob.isRenameAllowed()){
534             try{
535                 dob.rename(oldName);
536             }catch(Exception JavaDoc ex){
537                 printException(ex);
538                 writeRef("Renaming back failed!",FAILED);
539                 return false;
540             }
541         } else {
542             writeRef("\nRename not allowed!");
543             return false;
544         }
545         writeRef(PASSED);
546         return true;
547     }
548     
549     public boolean performDelete(DataObject dob) throws Exception JavaDoc {
550         writeRef("\nNow deleting ...");
551         String JavaDoc oldName = dob.getName();
552         DataObject backup = null;
553         if (dob.isCopyAllowed()) {
554             backup = dob.copy(temp);
555         } else {
556             writeRef("\nCopy not allowed!");
557             return false;
558         }
559         if (dob.isDeleteAllowed()) {
560             dob.delete();
561         } else {
562             writeRef("\nDelete not allowed!");
563             return false;
564         }
565         if (backup.isMoveAllowed()) {
566             backup.move(resources);
567         } else {
568             writeRef("\nMove not allowed!");
569             return false;
570         }
571         writeRef(PASSED);
572         return true;
573     }
574     
575     
576     boolean checkManipulationOperations(DataObject dob) throws Exception JavaDoc {
577         writeRef("\nChecking manipulating operations for " + dob.getName() + " ...");
578         return performCopy(dob) && performMove(dob) && performRename(dob) && performDelete(dob);
579     }
580     
581     public boolean checkTemplate(DataObject dob){
582         writeRef("\nNow checking template ...");
583         if(!dob.isTemplate()){
584             try{
585                 dob.setTemplate(true);
586             }catch(Exception JavaDoc ex){
587                 printException(ex);
588                 writeRef("Setting template failed!",FAILED);
589                 return false;
590             }
591             if(!dob.isTemplate()) {
592                 writeRef("DO should be template but isn't!",FAILED);
593                 return false;
594             }
595             try{
596                 dob.setTemplate(false);
597             }catch(Exception JavaDoc ex){
598                 printException(ex);
599                 writeRef("Unsetting template failed!",FAILED);
600                 return false;
601             }
602         } else writeRef("\nIs a template.");
603         writeRef(PASSED);
604         return true;
605     }
606     
607     public DataShadow shadowMe(DataObject dob) throws Exception JavaDoc{
608         return shadowMe(dob,null);
609     }
610     
611     public DataShadow shadowMe(DataObject dob, String JavaDoc name) throws Exception JavaDoc {
612         writeRef("\nCreating shadow from " + dob.getName() + " ...");
613         if(dob.isShadowAllowed()){
614 // try{
615
DataShadow ds = null;
616                 ds = DataShadow.create(temp, name, dob);
617                 writeRef(PASSED);
618                 return ds;
619 // }catch(Exception ex){
620
// printException(ex);
621
// writeRef("Creating of shadow failed!",FAILED);
622
// return null;
623
// }
624
} else {
625             writeRef("\nThis DO cannot be shadowed!");
626             writeRef(PASSED);
627             return null;
628         }
629     }
630     
631     
632      public static void showFilesRecursively(File f, PrintStream ps) {
633          ps.println(f);
634          if (f.isDirectory()) {
635              File files [] = f.listFiles();
636              for (int i = 0 ; i < files.length ; i++) {
637                 showFilesRecursively(files[i],ps);
638              }
639          }
640      }
641      public static DataObject findResource(String JavaDoc name) throws Exception JavaDoc {
642         String JavaDoc xtestData = System.getProperty("xtest.data");
643         if (! xtestData.endsWith(File.separator) ) {
644             xtestData = xtestData + "/";
645         }
646         String JavaDoc fileName = xtestData + name.substring(1).replace('/',File.separatorChar);
647         System.out.println("fileName:" + fileName);
648         if (new File(fileName).exists() == false ) {
649             throw new FileNotFoundException JavaDoc(fileName);
650         }
651         FileObject fo = org.openide.filesystems.FileUtil.toFileObject(new File(fileName));
652         if (fo == null) {
653             throw new NullPointerException JavaDoc("No resource found for " + fileName);
654         }
655         try {
656             return DataObject.find(fo);
657         } catch (Exception JavaDoc e) {
658             e.printStackTrace();
659             throw new NullPointerException JavaDoc("No resource found for " + fileName);
660         }
661     }
662      
663     /**ONLY FOR TESTING PURPOSES
664      *REAL TESTS ARE IN SEPARATED CLASSES
665      */

666   
667     //if you want print exceptions into log file, put here true.
668
public final boolean PRINT_EXCEPTIONS = true;
669     
670     public final String JavaDoc PASSED = "passed.\n";
671     public final String JavaDoc FAILED = "failed.\n";
672     //workdir, this hould be set by an user of this class
673
//user of this class shouldn't use their own ref and log
674
public static String JavaDoc work = null;
675 }
676
Popular Tags