001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041:
042: /*
043: * LoaderPoolTest.java
044: *
045: * Tests adding and removing of DataLoaders and some other related stuff.
046: * Should run in fresh instance of IDE.
047: *
048: * Created on May 23, 2001, 1:42 PM
049: */
050:
051: package DataLoaderTests.LoaderPoolTest;
052:
053: import org.openide.*;
054: import org.openide.loaders.*;
055: import org.openide.filesystems.*;
056: import org.openide.util.Lookup;
057:
058: import org.netbeans.core.*;
059:
060: import java.io.File;
061: import java.io.FileNotFoundException;
062: import java.io.IOException;
063:
064: import java.util.Enumeration;
065: import java.util.jar.JarFile;
066: import java.util.*;
067: import java.util.jar.Attributes;
068: import javax.swing.event.ChangeListener;
069: import javax.swing.event.ChangeEvent;
070:
071: import junit.framework.*;
072: import org.netbeans.junit.*;
073:
074: public class LoaderPoolTest extends NbTestCase implements
075: DataLoader.RecognizedFiles {
076:
077: /** Creates new LoaderPoolTest */
078: public LoaderPoolTest(java.lang.String testName) {
079: super (testName);
080: }
081:
082: boolean successful = true;
083:
084: LoaderPoolNode LPN = null;
085: Repository Rep = null;
086: DataLoaderPool DLP = null;
087: DataLoader javadl = null; //JavaDataLoader
088: DataLoader textdl = null; //TXTDataLoader
089: LoaderPoolTest.ChL changel = null; //change listener for changes over DataLoderPool
090: Enumeration en = null;
091:
092: int noOfChanges = 0; //count of changes over DataLoaderPool
093:
094: /**This methods write an output to log stream*/
095: public void writeLog(String text) {
096: log(text);
097: System.out.println(text);
098: if (text.equals(FAILED))
099: successful = false;
100: }
101:
102: /**This methods write an output to reference stream*/
103: public void writeRef(String text) {
104: ref(text);
105: System.out.println(text);
106: if (text.equals(FAILED))
107: successful = false;
108: }
109:
110: /**This methods write an output to reference stream and asserts success of the test fragment*/
111: public void writeRef(String text, String inf) {
112: ref(text);
113: System.out.println(text);
114: if (inf.equals(FAILED))
115: successful = false;
116: assertTrue(text, successful);
117: }
118:
119: /**If enabled, prints exception to the output and to the ref stream*/
120: void printException(Exception e) {
121: if (PRINT_EXCEPTIONS) {
122: e.printStackTrace();
123: e.printStackTrace(getRef());
124: }
125: }
126:
127: /**overrides parent definition of this methot,
128: *so this new works in this way - returns work filed
129: *that should have been set by user of this utility class
130: */
131: public String getWorkDirPath() {
132: if (work == null)
133: fail("Working directory not set!");
134: //always return what a someone else has set
135: return work;
136: }
137:
138: /**
139: *Performs initializing before own tests starts
140: */
141: void prepare() {
142: try {
143: //initializing ide
144: // TopManager.getDefault();
145:
146: //when not in XTest harness -> woring directory will be under actual userdir
147: if (Manager.getWorkDirPath() == null)
148: System.setProperty("nbjunit.workdir", System
149: .getProperty("netbeans.user"));
150: //clearWorkDir();
151: noOfChanges = 0;
152: Rep = (Repository) Lookup.getDefault().lookup(
153: Repository.class);
154:
155: //mounting filesystem
156: String str = null;
157: java.net.URL url = new LoaderPoolTest("x").getClass()
158: .getResource("LoaderPoolTest.class");
159: if (url.getProtocol().equals("nbfs")) {
160: //this allows tests to be executed inside running ide (ide mode)
161: // str = (FileUtil.toFile(org.openide.execution.NbfsURLConnection.decodeURL(url))).getAbsolutePath();
162: fail("nbfs is not handled");
163: } else
164: str = url.getPath(); //else test executed in code mode
165: str = str.substring(0, str.indexOf(new LoaderPoolTest("x")
166: .getClass().getPackage().getName()
167: .replace('.', '/')));
168: java.io.File ff = new java.io.File(str);
169: org.openide.filesystems.LocalFileSystem lfs = new org.openide.filesystems.LocalFileSystem();
170: lfs.setRootDirectory(ff);
171: Rep.addFileSystem(lfs);
172:
173: DLP = DataLoaderPool.getDefault();
174: //following doesn't work in nongui mode ;-(
175: // XXX Places are deprecated at all but the repository node (RepositoryNodeFactory),
176: // The rest is not useful.
177: // LPN = (LoaderPoolNode) ((Places)Lookup.getDefault().lookup(Places.class)).nodes().loaderPool();
178: // changel = new LoaderPoolTest.ChL(this);
179: // DLP.addChangeListener( changel );
180: } catch (Exception e) {
181: e.printStackTrace();
182: e.printStackTrace(getRef());
183: assertTrue("Initialization of test failed! ->" + e, false);
184: }
185: }
186:
187: /**
188: *Performs clean up
189: */
190: public void clean() {
191: //getRef().flush();
192: //getRef().close();
193:
194: DLP.removeChangeListener(changel);
195: noOfChanges = 0;
196: Rep = null;
197: DLP = null;
198: LPN = null;
199: changel = null;
200: }
201:
202: /**
203: *Performs waiting of current thread for time in millis
204: *@param millist integer number - time in millis to wait
205: */
206: void dummyWait(int millis) {
207: try {
208: Thread.sleep(millis);
209: } catch (Exception ex) {
210: printException(ex);
211: }
212: }
213:
214: /**
215: *Listener for changes over LoaderPool
216: */
217: class ChL implements ChangeListener {
218: LoaderPoolTest parent = null;
219:
220: public ChL(LoaderPoolTest lp) {
221: super ();
222: parent = lp;
223: }
224:
225: public void stateChanged(ChangeEvent e) {
226: writeRef("\nSome change over DataLoaderPool has happend, added or removed DataLoader!");
227: parent.noOfChanges++;
228: }
229: }
230:
231: /**
232: *Gets the specified DataLoader
233: *@param DLDisplayNameSubstr substring of the DataLoader's DisplayName
234: *@returns DataLoader or null
235: */
236: public DataLoader getDataLoader(String DLDisplayNameSubstr) {
237: if (DLDisplayNameSubstr != null) {
238: en = DLP.allLoaders();
239: while (en.hasMoreElements()) {
240: DataLoader dl = (DataLoader) en.nextElement();
241: if (dl.getDisplayName().indexOf(DLDisplayNameSubstr) != -1)
242: return dl;
243: }
244: }
245: writeRef("\n" + DLDisplayNameSubstr
246: + " loader not found in the LoaderPool!");
247: return null;
248: }
249:
250: /**
251: *Goes through all registered DataLoaders, firstProducerOf, ProducerOf,
252: *gets and sets PrefferedLoader for java source file
253: */
254: void exploreDataLoaderPool() throws Exception {
255:
256: writeRef("\nListing all registred DataLoaders ...");
257: en = DLP.allLoaders();
258: while (en.hasMoreElements()) {
259: DataLoader dl = (DataLoader) en.nextElement();
260: String str = dl.toString();
261: System.out.println(dl.getDisplayName() + " / "
262: + str.substring(0, str.indexOf('@')));
263: if (dl.getDisplayName().indexOf("Java Source") != -1)
264: javadl = dl;
265: if (dl.getDisplayName().indexOf("Textual") != -1)
266: textdl = dl;
267: }
268: writeRef(PASSED);
269:
270: writeRef("\nGetting firstProducerOf ...");
271: DataLoader[] dla = DLP.toArray();
272: for (int i = 0; i < dla.length; i++) {
273: String str = (DLP.firstProducerOf(dla[i]
274: .getRepresentationClass())).toString();
275: System.out.println(str.substring(0, str.indexOf('@')));
276: }
277: writeRef(PASSED);
278:
279: writeRef("\nGetting ProducerOf ...");
280: for (int i = 0; i < dla.length; i++) {
281: Enumeration e = DLP.producersOf(dla[i]
282: .getRepresentationClass());
283: while (e.hasMoreElements()) {
284: String str = e.nextElement().toString();
285: System.out.println(str.substring(0, str.indexOf('@')));
286: }
287: System.out.println("*");
288: }
289: writeRef(PASSED);
290:
291: writeRef("\nGetting prefered DataLoader for java source file ...");
292: //some java file
293: String name = "DataLoaderTests/DataObjectTest/data/ClassObject.java";
294:
295: FileObject fo = toFileObject(name);
296: writeRef(fo.toString());
297: if (DataLoaderPool.getPreferredLoader(fo) == null)
298: writeRef("\nnull");
299: else {
300: //writeRef("Check this, should be null.");
301: String str = DataLoaderPool.getPreferredLoader(fo)
302: .toString();
303: writeRef(str.substring(0, str.indexOf('@')));
304: }
305: writeRef(PASSED);
306:
307: writeRef("\nSetting prefered DataLoader for java source file ...");
308: DataLoaderPool.setPreferredLoader(fo, javadl);
309: writeRef(PASSED);
310:
311: writeRef("\nGetting prefered DataLoader for java source file ...");
312: writeRef(fo.toString());
313: //temp. disabled
314: //String str = DataLoaderPool.getPreferredLoader( fo ) .toString();
315: //writeRef(str.substring(0,str.indexOf('@')));
316: writeRef(PASSED);
317: }
318:
319: static LocalFileSystem lfs;
320:
321: private static FileObject toFileObject(String fileName)
322: throws Exception {
323: if (lfs == null) {
324: lfs = new LocalFileSystem();
325: String xtestData = System.getProperty("xtest.data");
326: if (!xtestData.endsWith(File.separator)) {
327: xtestData = xtestData + "/";
328: }
329: lfs.setRootDirectory(new File(xtestData));
330: }
331: /* System.out.println("filename:" + fileName );
332: fileName = xtestData + fileName.replace('/',File.separatorChar);
333: System.out.println("fileName:" + fileName);
334: File file = new File(fileName);
335: if (file.exists() == false ) {
336: throw new FileNotFoundException(fileName);
337: }*/
338: FileObject fo = lfs.findResource(fileName);
339: // FileObject fo = org.openide.filesystems.FileUtil.toFileObject(new File(fileName));
340: if (fo == null) {
341: throw new FileNotFoundException("fo:" + fileName);
342: }
343: return fo;
344: }
345:
346: /**
347: *@param file is path to the file in the repository
348: *@param dl is DataLoader
349: */
350: void createDataObject(String fileName, DataLoader dl)
351: throws Exception {
352: writeRef("\nCreating DataObject for file "
353: + fileName.substring(fileName.lastIndexOf('/') + 1)
354: + " ...");
355:
356: dl.findDataObject(toFileObject(fileName), this );
357: }
358:
359: /**
360: *For specified file tests if there is an exception thrown when creating
361: *DataObject using passed DataLoader (assuming that the DataObject exists
362: *the exception will be DataObjectExistsException).
363: *@param file is path to the file in the repository
364: *@param dl is DataLoader
365: */
366: void notCreateDataObject(String file, DataLoader dl)
367: throws Exception {
368: writeRef("\nnotCreating DataObject for file "
369: + file.substring(file.lastIndexOf('/') + 1) + " ...");
370: FileObject fo = toFileObject(file);
371:
372: try {
373: dl.findDataObject(fo, this );
374: writeRef("NotCreating DataObject failed!", FAILED);
375: } catch (Exception ex) {
376: printException(ex);
377: writeRef(PASSED);
378: }
379: }
380:
381: /**
382: *Tests if for specified file exists DataObject
383: *@param file path to the file in the repository
384: *@return true if exists
385: */
386: boolean existDataObject(String fileName) throws Exception {
387: writeRef("\nDataObject for file "
388: + fileName.substring(fileName.lastIndexOf('/') + 1)
389: + " should exist ...");
390: FileObject fo = toFileObject(fileName);
391: try {
392: DataObject.find(fo);
393: writeRef(PASSED);
394: return true;
395: } catch (Exception ex) {
396: printException(ex);
397: writeRef("DataObject should exist but doesn't!", FAILED);
398: return false;
399: }
400: }
401:
402: /**
403: *Tests if for specified file does not exist DataObject
404: *@param file path to the file in the repository
405: *@return true if does not exist
406: */
407: /* boolean notExistDataObject(String file){
408: writeRef("\nDataObject for file " + file.substring(file.lastIndexOf('/')+1) + " should not exist ...");
409: FileObject fo = FileUtil.toFileObject(new File(file));
410: try {
411: DataObject.find(fo);
412: writeRef("DataObject shouldn't exit but does!",FAILED);
413: return false;
414: } catch (Exception ex) {
415: printException(ex);
416: writeRef(PASSED);
417: return true;
418: }
419: }*/
420:
421: /**
422: *For passed file finds DataObject and verify if it was created with the desired DataLoader
423: *@param file path to the file in the repository
424: *@param loaderDisplayName DisplayName of desired loader
425: *@return true if the two DisplayNames are identical
426: */
427: boolean recognizedAs(String fileName, String loaderDisplayName)
428: throws IOException {
429: writeRef("\nFile "
430: + fileName.substring(fileName.lastIndexOf('/') + 1)
431: + " should be recognized as " + loaderDisplayName
432: + " ...");
433: File file = new File(fileName);
434: if (file.exists() == false) {
435: throw new FileNotFoundException(fileName);
436: }
437: FileObject fo = FileUtil.toFileObject(file);
438: try {
439: boolean status = DataObject.find(fo).getLoader()
440: .getDisplayName().indexOf(loaderDisplayName) != -1;
441: //System.out.println(DataObject.find(fo).getLoader().getDisplayName());
442: writeRef(PASSED);
443: return status;
444: } catch (Exception ex) {
445: printException(ex);
446: writeRef("File should be recognized as "
447: + loaderDisplayName + " but isn't!", FAILED);
448: return false;
449: }
450: }
451:
452: /**
453: *For passed file finds DataObject and verify if it was not created with the desired DataLoader
454: *@param file path to the file in the repository
455: *@param loaderDisplayName DisplayName of desired loader
456: *@return true if the two DisplayNames differ
457: */
458: boolean notRecognizedAs(String file, String loaderName) {
459: writeRef("\nFile " + file.substring(file.lastIndexOf('/') + 1)
460: + " should not be recognized as " + loaderName + " ...");
461: FileObject fo = FileUtil.toFileObject(new File(file));
462: try {
463: boolean status = DataObject.find(fo).getLoader()
464: .getDisplayName().indexOf(loaderName) == -1;
465: //System.out.println(DataObject.find(fo).getLoader().getDisplayName());
466: writeRef(PASSED);
467: return status;
468: } catch (Exception ex) {
469: printException(ex);
470: writeRef("File shouldn't be recognized as " + loaderName
471: + " but is!", FAILED);
472: return false;
473: }
474: }
475:
476: /**
477: *Removes DataLoader from DataLoaderPool
478: *@param dl DataLoader
479: */
480: void removeDataLoader(DataLoader dl) {
481: writeRef("\nRemoving DataLoader ...");
482: writeRef(dl.getRepresentationClass().toString());
483: LPN.remove(dl);
484: writeRef(PASSED);
485: }
486:
487: /**
488: *Adds DataLoader(s) to DataLoaderPool
489: *@param module name of the module containing loder(s) (name of the jar without extension)
490: */
491: void addDataLoader(String module) {
492: writeRef("\nAdding DataLoaders from LoadersSection from the module manifest ...");
493: try {
494: org.netbeans.ModuleManager mm = org.netbeans.core.NbTopManager
495: .get().getModuleSystem().getManager();
496: org.netbeans.Module m = mm.get(module);
497:
498: System.out.println("Got the Module: " + m.toString());
499:
500: HashSet mysections = new HashSet(25); // Set<ManifestSection>
501: Iterator it = m.getManifest().getEntries().entrySet()
502: .iterator(); // Iterator<Map.Entry<String,Attributes>>
503: while (it.hasNext()) {
504: Map.Entry entry = (Map.Entry) it.next();
505: org.netbeans.core.startup.ManifestSection section = org.netbeans.core.startup.ManifestSection
506: .create((String) entry.getKey(),
507: (Attributes) entry.getValue(), m);
508: if (section != null) {
509: mysections.add(section);
510: }
511: }
512:
513: System.out.println("Got all sections from manifest: "
514: + mysections.toString());
515:
516: it = mysections.iterator();
517: while (it.hasNext()) {
518: org.netbeans.core.startup.ManifestSection sect = (org.netbeans.core.startup.ManifestSection) it
519: .next();
520: if (sect instanceof org.netbeans.core.startup.ManifestSection.LoaderSection) {
521: System.out
522: .println("Got the LoaderSection: "
523: + ((org.netbeans.core.startup.ManifestSection.LoaderSection) sect)
524: .toString());
525: LPN
526: .add((org.netbeans.core.startup.ManifestSection.LoaderSection) sect);
527: }
528: }
529:
530: System.out.println("Loader should be added.");
531:
532: writeRef(PASSED);
533: } catch (Exception ex) {
534: printException(ex);
535: writeRef("Adding of DataLoader failed!", FAILED);
536: }
537: }
538:
539: /**
540: *Prints extensions that specified loader will recognize
541: *@param ufl UniFileLoader
542: */
543: void printExtensions(UniFileLoader ufl) {
544: if (ufl != null) {
545: writeRef("\nGetting registered file extension within this Loader ...");
546: en = ufl.getExtensions().extensions();
547: while (en.hasMoreElements())
548: writeRef(en.nextElement().toString());
549: writeRef(PASSED);
550: }
551: }
552:
553: /**
554: *Prints extensions that specified loader will recognize
555: *@param ufl UniFileLoader
556: */
557: boolean refPrintExtensions(DataLoader dl) {
558: if (dl != null) {
559: writeRef("\nGetting registered file extension within this Loader ...");
560: try {
561: //java.lang.reflect.Method[] ms = dl.getClass().getMethods();
562: //for(int i = 0 ; i < ms.length ; i ++) System.out.println(ms[i]);
563: java.lang.reflect.Method mm = dl.getClass().getMethod(
564: "getExtensions", new Class[0]);
565: Object obj = mm.invoke(dl, new Class[0]);
566: en = ((ExtensionList) obj).extensions();
567: while (en.hasMoreElements())
568: writeRef(en.nextElement().toString());
569: writeRef(PASSED);
570: return true;
571: } catch (Exception ex) {
572: printException(ex);
573: writeRef("Printing extensions failed!", FAILED);
574: }
575: }
576: return false;
577: }
578:
579: /**
580: *Two ways should return the same
581: */
582: void compareTest() {
583: // See above XXX.
584: // writeRef("\nComparing instances of NbLoaderPool ...");
585: // //dlp should be NbLoaderPool
586: // LoaderPoolNode.NbLoaderPool nblp = (LoaderPoolNode.NbLoaderPool) DLP;
587: //// LoaderPoolNode lpn = (LoaderPoolNode) ((Places)Lookup.getDefault().lookup(Places.class)).nodes().loaderPool();
588: // LoaderPoolNode.NbLoaderPool nblp_temp = lpn.getNbLoaderPool();
589: // //nblp and nblp_temp should be the same
590: // if ( ! nblp.equals(nblp_temp) ) writeRef("Got two different instances of DataLoaderPool!",FAILED);
591: // else writeRef(PASSED);
592: }
593:
594: /**
595: *Will consume specified amount of memory.
596: *Method: create String[amount]
597: *@param amount dimension of String array
598: */
599: void eatMemory(int amount) {
600: writeRef("\nConsuming memory ...");
601: String arr[] = new String[amount];
602: for (int i = 0; i < amount; i++)
603: arr[i] = "Something realy stupid here ;-) ...";
604: writeRef(" Done.");
605: }
606:
607: /**
608: *Tries to invoke garbage collection.
609: *Method: 3xgc, sleep 5s, 1xgc, sleep 5s
610: */
611: void sweepMemory() {
612: writeRef("\nSweeping memory ...");
613: for (int i = 0; i < 3; i++)
614: System.gc();
615: try {
616: Thread.currentThread().sleep(5000);
617: } catch (Exception ex) {
618: }
619: System.gc();
620: try {
621: Thread.currentThread().sleep(5000);
622: } catch (Exception ex) {
623: }
624: writeRef(" Done.");
625: }
626:
627: /**ONLY FOR TESTING PURPOSES
628: *REAL TESTS ARE IN SEPARATED CLASSES
629: */
630: public static void main(String args[]) {
631:
632: LoaderPoolTest lpt = new LoaderPoolTest("x");
633:
634: try {
635:
636: lpt.prepare();
637:
638: lpt.writeRef(new LoaderPoolTest("x").getClass().getName());
639:
640: //removeDataLoader(getDataLoader("Text"));
641: lpt.addDataLoader("org.netbeans.modules.text");
642:
643: lpt.clean();
644:
645: System.out.println("\n" + lpt.successful);
646:
647: } catch (Throwable ee) {
648: ee.printStackTrace(lpt.getRef());
649: ee.printStackTrace();
650: lpt.writeRef(lpt.FAILED);
651: }
652:
653: lpt.assertTrue(lpt.successful);
654:
655: }
656:
657: public void markRecognized(FileObject fo) {
658: }
659:
660: //if you want print exceptions into log file, put here true.
661: public final boolean PRINT_EXCEPTIONS = true;
662:
663: public final String PASSED = "passed.";
664: public final String FAILED = "failed.";
665: //workdir, this hould be set by an user of this class
666: //user of this class shouldn't use their own ref and log
667: public static String work = null;
668: }
|