KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > tests > xml > AbstractTestUtil


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 package org.netbeans.tests.xml;
20
21 import java.beans.PropertyChangeEvent JavaDoc;
22 import java.beans.PropertyChangeListener JavaDoc;
23 import java.beans.PropertyVetoException JavaDoc;
24 import java.io.*;
25 import java.net.MalformedURLException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.Random JavaDoc;
29 import javax.swing.text.BadLocationException JavaDoc;
30 import javax.swing.text.StyledDocument JavaDoc;
31 import org.netbeans.api.java.classpath.ClassPath;
32 import org.netbeans.jellytools.Bundle;
33 import org.netbeans.modules.xml.tax.cookies.TreeDocumentCookie;
34 import org.netbeans.tax.TreeDocument;
35 import org.netbeans.tax.TreeException;
36 import org.netbeans.tax.TreeNode;
37 import org.netbeans.tax.io.XMLStringResult;
38 import org.openide.cookies.EditorCookie;
39 import org.openide.cookies.SaveCookie;
40 import org.openide.filesystems.*;
41 import org.openide.filesystems.FileSystem.AtomicAction;
42 import org.openide.loaders.DataFolder;
43 import org.openide.loaders.DataObject;
44 import org.openide.loaders.DataObjectNotFoundException;
45 import org.openide.loaders.XMLDataObject;
46 import org.openide.modules.ModuleInfo;
47 import org.openide.util.Lookup;
48 import org.openide.util.NbBundle;
49 import org.openide.util.Lookup.Template;
50
51
52 /**
53  * Provides the basic support for XML API tests.
54  * @author mschovanek
55  */

56 public abstract class AbstractTestUtil {
57     protected static boolean DEBUG = true;
58     
59     public static final String JavaDoc CATALOG_PACKAGE = "org.netbeans.modules.xml.catalog";
60     public static final String JavaDoc CORE_PACKAGE = "org.netbeans.modules.xml.core";
61     public static final String JavaDoc TAX_PACKAGE = "org.netbeans.modules.xml.tax";
62     public static final String JavaDoc TEXT_PACKAGE = "org.netbeans.modules.xml.text";
63     public static final String JavaDoc TOOLS_PACKAGE = "org.netbeans.modules.xml.tools";
64     public static final String JavaDoc TREE_PACKAGE = "org.netbeans.modules.xml.tree";
65     
66     //--------------------------------------------------------------------------
67
// * * * X M L * * *
68
//--------------------------------------------------------------------------
69

70     /**
71      * Converts the TreeNode to a string.
72      */

73     public static String JavaDoc nodeToString(TreeNode node) {
74         try {
75             return XMLStringResult.toString(node);
76         } catch (TreeException te) {
77             return null;
78         }
79     }
80     
81     /**
82      * Converts the node to a string.
83      */

84     public static String JavaDoc nodeToString(Object JavaDoc node) {
85         return node.toString();
86     }
87     
88     //--------------------------------------------------------------------------
89
// * * * S T R I N G S * * *
90
//--------------------------------------------------------------------------
91

92     /** Search-and-replace string matches to expression "begin.*end"
93      * @param original the original string
94      * @param begin the begin of substring to be find
95      * @param end the end of substring to be find
96      * @param replaceTo the substring to replace it with
97      * @return a new string with 1st occurrence replaced
98      */

99     public static String JavaDoc replaceString(String JavaDoc original, String JavaDoc begin, String JavaDoc end, String JavaDoc replaceTo) {
100         int bi = original.indexOf(begin);
101         int ei = original.indexOf(end, bi) + end.length();
102         if (bi < 0 || ei < 0) {
103             return original;
104         } else {
105             return original.substring(0, bi) + replaceTo + original.substring(ei, original.length());
106         }
107     }
108     
109     /**
110      * Removes first character occurence from string.
111      */

112     public static String JavaDoc removeChar(String JavaDoc str, char ch) {
113         int index = str.indexOf(ch);
114         
115         if (index > -1) {
116             StringBuffer JavaDoc sb = new StringBuffer JavaDoc(str).deleteCharAt(str.indexOf(ch));
117             return new String JavaDoc(sb);
118         } else {
119             return str;
120         }
121     }
122     
123     /**
124      * Joins elemets delimited by delim.
125      */

126     public static String JavaDoc joinElements(String JavaDoc[] elements, String JavaDoc delim) {
127         if (elements == null) {
128             return null;
129         }
130         
131         String JavaDoc path = elements[0];
132         for (int i = 1; i < elements.length; i++) {
133             path += (delim + elements[i]);
134         }
135         return path;
136     }
137     
138     /**
139      * Returns last element.
140      */

141     public static final String JavaDoc lastElement(String JavaDoc string, String JavaDoc delim) {
142         int index = string.lastIndexOf(delim);
143         if (index == -1) {
144             return string;
145         } else {
146             return string.substring(index + 1);
147         }
148     }
149     
150     //--------------------------------------------------------------------------
151
// * * * S T R I N G L O C A L I Z A T I O N * * *
152
//--------------------------------------------------------------------------
153

154     /** Get localized string, removes '&' and cuts parameters like{0} from the end.
155      * @param key key of localized value.
156      * @return localized value.
157      */

158     public final String JavaDoc getStringTrimmed(String JavaDoc key) {
159         return Bundle.getStringTrimmed(getBundel(), key);
160     }
161     
162     /** Get localized string.
163      * @param key key of localized value.
164      * @return localized value.
165      */

166     public final String JavaDoc getString(String JavaDoc key) {
167         return NbBundle.getMessage(this.getClass(), key);
168     }
169     
170     /** Get localized string by passing parameter.
171      * @param key key of localized value.
172      * @param param argument to use when formating the message
173      * @return localized value.
174      */

175     public final String JavaDoc getString(String JavaDoc key, Object JavaDoc param) {
176         return NbBundle.getMessage(this.getClass(), key, param);
177     }
178     
179     /** Get localized string by passing parameter.
180      * @param key key of localized value.
181      * @param param1 argument to use when formating the message
182      * @param param2 the second argument to use for formatting
183      * @return localized value.
184      */

185     public final String JavaDoc getString(String JavaDoc key, Object JavaDoc param1, Object JavaDoc param2) {
186         return NbBundle.getMessage(this.getClass(), key, param1, param2);
187     }
188     
189     /** Get localized character. Usually used on mnemonic.
190      * @param key key of localized value.
191      * @return localized value.
192      */

193     public final char getChar(String JavaDoc key) {
194         return NbBundle.getMessage(this.getClass(), key).charAt(0);
195     }
196     
197     private String JavaDoc getBundel() {
198         return this.getClass().getPackage().getName() + ".Bundle";
199     }
200     
201     //--------------------------------------------------------------------------
202
// * * * D A T A O B J E C T S * * *
203
//--------------------------------------------------------------------------
204

205     /** Converts DataObject to String.
206      */

207     public static String JavaDoc dataObjectToString(DataObject dataObject) throws IOException, BadLocationException JavaDoc {
208         EditorCookie editorCookie = (EditorCookie) dataObject.getCookie(EditorCookie.class);
209         
210         if (editorCookie != null) {
211             StyledDocument JavaDoc document = editorCookie.openDocument();
212             if (document != null) {
213                 return document.getText(0, document.getLength());
214             }
215         }
216         return null;
217     }
218     
219     /** Saves DataObject
220      */

221     public static void saveDataObject(DataObject dataObject) throws IOException {
222         SaveCookie cookie = (SaveCookie) dataObject.getCookie(SaveCookie.class);
223         if (cookie == null) throw new IllegalStateException JavaDoc("Cannot save document without SaveCookie.");
224         cookie.save();
225     }
226     
227     //--------------------------------------------------------------------------
228
// * * * F I L E S Y S T E M S * * *
229
//--------------------------------------------------------------------------
230

231     /**
232      * Mounts local directory
233      */

234     public static LocalFileSystem mountDirectory(File dir) throws PropertyVetoException JavaDoc, IOException {
235         LocalFileSystem fs = new LocalFileSystem();
236         fs.setRootDirectory(dir);
237         Repository rep = Repository.getDefault();
238         FileSystem ffs = rep.findFileSystem(fs.getSystemName());
239         if (ffs != null) {
240             rep.removeFileSystem(ffs);
241         }
242         rep.addFileSystem(fs);
243         return fs;
244     }
245     
246     /**
247      * Opens the XML Document with the given package, name and extension
248      */

249     public static TreeDocument openXMLDocument(String JavaDoc aPackage, String JavaDoc name, String JavaDoc ext) throws IOException {
250         DataObject dao = findDataObject(aPackage, name, ext);
251         
252         if (dao == null) {
253             throw new IOException(aPackage + "." + name + "." + ext + " data object not found.");
254         }
255         
256         XMLDataObject xmlDataObject;
257         if (XMLDataObject.class.isInstance(dao)) {
258             xmlDataObject = (XMLDataObject) dao;
259         } else {
260             throw new IOException(aPackage + "." + name + "." + ext + " data object is not XMLDataObject.");
261         }
262         
263         TreeDocumentCookie cookie = (TreeDocumentCookie) xmlDataObject.getCookie(TreeDocumentCookie.class);
264         if (cookie == null) {
265             throw new IOException("Missing TreeDocumentCookie at " + aPackage + "." + name + "." + ext);
266         }
267         
268         TreeDocument document = (TreeDocument) cookie.getDocumentRoot();
269         if (document == null) {
270             throw new IOException("Ivalid XML data object" + aPackage + "." + name + "." + ext);
271         }
272         
273         return document;
274     }
275     
276     /**
277      * Deletes FileObject.
278      */

279     public static void deleteFileObject(FileObject fo) throws IOException {
280         DataObject dataObject = DataObject.find(fo);
281         dataObject.getNodeDelegate().destroy();
282     }
283     
284     /**
285      * Finds DataFolder.
286      */

287     public static DataFolder findFolder(String JavaDoc aPackage) throws Exception JavaDoc {
288         return (DataFolder) findDataObject(aPackage, null, null);
289     }
290     
291     /**
292      * Finds absolut path for FileObject.
293      */

294     public static String JavaDoc toAbsolutePath(FileObject fo) {
295         return FileUtil.toFile(fo).getAbsolutePath();
296     }
297     
298     /**
299      * Finds the DataObject with the given package, name and extension
300      */

301     public static DataObject findDataObject(String JavaDoc aPackage, String JavaDoc name, String JavaDoc ext) throws DataObjectNotFoundException {
302         FileObject fo = null;
303         fo = Repository.getDefault().find(aPackage, name, ext);
304         if (fo == null) {
305             return null;
306         } else {
307             return DataObject.find(fo);
308         }
309     }
310     
311     /**
312      * Finds the DataObject with the given package, name and extension
313      */

314     public static FileObject findFileObject(String JavaDoc aPackage, String JavaDoc name, String JavaDoc ext) {
315         return Repository.getDefault().find(aPackage, name, ext);
316     }
317     
318     /**
319      * Finds the DataObject with the given name in test's 'data' folder. The name of a resource is
320      * a "/"-separated path name that identifies the resource relatively to 'data' folder.<p />
321      * <i>e.g. "sub_dir/data.xml"</i>
322      */

323     public DataObject findData(String JavaDoc name) throws DataObjectNotFoundException {
324         //Repository.getDefault().
325
String JavaDoc resName = this.getClass().getPackage().getName();
326         resName = resName.replace('.', '/');
327         resName += "/data/" + name;
328         FileObject fo = ClassPath.getClassPath(null, ClassPath.EXECUTE).findResource(resName);
329         if (fo == null) {
330             if (DEBUG) {
331                 System.err.println("Cannot find FileObject: " + resName);
332             }
333             return null;
334         } else {
335             return DataObject.find(fo);
336         }
337     }
338     
339     /**
340      * Finds the DataObject with the given name. The name of a resource is
341      * a "/"-separated path name that identifies the resource or Nbfs URL.
342      */

343     public static DataObject findDataObject(String JavaDoc name) throws DataObjectNotFoundException {
344         FileObject fo = findFileObject(name);
345         if (fo == null) {
346             if (DEBUG) {
347                 System.err.println("Cannot find FileObject: " + name);
348             }
349             return null;
350         } else {
351             return DataObject.find(fo);
352         }
353     }
354     
355     /**
356      * Finds the FileObject with the given name. The name of a resource is
357      * a "/"-separated path name that identifies the resource or Nbfs URL.
358      */

359     public static FileObject findFileObject(String JavaDoc name) {
360         FileObject fo = null;
361         if (name.startsWith("nbfs:")) {
362             try {
363                 fo = URLMapper.findFileObject(new URL JavaDoc(name));
364             } catch (MalformedURLException JavaDoc mue) {};
365         } else {
366             fo = Repository.getDefault().findResource(name);
367         }
368         return fo;
369     }
370     
371     /**
372      * Finds the template with the given name.
373      */

374     public static DataObject getTemplate(String JavaDoc tname) throws DataObjectNotFoundException {
375         FileObject fileObject = Repository.getDefault().findResource("Templates/" + tname);
376         if (fileObject == null) {
377             throw new IllegalArgumentException JavaDoc("Cannot find template: " + tname);
378         }
379         return DataObject.find(fileObject);
380     }
381     
382     /**
383      * Creates new DataObject at the folder with given name from the template
384      * with the given tname.
385      */

386     public static DataObject newFromTemplate(String JavaDoc tname, String JavaDoc folder, String JavaDoc name) throws IOException {
387         DataObject dataObject = getTemplate(tname);
388         DataFolder dataFolder = (DataFolder) findDataObject(folder);
389         return dataObject.createFromTemplate(dataFolder, name);
390     }
391     
392     /**
393      * Removes the DataObject with the given name. The name of a resource is
394      * a "/"-separated path name that identifies the resource or Nbfs URL.
395      */

396     public static boolean removeDocument(String JavaDoc name) throws IOException {
397         DataObject dataObject = findDataObject(name);
398         if (dataObject != null) {
399             dataObject.delete();
400             return true;
401         } else {
402             return false;
403         }
404     }
405     
406     /**
407      * Creates new Data Object
408      */

409     public static DataObject createDataObject(DataFolder folder, final String JavaDoc name, final String JavaDoc extension, final String JavaDoc content) throws IOException {
410         final FileObject targetFolder = folder.getPrimaryFile();
411         FileSystem filesystem = targetFolder.getFileSystem();
412         
413         final FileObject[] fileObject = new FileObject[1];
414         AtomicAction fsAction = new AtomicAction() {
415             public void run() throws IOException {
416                 FileObject fo = targetFolder.createData(name, extension);
417                 FileLock lock = null;
418                 try {
419                     lock = fo.lock();
420                     OutputStream out = fo.getOutputStream(lock);
421                     out = new BufferedOutputStream(out, 999);
422                     Writer writer = new OutputStreamWriter(out, "UTF8"); // NOI18N
423
writer.write(content + '\n'); // NOI18N
424
writer.flush();
425                     writer.close();
426                     
427                     // return DataObject
428
lock.releaseLock();
429                     lock = null;
430                     
431                     fileObject[0] = fo;
432                     
433                 } finally {
434                     if (lock != null) lock.releaseLock();
435                 }
436             }
437         };
438         
439         filesystem.runAtomicAction(fsAction);
440         return DataObject.find(fileObject[0]);
441     }
442     
443     
444     
445     //--------------------------------------------------------------------------
446
// * * * O T H E R * * *
447
//--------------------------------------------------------------------------
448

449     /**
450      * Enbles <code>enable = true</code> or disables <code>enable = false</code> the module.
451      */

452     public static void switchModule(String JavaDoc codeName, boolean enable) throws Exception JavaDoc {
453         String JavaDoc statusFile = "Modules/" + codeName.replace('.', '-') + ".xml";
454         ModuleInfo mi = getModuleInfo(codeName);
455 /*
456         FileObject fo = findFileObject(statusFile);
457         Document document = XMLUtil.parse(new InputSource(fo.getInputStream()), false, false, null, EntityCatalog.getDefault());
458         //Document document = XMLUtil.parse(new InputSource(data.getPrimaryFile().getInputStream()), false, false, null, EntityCatalog.getDefault());
459         NodeList list = document.getElementsByTagName("param");
460  
461         for (int i = 0; i < list.getLength(); i++) {
462             Element ele = (Element) list.item(i);
463             if (ele.getAttribute("name").equals("enabled")) {
464                 ele.getFirstChild().setNodeValue(enable ? "true" : "false");
465                 break;
466             }
467         }
468  
469         FileLock lock = fo.lock();
470         OutputStream os = fo.getOutputStream(lock);
471         XMLUtil.write(document, os, "UTF-8");
472         lock.releaseLock();
473         os.close();
474  */

475         
476         // module is switched
477
if (mi.isEnabled() == enable) {
478             return;
479         }
480         
481         DataObject data = findDataObject(statusFile);
482         EditorCookie ec = (EditorCookie) data.getCookie(EditorCookie.class);
483         StyledDocument JavaDoc doc = ec.openDocument();
484         
485         // Change parametr enabled
486
String JavaDoc stag = "<param name=\"enabled\">";
487         String JavaDoc etag = "</param>";
488         String JavaDoc enabled = enable ? "true" : "false";
489         String JavaDoc result;
490         
491         String JavaDoc str = doc.getText(0,doc.getLength());
492         int sindex = str.indexOf(stag);
493         int eindex = str.indexOf(etag, sindex);
494         if (sindex > -1 && eindex > sindex) {
495             result = str.substring(0, sindex + stag.length()) + enabled + str.substring(eindex);
496             //System.err.println(result);
497
} else {
498             //throw new IllegalStateException("Invalid format of: " + statusFile + ", missing parametr 'enabled'");
499
// Probably autoload module
500
return;
501         }
502         
503         // prepare synchronization and register listener
504
final Waiter waiter = new Waiter();
505         final PropertyChangeListener JavaDoc pcl = new PropertyChangeListener JavaDoc() {
506             public void propertyChange(PropertyChangeEvent JavaDoc evt) {
507                 if (evt.getPropertyName().equals("enabled")) {
508                     waiter.notifyFinished();
509                 }
510             }
511         };
512         mi.addPropertyChangeListener(pcl);
513         
514         // save document
515
doc.remove(0,doc.getLength());
516         doc.insertString(0,result,null);
517         ec.saveDocument();
518         
519         // wait for enabled propety change and remove listener
520
waiter.waitFinished();
521         mi.removePropertyChangeListener(pcl);
522     }
523     
524     /**
525      * Switch on all XML modules and returns <code>true</code> if change state of any module else <code>false</code>.
526      */

527     public static boolean switchAllXMLModules(boolean enable) throws Exception JavaDoc {
528         boolean result = false;
529         Iterator JavaDoc it = Lookup.getDefault().lookup(new Template(ModuleInfo.class)).allInstances().iterator();
530         
531         while (it.hasNext()) {
532             ModuleInfo mi = (ModuleInfo) it.next();
533             if (mi.getCodeNameBase().startsWith("org.netbeans.modules.xml.") && (mi.isEnabled() != enable)) {
534                 switchModule(mi.getCodeNameBase(), enable);
535                 result = true;
536             }
537         }
538         return result;
539     }
540     
541     /**
542      * Returns module's info or <code>null</null>.
543      */

544     public static ModuleInfo getModuleInfo(String JavaDoc codeName) {
545         Iterator JavaDoc it = Lookup.getDefault().lookup(new Template(ModuleInfo.class)).allInstances().iterator();
546         
547         while (it.hasNext()) {
548             ModuleInfo mi = (ModuleInfo) it.next();
549             // if (mi.getCodeNameBase().equals(codeName) && mi.isEnabled()) {
550
if (mi.getCodeNameBase().equals(codeName)) {
551                 return mi;
552             }
553         }
554         return null;
555     }
556     
557     /**
558      * Returns <code>true</code> if module is enabled else <code>false</code>.
559      */

560     public static boolean isModuleEnabled(String JavaDoc codeName) {
561         ModuleInfo mi = getModuleInfo(codeName);
562         if (mi == null) {
563             throw new IllegalArgumentException JavaDoc("Invalid codeName: " + codeName);
564         }
565         
566         return mi.isEnabled();
567     }
568     
569     protected static Random JavaDoc randomGenerator = new Random JavaDoc();
570     
571     /**
572      * Generates random integer.
573      */

574     public static int randomInt(int n) {
575         return randomGenerator.nextInt(n);
576     }
577     
578     // ************************
579
// * * * C L A S E S * * *
580
// ************************
581

582     static class Waiter {
583         private boolean finished = false;
584         
585         /** Restarts Synchronizer.
586          */

587         public void start() {
588             finished = false;
589         }
590         
591         /** Wait until the task is finished.
592          */

593         public void waitFinished() {
594             if (!finished) {
595                 synchronized (this) {
596                     while (!finished) {
597                         try {
598                             wait();
599                         } catch (InterruptedException JavaDoc ex) {
600                         }
601                     }
602                 }
603             }
604         }
605         
606         /** Notify all waiters that this task has finished.
607          */

608         public void notifyFinished() {
609             synchronized (this) {
610                 finished = true;
611                 notifyAll();
612             }
613         }
614     }
615 }
616
Popular Tags