KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > DataLoaderTests > LoaderPoolTest


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  * LoaderPoolTest.java
22  *
23  * Tests adding and removing of DataLoaders and some other related stuff.
24  * Should run in fresh instance of IDE.
25  *
26  * Created on May 23, 2001, 1:42 PM
27  */

28
29 package DataLoaderTests.LoaderPoolTest;
30
31 import org.openide.*;
32 import org.openide.loaders.*;
33 import org.openide.filesystems.*;
34 import org.openide.util.Lookup;
35
36 import org.netbeans.core.*;
37
38 import java.io.File JavaDoc;
39 import java.io.FileNotFoundException JavaDoc;
40 import java.io.IOException JavaDoc;
41
42 import java.util.Enumeration JavaDoc;
43 import java.util.jar.JarFile JavaDoc;
44 import java.util.*;
45 import java.util.jar.Attributes JavaDoc;
46 import javax.swing.event.ChangeListener JavaDoc;
47 import javax.swing.event.ChangeEvent JavaDoc;
48
49 import junit.framework.*;
50 import org.netbeans.junit.*;
51
52 public class LoaderPoolTest extends NbTestCase
53                             implements DataLoader.RecognizedFiles
54 {
55     
56     /** Creates new LoaderPoolTest */
57     public LoaderPoolTest(java.lang.String JavaDoc testName) {
58         super(testName);
59     }
60     
61     boolean successful = true;
62     
63     LoaderPoolNode LPN = null;
64     Repository Rep = null;
65     DataLoaderPool DLP = null;
66     DataLoader javadl = null; //JavaDataLoader
67
DataLoader textdl = null; //TXTDataLoader
68
LoaderPoolTest.ChL changel = null; //change listener for changes over DataLoderPool
69
Enumeration JavaDoc en = null;
70     
71     int noOfChanges = 0; //count of changes over DataLoaderPool
72

73     /**This methods write an output to log stream*/
74     public void writeLog(String JavaDoc text) {
75         log(text);
76         System.out.println(text);
77         if (text.equals(FAILED)) successful = false;
78     }
79     
80     /**This methods write an output to reference stream*/
81     public void writeRef(String JavaDoc text) {
82         ref(text);
83         System.out.println(text);
84         if (text.equals(FAILED)) successful = false;
85     }
86     
87     /**This methods write an output to reference stream and asserts success of the test fragment*/
88     public void writeRef(String JavaDoc text, String JavaDoc inf) {
89         ref(text);
90         System.out.println(text);
91         if (inf.equals(FAILED)) successful = false;
92         assertTrue(text,successful);
93     }
94     
95     /**If enabled, prints exception to the output and to the ref stream*/
96     void printException(Exception JavaDoc e) {
97         if(PRINT_EXCEPTIONS){
98             e.printStackTrace();
99             e.printStackTrace(getRef());
100         }
101     }
102     
103
104     /**overrides parent definition of this methot,
105      *so this new works in this way - returns work filed
106      *that should have been set by user of this utility class
107      */

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

117     void prepare() {
118         try{
119             //initializing ide
120
// TopManager.getDefault();
121

122             //when not in XTest harness -> woring directory will be under actual userdir
123
if (Manager.getWorkDirPath()==null) System.setProperty("nbjunit.workdir",System.getProperty("netbeans.user"));
124             //clearWorkDir();
125
noOfChanges = 0;
126             Rep = (Repository) Lookup.getDefault().lookup(Repository.class);
127             
128             //mounting filesystem
129
String JavaDoc str = null;
130             java.net.URL JavaDoc url = new LoaderPoolTest("x").getClass().getResource("LoaderPoolTest.class");
131             if (url.getProtocol().equals("nbfs")) {
132                 //this allows tests to be executed inside running ide (ide mode)
133
// str = (FileUtil.toFile(org.openide.execution.NbfsURLConnection.decodeURL(url))).getAbsolutePath();
134
fail("nbfs is not handled");
135             }
136             else str = url.getPath(); //else test executed in code mode
137
str = str.substring(0,str.indexOf(new LoaderPoolTest("x").getClass().getPackage().getName().replace('.','/')));
138             java.io.File JavaDoc ff = new java.io.File JavaDoc(str);
139             org.openide.filesystems.LocalFileSystem lfs = new org.openide.filesystems.LocalFileSystem();
140             lfs.setRootDirectory(ff);
141             Rep.addFileSystem(lfs);
142             
143             DLP = DataLoaderPool.getDefault ();
144             //following doesn't work in nongui mode ;-(
145
// XXX Places are deprecated at all but the repository node (RepositoryNodeFactory),
146
// The rest is not useful.
147
// LPN = (LoaderPoolNode) ((Places)Lookup.getDefault().lookup(Places.class)).nodes().loaderPool();
148
// changel = new LoaderPoolTest.ChL(this);
149
// DLP.addChangeListener( changel );
150
}catch(Exception JavaDoc e){
151             e.printStackTrace();
152             e.printStackTrace(getRef());
153             assertTrue("Initialization of test failed! ->" + e,false);
154         }
155     }
156     
157     /**
158      *Performs clean up
159      */

160     public void clean() {
161         //getRef().flush();
162
//getRef().close();
163

164         DLP.removeChangeListener( changel );
165         noOfChanges = 0;
166         Rep = null;
167         DLP = null;
168         LPN = null;
169         changel = null;
170     }
171     
172     /**
173      *Performs waiting of current thread for time in millis
174      *@param millist integer number - time in millis to wait
175      */

176     void dummyWait(int millis) {
177         try {
178             Thread.sleep(millis);
179         } catch (Exception JavaDoc ex) {
180             printException(ex);
181         }
182     }
183     
184     /**
185      *Listener for changes over LoaderPool
186      */

187     class ChL implements ChangeListener JavaDoc{
188         LoaderPoolTest parent = null;
189         public ChL(LoaderPoolTest lp){
190             super();
191             parent=lp;
192         }
193         public void stateChanged(ChangeEvent JavaDoc e) {
194             writeRef("\nSome change over DataLoaderPool has happend, added or removed DataLoader!");
195             parent.noOfChanges ++;
196         }
197     }
198     
199     /**
200      *Gets the specified DataLoader
201      *@param DLDisplayNameSubstr substring of the DataLoader's DisplayName
202      *@returns DataLoader or null
203      */

204     public DataLoader getDataLoader(String JavaDoc DLDisplayNameSubstr) {
205         if ( DLDisplayNameSubstr != null ) {
206             en = DLP .allLoaders();
207             while ( en.hasMoreElements() ) {
208                 DataLoader dl = (DataLoader) en.nextElement();
209                 if ( dl.getDisplayName().indexOf(DLDisplayNameSubstr) != -1 ) return dl;
210             }
211         }
212         writeRef("\n" + DLDisplayNameSubstr + " loader not found in the LoaderPool!");
213         return null;
214     }
215     
216     /**
217      *Goes through all registered DataLoaders, firstProducerOf, ProducerOf,
218      *gets and sets PrefferedLoader for java source file
219      */

220     void exploreDataLoaderPool() throws Exception JavaDoc {
221         
222         writeRef("\nListing all registred DataLoaders ...");
223         en = DLP .allLoaders();
224         while ( en.hasMoreElements() ) {
225             DataLoader dl = (DataLoader) en.nextElement();
226             String JavaDoc str = dl.toString();
227             System.out.println( dl.getDisplayName() + " / " + str.substring(0,str.indexOf('@')) );
228             if ( dl.getDisplayName().indexOf("Java Source") != -1 ) javadl = dl;
229             if ( dl.getDisplayName().indexOf("Textual") != -1 ) textdl = dl;
230         }
231         writeRef(PASSED);
232         
233         writeRef("\nGetting firstProducerOf ...");
234         DataLoader[] dla = DLP.toArray();
235         for ( int i = 0 ; i < dla.length ; i ++ ) {
236             String JavaDoc str = (DLP.firstProducerOf(dla[i].getRepresentationClass()) ).toString();
237             System.out.println(str.substring(0,str.indexOf('@')));
238         }
239         writeRef(PASSED);
240         
241         writeRef("\nGetting ProducerOf ...");
242         for ( int i = 0 ; i < dla.length ; i ++ ) {
243             Enumeration JavaDoc e = DLP.producersOf(dla[i].getRepresentationClass());
244             while (e.hasMoreElements()) {
245                 String JavaDoc str = e.nextElement().toString();
246                 System.out.println(str.substring(0,str.indexOf('@')));
247             }
248             System.out.println("*");
249         }
250         writeRef(PASSED);
251         
252         writeRef("\nGetting prefered DataLoader for java source file ...");
253         //some java file
254
String JavaDoc name = "DataLoaderTests/DataObjectTest/data/ClassObject.java";
255         
256         
257         FileObject fo = toFileObject(name);
258         writeRef(fo.toString());
259         if ( DataLoaderPool.getPreferredLoader( fo ) == null ) writeRef("\nnull");
260         else {
261             //writeRef("Check this, should be null.");
262
String JavaDoc str = DataLoaderPool.getPreferredLoader( fo ) .toString();
263             writeRef(str.substring(0,str.indexOf('@')));
264         }
265         writeRef(PASSED);
266         
267         writeRef("\nSetting prefered DataLoader for java source file ...");
268         DataLoaderPool.setPreferredLoader( fo , javadl );
269          writeRef(PASSED);
270         
271         writeRef("\nGetting prefered DataLoader for java source file ...");
272         writeRef(fo.toString());
273         //temp. disabled
274
//String str = DataLoaderPool.getPreferredLoader( fo ) .toString();
275
//writeRef(str.substring(0,str.indexOf('@')));
276
writeRef(PASSED);
277     }
278     
279    static LocalFileSystem lfs ;
280   
281     private static FileObject toFileObject(String JavaDoc fileName ) throws Exception JavaDoc {
282         if (lfs == null ) {
283             lfs = new LocalFileSystem();
284             String JavaDoc xtestData = System.getProperty("xtest.data");
285             if (! xtestData.endsWith(File.separator) ) {
286                 xtestData = xtestData + "/";
287             }
288             lfs.setRootDirectory(new File JavaDoc (xtestData));
289         }
290   /* System.out.println("filename:" + fileName );
291         fileName = xtestData + fileName.replace('/',File.separatorChar);
292         System.out.println("fileName:" + fileName);
293         File file = new File(fileName);
294         if (file.exists() == false ) {
295             throw new FileNotFoundException(fileName);
296         }*/

297         FileObject fo = lfs.findResource(fileName);
298 // FileObject fo = org.openide.filesystems.FileUtil.toFileObject(new File(fileName));
299
if (fo == null) {
300             throw new FileNotFoundException JavaDoc ("fo:" + fileName);
301         }
302         return fo;
303     }
304     /**
305      *@param file is path to the file in the repository
306      *@param dl is DataLoader
307      */

308     void createDataObject(String JavaDoc fileName, DataLoader dl) throws Exception JavaDoc {
309         writeRef("\nCreating DataObject for file " + fileName.substring(fileName.lastIndexOf('/')+1) + " ...");
310         
311         dl.findDataObject (toFileObject(fileName), this );
312     }
313     
314     /**
315      *For specified file tests if there is an exception thrown when creating
316      *DataObject using passed DataLoader (assuming that the DataObject exists
317      *the exception will be DataObjectExistsException).
318      *@param file is path to the file in the repository
319      *@param dl is DataLoader
320      */

321     void notCreateDataObject(String JavaDoc file, DataLoader dl) throws Exception JavaDoc {
322         writeRef("\nnotCreating DataObject for file " + file.substring(file.lastIndexOf('/')+1) + " ...");
323         FileObject fo = toFileObject(file);
324         
325         try {
326            dl.findDataObject (fo, this );
327             writeRef("NotCreating DataObject failed!",FAILED);
328         } catch (Exception JavaDoc ex) {
329             printException(ex);
330             writeRef(PASSED);
331         }
332     }
333     
334     /**
335      *Tests if for specified file exists DataObject
336      *@param file path to the file in the repository
337      *@return true if exists
338      */

339     boolean existDataObject(String JavaDoc fileName) throws Exception JavaDoc {
340         writeRef("\nDataObject for file " + fileName.substring(fileName.lastIndexOf('/')+1) + " should exist ...");
341         FileObject fo = toFileObject(fileName);
342         try {
343             DataObject.find(fo);
344             writeRef(PASSED);
345             return true;
346         } catch (Exception JavaDoc ex) {
347             printException(ex);
348             writeRef("DataObject should exist but doesn't!",FAILED);
349             return false;
350         }
351     }
352     
353     /**
354      *Tests if for specified file does not exist DataObject
355      *@param file path to the file in the repository
356      *@return true if does not exist
357      */

358 /* boolean notExistDataObject(String file){
359         writeRef("\nDataObject for file " + file.substring(file.lastIndexOf('/')+1) + " should not exist ...");
360         FileObject fo = FileUtil.toFileObject(new File(file));
361         try {
362             DataObject.find(fo);
363             writeRef("DataObject shouldn't exit but does!",FAILED);
364             return false;
365         } catch (Exception ex) {
366             printException(ex);
367             writeRef(PASSED);
368             return true;
369         }
370     }*/

371     
372     
373     /**
374      *For passed file finds DataObject and verify if it was created with the desired DataLoader
375      *@param file path to the file in the repository
376      *@param loaderDisplayName DisplayName of desired loader
377      *@return true if the two DisplayNames are identical
378      */

379     boolean recognizedAs(String JavaDoc fileName, String JavaDoc loaderDisplayName) throws IOException JavaDoc {
380         writeRef("\nFile " + fileName.substring(fileName.lastIndexOf('/')+1) + " should be recognized as " + loaderDisplayName + " ...");
381         File JavaDoc file = new File JavaDoc(fileName);
382         if (file.exists() == false) {
383             throw new FileNotFoundException JavaDoc (fileName);
384         }
385         FileObject fo = FileUtil.toFileObject(file);
386         try {
387             boolean status = DataObject.find(fo).getLoader().getDisplayName().indexOf(loaderDisplayName) != -1;
388             //System.out.println(DataObject.find(fo).getLoader().getDisplayName());
389
writeRef(PASSED);
390             return status;
391         } catch (Exception JavaDoc ex) {
392             printException(ex);
393             writeRef("File should be recognized as "+ loaderDisplayName +" but isn't!",FAILED);
394             return false;
395         }
396     }
397     
398     /**
399      *For passed file finds DataObject and verify if it was not created with the desired DataLoader
400      *@param file path to the file in the repository
401      *@param loaderDisplayName DisplayName of desired loader
402      *@return true if the two DisplayNames differ
403      */

404     boolean notRecognizedAs(String JavaDoc file, String JavaDoc loaderName){
405         writeRef("\nFile " + file.substring(file.lastIndexOf('/')+1) + " should not be recognized as " + loaderName + " ...");
406         FileObject fo = FileUtil.toFileObject(new File JavaDoc(file));
407         try {
408             boolean status = DataObject.find(fo).getLoader().getDisplayName().indexOf(loaderName) == -1;
409             //System.out.println(DataObject.find(fo).getLoader().getDisplayName());
410
writeRef(PASSED);
411             return status;
412         } catch (Exception JavaDoc ex) {
413             printException(ex);
414             writeRef("File shouldn't be recognized as "+ loaderName +" but is!",FAILED);
415             return false;
416         }
417     }
418     
419     /**
420      *Removes DataLoader from DataLoaderPool
421      *@param dl DataLoader
422      */

423     void removeDataLoader( DataLoader dl ){
424         writeRef("\nRemoving DataLoader ...");
425         writeRef(dl.getRepresentationClass().toString());
426         LPN.remove( dl );
427         writeRef(PASSED);
428     }
429     
430     /**
431      *Adds DataLoader(s) to DataLoaderPool
432      *@param module name of the module containing loder(s) (name of the jar without extension)
433      */

434     void addDataLoader( String JavaDoc module ){
435         writeRef("\nAdding DataLoaders from LoadersSection from the module manifest ...");
436         try{
437             org.netbeans.ModuleManager mm = org.netbeans.core.NbTopManager.get().getModuleSystem().getManager();
438             org.netbeans.Module m = mm.get(module);
439             
440             System.out.println("Got the Module: " + m.toString());
441             
442             HashSet mysections = new HashSet(25); // Set<ManifestSection>
443
Iterator it = m.getManifest().getEntries().entrySet().iterator(); // Iterator<Map.Entry<String,Attributes>>
444
while (it.hasNext()) {
445                 Map.Entry entry = (Map.Entry)it.next();
446                 org.netbeans.core.startup.ManifestSection section = org.netbeans.core.startup.ManifestSection.create((String JavaDoc)entry.getKey(), (Attributes JavaDoc)entry.getValue(), m);
447                 if (section != null) {
448                     mysections.add(section);
449                 }
450             }
451             
452             System.out.println("Got all sections from manifest: " + mysections.toString());
453             
454             it = mysections.iterator();
455             while (it.hasNext()) {
456                 org.netbeans.core.startup.ManifestSection sect = (org.netbeans.core.startup.ManifestSection)it.next();
457                 if (sect instanceof org.netbeans.core.startup.ManifestSection.LoaderSection) {
458                     System.out.println("Got the LoaderSection: " + ((org.netbeans.core.startup.ManifestSection.LoaderSection)sect).toString() );
459                     LPN.add((org.netbeans.core.startup.ManifestSection.LoaderSection)sect);
460                 }
461             }
462             
463             System.out.println("Loader should be added.");
464             
465             writeRef(PASSED);
466         }catch(Exception JavaDoc ex){
467             printException(ex);
468             writeRef("Adding of DataLoader failed!",FAILED);
469         }
470     }
471     
472     /**
473      *Prints extensions that specified loader will recognize
474      *@param ufl UniFileLoader
475      */

476     void printExtensions(UniFileLoader ufl){
477         if ( ufl != null ) {
478             writeRef("\nGetting registered file extension within this Loader ...");
479             en = ufl .getExtensions() .extensions();
480             while ( en.hasMoreElements() ) writeRef(en.nextElement().toString());
481             writeRef(PASSED);
482         }
483     }
484     
485     /**
486      *Prints extensions that specified loader will recognize
487      *@param ufl UniFileLoader
488      */

489     boolean refPrintExtensions(DataLoader dl){
490         if ( dl != null ) {
491             writeRef("\nGetting registered file extension within this Loader ...");
492             try {
493                 //java.lang.reflect.Method[] ms = dl.getClass().getMethods();
494
//for(int i = 0 ; i < ms.length ; i ++) System.out.println(ms[i]);
495
java.lang.reflect.Method JavaDoc mm = dl.getClass().getMethod("getExtensions", new Class JavaDoc[0]);
496                 Object JavaDoc obj = mm.invoke(dl,new Class JavaDoc[0]);
497                 en = ( (ExtensionList) obj).extensions();
498                 while ( en.hasMoreElements() ) writeRef(en.nextElement().toString());
499                 writeRef(PASSED);
500                 return true;
501             }catch (Exception JavaDoc ex){
502                 printException(ex);
503                 writeRef("Printing extensions failed!",FAILED);
504             }
505         } return false;
506     }
507     
508     /**
509      *Two ways should return the same
510      */

511     void compareTest(){
512         // See above XXX.
513
// writeRef("\nComparing instances of NbLoaderPool ...");
514
// //dlp should be NbLoaderPool
515
// LoaderPoolNode.NbLoaderPool nblp = (LoaderPoolNode.NbLoaderPool) DLP;
516
//// LoaderPoolNode lpn = (LoaderPoolNode) ((Places)Lookup.getDefault().lookup(Places.class)).nodes().loaderPool();
517
// LoaderPoolNode.NbLoaderPool nblp_temp = lpn.getNbLoaderPool();
518
// //nblp and nblp_temp should be the same
519
// if ( ! nblp.equals(nblp_temp) ) writeRef("Got two different instances of DataLoaderPool!",FAILED);
520
// else writeRef(PASSED);
521
}
522     
523     /**
524      *Will consume specified amount of memory.
525      *Method: create String[amount]
526      *@param amount dimension of String array
527      */

528     void eatMemory(int amount){
529         writeRef("\nConsuming memory ...");
530         String JavaDoc arr[] = new String JavaDoc[amount];
531         for (int i = 0 ; i < amount ; i ++) arr[i] = "Something realy stupid here ;-) ...";
532         writeRef(" Done.");
533     }
534     
535     /**
536      *Tries to invoke garbage collection.
537      *Method: 3xgc, sleep 5s, 1xgc, sleep 5s
538      */

539     void sweepMemory(){
540         writeRef("\nSweeping memory ...");
541         for (int i = 0 ; i < 3 ; i ++) System.gc();
542         try {
543             Thread.currentThread().sleep(5000);
544         }catch(Exception JavaDoc ex) {}
545         System.gc();
546         try {
547             Thread.currentThread().sleep(5000);
548         }catch(Exception JavaDoc ex) {}
549         writeRef(" Done.");
550     }
551     
552     
553     
554     /**ONLY FOR TESTING PURPOSES
555      *REAL TESTS ARE IN SEPARATED CLASSES
556      */

557     public static void main(String JavaDoc args[]) {
558         
559         LoaderPoolTest lpt = new LoaderPoolTest("x");
560         
561         try{
562             
563             lpt.prepare();
564             
565             lpt.writeRef(new LoaderPoolTest("x").getClass().getName());
566             
567             //removeDataLoader(getDataLoader("Text"));
568
lpt.addDataLoader("org.netbeans.modules.text");
569             
570             lpt.clean();
571             
572             System.out.println("\n" + lpt.successful );
573             
574         }catch(Throwable JavaDoc ee){
575             ee.printStackTrace(lpt.getRef());
576             ee.printStackTrace();
577             lpt.writeRef(lpt.FAILED);
578         }
579         
580         lpt.assertTrue(lpt.successful);
581         
582     }
583     
584     public void markRecognized(FileObject fo) {
585     }
586     
587     //if you want print exceptions into log file, put here true.
588
public final boolean PRINT_EXCEPTIONS = true;
589     
590     public final String JavaDoc PASSED = "passed.";
591     public final String JavaDoc FAILED = "failed.";
592     //workdir, this hould be set by an user of this class
593
//user of this class shouldn't use their own ref and log
594
public static String JavaDoc work = null;
595 }
596
Popular Tags