KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > junit > TestUtil


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-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.junit;
21
22 import com.sun.source.tree.ClassTree;
23 import com.sun.source.tree.CompilationUnitTree;
24 import com.sun.source.tree.Tree;
25 import java.net.URL JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.logging.Logger JavaDoc;
28 import org.netbeans.api.java.classpath.ClassPath;
29 import org.netbeans.api.java.queries.UnitTestForSourceQuery;
30 import org.netbeans.api.java.source.CompilationInfo;
31 import org.netbeans.api.project.FileOwnerQuery;
32 import org.netbeans.api.project.Project;
33 import org.netbeans.api.project.SourceGroup;
34 import org.netbeans.modules.junit.plugin.JUnitPlugin;
35 import org.netbeans.modules.junit.plugin.JUnitPlugin.CreateTestParam;
36 import org.netbeans.modules.junit.wizards.Utils;
37 import org.openide.DialogDisplayer;
38 import org.openide.ErrorManager;
39 import org.openide.NotifyDescriptor;
40 import org.openide.filesystems.FileObject;
41 import org.openide.filesystems.FileUtil;
42 import org.openide.filesystems.URLMapper;
43 import org.openide.loaders.DataFolder;
44 import org.openide.loaders.DataObject;
45 import org.openide.loaders.DataObjectNotFoundException;
46 import org.openide.nodes.Node;
47 import java.util.ArrayList JavaDoc;
48 import java.util.Collection JavaDoc;
49 import java.util.HashMap JavaDoc;
50 import java.util.List JavaDoc;
51 import java.util.Map JavaDoc;
52 import java.util.Set JavaDoc;
53 import java.util.StringTokenizer JavaDoc;
54 import java.util.logging.Level JavaDoc;
55 import javax.lang.model.element.TypeElement;
56 import org.openide.util.Utilities;
57
58
59 /**
60  *
61  * @author rmatous
62  * @author Marian Petras
63  * @version 1.1
64  */

65 public class TestUtil {
66     static private final String JavaDoc JAVA_SOURCES_SUFFIX = "java";
67     private static final String JavaDoc JAVA_MIME_TYPE = "text/x-java"; //NOI18N
68

69     static private String JavaDoc getTestClassSuffix() {
70         return JUnitSettings.TEST_CLASSNAME_SUFFIX;
71     }
72     
73     static private String JavaDoc getTestClassPrefix() {
74         return JUnitSettings.TEST_CLASSNAME_PREFIX;
75     }
76     
77     static private String JavaDoc getTestSuiteSuffix() {
78         return JUnitSettings.SUITE_CLASSNAME_SUFFIX;
79     }
80     
81     static private String JavaDoc getTestSuitePrefix() {
82         return JUnitSettings.SUITE_CLASSNAME_PREFIX;
83     }
84     
85     static private String JavaDoc getRootSuiteName() {
86         return JUnitSettings.getDefault().getRootSuiteClassName();
87     }
88     
89     //
90
// test class names
91
//
92
public static String JavaDoc getTestClassFullName(String JavaDoc sourceClassName, String JavaDoc packageName) {
93         String JavaDoc shortTestClassName = getTestClassName(sourceClassName);
94         return ((packageName == null) || (packageName.length() == 0))
95                ? shortTestClassName
96                : packageName.replace('.','/') + '/' + shortTestClassName;
97     }
98     
99     public static String JavaDoc getTestClassName(String JavaDoc sourceClassName) {
100         return getTestClassPrefix() + sourceClassName + getTestClassSuffix();
101     }
102         
103     
104     //
105
// suite class names
106
//
107

108     
109     /**
110      * Converts given package filename to test suite filename, e.g.
111      * &quot;<tt>org/netbeans/foo</tt>&quot; -&gt;
112      * &quot;<tt>org/netbeans/foo/{suite-prefix}Foo{suite-suffix}</tt>&quot;
113      * @param packageFileName package filename in form of "org/netbeans/foo"
114      */

115     public static String JavaDoc convertPackage2SuiteName(String JavaDoc packageFileName) {
116         if (packageFileName.length() == 0) {
117             return getRootSuiteName();
118         } else {
119             int index = packageFileName.lastIndexOf('/');
120             String JavaDoc pkg = index > -1 ? packageFileName.substring(index+1) : packageFileName;
121             pkg = pkg.substring(0, 1).toUpperCase() + pkg.substring(1);
122             return packageFileName + "/" + getTestSuitePrefix()+pkg+getTestSuiteSuffix();
123         }
124     }
125     
126     
127     /**
128      * Converts given class filename to test filename, e.g.
129      * &quot;<tt>org/netbeans/Foo</tt>&quot;
130      * -&gt; &quot;<tt>org/netbeans/{test-prefix}Foo{test-suffix}</tt>&quot;
131      *
132      * @param classFileName class filename in form of
133      * &quot;<tt>org/netbeans/Foo</tt>&quot;,
134      * i.e. without extension, no inner class
135      */

136     public static String JavaDoc convertClass2TestName(String JavaDoc classFileName) {
137         int index = classFileName.lastIndexOf('/');
138         String JavaDoc pkg = index > -1 ? classFileName.substring(0, index) : "";
139         String JavaDoc clazz = index > -1 ? classFileName.substring(index+1) : classFileName;
140         clazz = clazz.substring(0, 1).toUpperCase() + clazz.substring(1);
141         if (pkg.length() > 0) {
142             pkg += "/";
143         }
144         return pkg + getTestClassPrefix()+clazz+getTestClassSuffix();
145     }
146
147     /**
148      * Show error message box.
149      */

150     public static void notifyUser(String JavaDoc msg) {
151         notifyUser(msg, NotifyDescriptor.ERROR_MESSAGE);
152     }
153     
154     /**
155      * Show message box of the specified severity.
156      */

157     public static void notifyUser(String JavaDoc msg, int messageType) {
158         NotifyDescriptor descr = new NotifyDescriptor.Message(msg, messageType);
159         DialogDisplayer.getDefault().notify(descr);
160     }
161
162
163     
164     // other misc methods
165

166     static public FileObject getFileObjectFromNode(Node node) {
167         DataObject dO;
168         DataFolder df;
169         
170         dO = node.getCookie(DataObject.class);
171         if (null != dO)
172             return dO.getPrimaryFile();
173
174         df = node.getCookie(DataFolder.class);
175         if (null != df)
176             return df.getPrimaryFile();
177         
178 //XXX: retouche
179
// ClassElement ce = (ClassElement) node.getCookie(ClassElement.class);
180
// if (null != ce) {
181
// // find the parent DataObject, which node belongs to
182
// while (null != (node = node.getParentNode())) {
183
// if (null != (dO = (DataObject) node.getCookie(DataObject.class)))
184
// return dO.getPrimaryFile();
185
// }
186
// }
187
return null;
188     }
189
190     /**
191      */

192     static boolean isJavaFile(FileObject fileObj) {
193         return "java".equals(fileObj.getExt()) //NOI18N
194
|| "text/x-java".equals(FileUtil.getMIMEType(fileObj)); //NOI18N
195
}
196     
197
198         
199     static boolean isClassTest(CompilationInfo compilationInfo,
200                                TypeElement classElem) {
201         return isClassImplementingTestInterface(compilationInfo, classElem);
202     }
203     
204     // is JavaClass a Test class?
205
static boolean isClassImplementingTestInterface(
206                                             CompilationInfo compilationInfo,
207                                             TypeElement classElem) {
208         String JavaDoc testIfaceFullName = "junit.framework.Test"; //NOI18N
209
TypeElement testIface = compilationInfo.getElements()
210                                .getTypeElement(testIfaceFullName);
211         
212         if (testIface == null) {
213             String JavaDoc msg = "junit: TestUtil.isClassImplementingTestInterface(...) " //NOI18N
214
+ "could not find TypeElement for " //NOI18N
215
+ testIfaceFullName;
216             Logger.getLogger("global").log(Level.WARNING, msg); //NOI18N
217
return false;
218         }
219         
220         return compilationInfo.getTypes().isSubtype(classElem.asType(),
221                                                     testIface.asType());
222     }
223     
224         
225     
226     // is class an exception
227

228
229     static boolean isClassException(CompilationInfo compilationInfo,
230                                     TypeElement classElem) {
231         String JavaDoc throwableFullName = "java.lang.Throwable"; //NOI18N
232
TypeElement throwable = compilationInfo.getElements()
233                                 .getTypeElement(throwableFullName);
234         
235         if (throwable == null) {
236             String JavaDoc msg = "junit: TestUtil.isClassException(...) " //NOI18N
237
+ "could not find TypeElement for " //NOI18N
238
+ throwableFullName;
239             Logger.getLogger("global").log(Level.SEVERE, msg); //NOI18N
240
return false;
241         }
242         
243         return compilationInfo.getTypes().isSubtype(classElem.asType(),
244                                                     throwable.asType());
245     }
246
247
248     /**
249      * Finds a main class.
250      *
251      * @param compInfo defines scope in which the class is to be found
252      * @param className name of the class to be found
253      * @return the found class; or <code>null</code> if the class was not
254      * found (e.g. because of a broken source file)
255      */

256     public static ClassTree findMainClass(final CompilationInfo compInfo) {
257         final String JavaDoc className = compInfo.getFileObject().getName();
258         
259         CompilationUnitTree compUnitTree = compInfo.getCompilationUnit();
260         String JavaDoc shortClassName = getSimpleName(className);
261         for (Tree typeDecl : compUnitTree.getTypeDecls()) {
262             if (Tree.Kind.CLASS == typeDecl.getKind()) {
263                 ClassTree clazz = (ClassTree) typeDecl;
264                 if (clazz.getSimpleName().toString().equals(shortClassName)) {
265                     return clazz;
266                 }
267             }
268         }
269         return null;
270     }
271     
272     /**
273      * Converts filename to the fully qualified name of the main class
274      * residing in the file.<br />
275      * For example: <tt>test/myapp/App.java</tt> --&gt; <tt>test.myapp.App</tt>
276      *
277      * @param filename
278      * @return corresponding package name. Null if the input is not
279      * well formed.
280      */

281     static String JavaDoc fileToClassName(String JavaDoc fileName) {
282         if (fileName.endsWith(".java")) { //NOI18N
283
return (fileName.substring(0, fileName.length()-5)).replace('/','.');
284         } else
285             return null;
286     }
287
288     /**
289      * Returns full names of all primary Java classes
290      * withing the specified folder (non-recursive).
291      *
292      * @param packageFolder folder to search
293      * @param classPath classpath to be used for the search
294      * @return list of full names of all primary Java classes
295      * within the specified package
296      */

297     public static List JavaDoc<String JavaDoc> getJavaFileNames(FileObject packageFolder, ClassPath classPath) {
298         FileObject[] children = packageFolder.getChildren();
299         if (children.length == 0) {
300             return Collections.<String JavaDoc>emptyList();
301         }
302         
303         List JavaDoc<String JavaDoc> result = new ArrayList JavaDoc<String JavaDoc>(children.length);
304         for (FileObject child : children) {
305             if (child.isFolder() || child.isVirtual()
306                     || !child.getMIMEType().equals(JAVA_MIME_TYPE)) {
307                 continue;
308             }
309
310             DataObject dataObject;
311             try {
312                 dataObject = DataObject.find(child);
313             } catch (DataObjectNotFoundException ex) {
314                 continue;
315             }
316
317 //XXX: retouche
318
// Resource rc = JavaModel.getResource(dataObject.getPrimaryFile());
319
// result.add(getMainJavaClass(rc).getName());
320
}
321         return result.isEmpty() ? Collections.<String JavaDoc>emptyList() : result;
322     }
323
324 //XXX: retouche
325
// public static List filterFeatures(JavaClass cls, Class type) {
326
// LinkedList ret = new LinkedList();
327
// Iterator it = cls.getFeatures().iterator();
328
//
329
// while (it.hasNext()) {
330
// Feature f = (Feature)it.next();
331
// if (type.isAssignableFrom(f.getClass())) ret.add(f);
332
// }
333
// return ret;
334
// }
335

336 //XXX: retouche
337
// public static Feature getFeatureByName(JavaClass src, Class cls, String name) {
338
// if (!Feature.class.isAssignableFrom(cls)) throw new IllegalArgumentException("cls is not Feature");
339
//
340
// Iterator it = src.getFeatures().iterator();
341
// while (it.hasNext()) {
342
// Object o = it.next();
343
// if (cls.isAssignableFrom(o.getClass())) {
344
// Feature f = (Feature)o;
345
// if (f.getName().equals(name)) return f;
346
// }
347
// }
348
// return null;
349
// }
350

351
352 //XXX: retouche
353
// public static JavaClass getClassBySimpleName(JavaClass cls, String name) {
354
// return cls.getInnerClass(name, false);
355
// }
356

357     static public String JavaDoc createNewName(int i, Set JavaDoc usedNames) {
358         String JavaDoc ret;
359         do {
360             ret = "p" + i++;
361         } while (usedNames.contains(ret));
362         return ret;
363     }
364
365 //XXX: retouche
366
// static public Parameter cloneParam(Parameter p, JavaModelPackage pkg, int order, Set usedNames) {
367
// String name = p.getName();
368
// if (name == null || name.length()==0 || usedNames.contains(name)) {
369
// name = createNewName(order, usedNames);
370
// }
371
// usedNames.add(name);
372
//
373
//
374
// Parameter ret =
375
// pkg.getParameter().
376
// createParameter(name,
377
// p.getAnnotations(),
378
// p.isFinal(),
379
// null,
380
// 0,//p.getDimCount(),
381
// p.isVarArg());
382
// ret.setType(p.getType());
383
// return ret;
384
// }
385

386 //XXX: retouche
387
// public static List cloneParams(List params, JavaModelPackage pkg) {
388
// Iterator origParams = params.iterator();
389
// List newParams = new LinkedList();
390
// int o = 0;
391
// HashSet usedNames = new HashSet(params.size()*2);
392
// while (origParams.hasNext()) {
393
// Parameter p = (Parameter)origParams.next();
394
// newParams.add(TestUtil.cloneParam(p, pkg, o++, usedNames));
395
// }
396
// return newParams;
397
// }
398

399
400 //XXX: retouche
401
// /**
402
// * Gets collection of types of the parameters passed in in the
403
// * argument. The returned collection has the same size as the
404
// * input collection.
405
// * @param params List<Parameter>
406
// * @return List<Type>
407
// */
408
// static public List getParameterTypes(List params) {
409
// List ret = new ArrayList(params.size());
410
// Iterator it = params.iterator();
411
// while (it.hasNext()) {
412
// ret.add(((Parameter)it.next()).getType());
413
// }
414
// return ret;
415
// }
416

417
418
419 //XXX: retouche
420
// /**
421
// * Gets list of all features within the given class of the given
422
// * class and modifiers.
423
// * @param c the JavaClass to search
424
// * @param cls the Class to search for
425
// * @param modifiers the modifiers to search for
426
// * @param recursive if true, the search descents to superclasses
427
// * and interfaces
428
// * @return List of the collected Features
429
// */
430
// public static List collectFeatures(JavaClass c, Class cls,
431
// int modifiers, boolean recursive) {
432
//
433
// return collectFeatures(c, cls, modifiers, recursive, new LinkedList(), new HashSet());
434
// }
435

436
437
438
439 //XXX: retouche
440
// private static List collectFeatures(JavaClass c, Class cls,
441
// int modifiers, boolean recursive,
442
// List list, Set visited )
443
// {
444
//
445
// if (!visited.add(c)) return list;
446
// // this class
447
//
448
// int mo = (c.isInterface()) ? Modifier.ABSTRACT : 0;
449
// Iterator it = TestUtil.filterFeatures(c, cls).iterator();
450
// while (it.hasNext()) {
451
// Feature m = (Feature)it.next();
452
// if (((m.getModifiers() | mo) & modifiers) == modifiers) {
453
// list.add(m);
454
// }
455
// }
456
//
457
// if (recursive) {
458
// // super
459
// JavaClass sup = c.getSuperClass();
460
// if (sup != null) collectFeatures(sup, cls, modifiers, recursive, list, visited);
461
//
462
// // interfaces
463
// Iterator ifaces = c.getInterfaces().iterator();
464
// while (ifaces.hasNext()) collectFeatures((JavaClass)ifaces.next(), cls,
465
// modifiers, recursive, list, visited);
466
// }
467
//
468
// return list;
469
// }
470

471 //XXX: retouche
472
// public static boolean hasMainMethod(JavaClass cls) {
473
//
474
// JavaModelPackage pkg = (JavaModelPackage)cls.refImmediatePackage();
475
// return cls.getMethod("main",
476
// Collections.singletonList(pkg.getArray().resolveArray(TestUtil.getStringType(pkg))),
477
// false) != null;
478
//
479
// }
480

481 //XXX: retouche
482
// public static Type getStringType(JavaModelPackage pkg) {
483
// return pkg.getType().resolve("java.lang.String");
484
// }
485

486 //XXX: retouche
487
// public static TypeReference getTypeReference(JavaModelPackage pkg, String name) {
488
// return pkg.getMultipartId().createMultipartId(name, null, Collections.EMPTY_LIST);
489
// }
490

491     /**
492      * Finds <code>SourceGroup</code>s where a test for the given class
493      * can be created (so that it can be found by the projects infrastructure
494      * when a test for the class is to be opened or run).
495      *
496      * @param fileObject <code>FileObject</code> to find target
497      * <code>SourceGroup</code>(s) for
498      * @return an array of objects - each of them can be either
499      * a <code>SourceGroup</code> for a possible target folder
500      * or simply a <code>FileObject</code> representing a possible
501      * target folder (if <code>SourceGroup</code>) for the folder
502      * was not found);
503      * the returned array may be empty but not <code>null</code>
504      * @author Marian Petras
505      */

506     public static Object JavaDoc[] getTestTargets(FileObject fileObject) {
507         
508         /* .) get project owning the given FileObject: */
509         final Project project = FileOwnerQuery.getOwner(fileObject);
510         if (project == null) {
511             return new Object JavaDoc[0];
512         }
513         
514         SourceGroup sourceGroupOwner = findSourceGroupOwner(fileObject);
515         if (sourceGroupOwner == null) {
516             return new Object JavaDoc[0];
517         }
518         
519         /* .) get URLs of target SourceGroup's roots: */
520         final URL JavaDoc[] rootURLs = UnitTestForSourceQuery.findUnitTests(
521                                        sourceGroupOwner.getRootFolder());
522         if (rootURLs.length == 0) {
523             return new Object JavaDoc[0];
524         }
525         
526         /* .) convert the URLs to FileObjects: */
527         boolean someSkipped = false;
528         FileObject[] sourceRoots = new FileObject[rootURLs.length];
529         for (int i = 0; i < rootURLs.length; i++) {
530             if ((sourceRoots[i] = URLMapper.findFileObject(rootURLs[i]))
531                     == null) {
532                 ErrorManager.getDefault().notify(
533                         ErrorManager.INFORMATIONAL,
534                         new IllegalStateException JavaDoc(
535                            "No FileObject found for the following URL: "//NOI18N
536
+ rootURLs[i]));
537                 someSkipped = true;
538                 continue;
539             }
540             if (FileOwnerQuery.getOwner(sourceRoots[i]) != project) {
541                 ErrorManager.getDefault().notify(
542                         ErrorManager.INFORMATIONAL,
543                         new IllegalStateException JavaDoc(
544                     "Source root found by FileOwnerQuery points " //NOI18N
545
+ "to a different project for the following URL: " //NOI18N
546
+ rootURLs[i]));
547                 sourceRoots[i] = null;
548                 someSkipped = true;
549                 continue;
550             }
551         }
552         
553         if (someSkipped) {
554             FileObject roots[] = skipNulls(sourceRoots, new FileObject[0]);
555             if (roots.length == 0) {
556                 return new Object JavaDoc[0];
557             }
558             sourceRoots = roots;
559         }
560         
561         /* .) find SourceGroups corresponding to the FileObjects: */
562         final Object JavaDoc[] targets = new Object JavaDoc[sourceRoots.length];
563         Map JavaDoc<FileObject,SourceGroup> map = getFileObject2SourceGroupMap(project);
564         for (int i = 0; i < sourceRoots.length; i++) {
565             SourceGroup srcGroup = map.get(sourceRoots[i]);
566             targets[i] = srcGroup != null ? srcGroup : sourceRoots[i];
567         }
568         return targets;
569     }
570     
571     /**
572      * Finds a <code>SourceGroup</code> the given file belongs to.
573      * Only Java <code>SourceGroup</code>s are taken into account.
574      *
575      * @param file <code>FileObject</code> whose owning
576      * <code>SourceGroup</code> to be found
577      * @return Java <code>SourceGroup</code> containing the given
578      * file; or <code>null</code> if no such
579      * <code>SourceGroup</code> was found
580      * @author Marian Petras
581      */

582     public static SourceGroup findSourceGroupOwner(FileObject file) {
583         final Project project = FileOwnerQuery.getOwner(file);
584         return findSourceGroupOwner(project, file);
585     }
586     
587     /**
588      * Finds a <code>SourceGroup</code> the given file belongs to.
589      * Only Java <code>SourceGroup</code>s are taken into account.
590      *
591      * @param project the <code>Project</code> the file belongs to
592      * @param file <code>FileObject</code> whose owning
593      * <code>SourceGroup</code> to be found
594      * @return Java <code>SourceGroup</code> containing the given
595      * file; or <code>null</code> if no such
596      * <code>SourceGroup</code> was found
597      */

598
599     public static SourceGroup findSourceGroupOwner(Project project, FileObject file) {
600         final SourceGroup[] sourceGroups
601                 = new Utils(project).getJavaSourceGroups();
602         for (int i = 0; i < sourceGroups.length; i++) {
603             SourceGroup srcGroup = sourceGroups[i];
604             FileObject root = srcGroup.getRootFolder();
605             if (((file==root)||(FileUtil.isParentOf(root,file))) &&
606                  srcGroup.contains(file)) {
607                 return srcGroup;
608             }
609         }
610         return null;
611     }
612     
613     /**
614      * Finds all <code>SourceGroup</code>s of the given project
615      * containing a class of the given name.
616      *
617      * @param project project to be searched for matching classes
618      * @param className class name pattern
619      * @return unmodifiable collection of <code>SourceGroup</code>s
620      * which contain files corresponding to the given name
621      * (may be empty but not <code>null</code>)
622      * @author Marian Petras
623      */

624     public static Collection JavaDoc<SourceGroup> findSourceGroupOwners(
625             final Project project,
626             final String JavaDoc className) {
627         final SourceGroup[] sourceGroups
628                 = new Utils(project).getJavaSourceGroups();
629         if (sourceGroups.length == 0) {
630             return Collections.<SourceGroup>emptyList();
631         }
632         
633         final String JavaDoc relativePath = className.replace('.', '/')
634                                     + ".java"; //NOI18N
635

636         ArrayList JavaDoc<SourceGroup> result = new ArrayList JavaDoc<SourceGroup>(4);
637         for (int i = 0; i < sourceGroups.length; i++) {
638             SourceGroup srcGroup = sourceGroups[i];
639             FileObject root = srcGroup.getRootFolder();
640             FileObject file = root.getFileObject(relativePath);
641             if (file != null && FileUtil.isParentOf(root, file)
642                              && srcGroup.contains(file)) {
643                 result.add(srcGroup);
644             }
645         }
646         if (result.isEmpty()) {
647             return Collections.<SourceGroup>emptyList();
648         }
649         result.trimToSize();
650         return Collections.unmodifiableList(result);
651     }
652     
653     /**
654      * Creates a copy of the given array, except that <code>null</code> objects
655      * are omitted.
656      * The length of the returned array is (<var>l</var> - <var>n</var>), where
657      * <var>l</var> is length of the passed array and <var>n</var> is number
658      * of <code>null</code> elements of the array. Order of
659      * non-<code>null</code> elements is kept in the returned array.
660      * The returned array is always a new array, even if the passed
661      * array does not contain any <code>null</code> elements.
662      *
663      * @param objs array to copy
664      * @param type an empty array of the correct type to be returned
665      * @return array containing the same objects as the passed array, in the
666      * same order, just with <code>null</code> elements missing
667      * @author Marian Petras
668      */

669     public static <T> T[] skipNulls(final T[] objs, final T[] type) {
670         List JavaDoc<T> resultList = new ArrayList JavaDoc<T>(objs.length);
671         
672         for (int i = 0; i < objs.length; i++) {
673             if (objs[i] != null) {
674                 resultList.add(objs[i]);
675             }
676         }
677         
678         return resultList.toArray(type);
679     }
680     
681     /**
682      * Creates a map from folders to <code>SourceGroup</code>s of a given
683      * project.
684      * The map allows to ascertian for a given folder
685      * which <code>SourceGroup</code> it is a root folder of.
686      *
687      * @param project project whose <code>SourceGroup</code>s should be in the
688      * returned map
689      * @return map from containing all <code>SourceGroup</code>s of a given
690      * project, having their root folders as keys
691      * @author Marian Petras
692      */

693     public static Map JavaDoc<FileObject,SourceGroup> getFileObject2SourceGroupMap(
694                                                               Project project) {
695         final SourceGroup[] sourceGroups
696                 = new Utils(project).getJavaSourceGroups();
697         
698         if (sourceGroups.length == 0) {
699             return Collections.<FileObject,SourceGroup>emptyMap();
700         } else if (sourceGroups.length == 1) {
701             return Collections.singletonMap(sourceGroups[0].getRootFolder(),
702                                             sourceGroups[0]);
703         } else {
704             Map JavaDoc<FileObject,SourceGroup> map;
705             map = new HashMap JavaDoc<FileObject,SourceGroup>(
706                     Math.round(sourceGroups.length * 1.4f + .5f),
707                                .75f);
708             for (int i = 0; i < sourceGroups.length; i++) {
709                 map.put(sourceGroups[i].getRootFolder(),
710                         sourceGroups[i]);
711             }
712             return map;
713         }
714     }
715
716     // Nice copy of useful methods (Taken from JavaModule)
717
public static boolean isValidPackageName(String JavaDoc str) {
718         if (str.length() > 0 && str.charAt(0) == '.') {
719             return false;
720         }
721         StringTokenizer JavaDoc tukac = new StringTokenizer JavaDoc(str, ".");
722         while (tukac.hasMoreTokens()) {
723             String JavaDoc token = tukac.nextToken();
724             if ("".equals(token))
725                 return false;
726             if (!Utilities.isJavaIdentifier(token))
727                 return false;
728         }
729         return true;
730     }
731     
732     /**
733      *
734      */

735     public static JUnitPlugin getPluginForProject(final Project project) {
736         Object JavaDoc pluginObj = project.getLookup().lookup(JUnitPlugin.class);
737         return (pluginObj != null) ? (JUnitPlugin) pluginObj
738                                    : new DefaultPlugin();
739     }
740
741     /**
742      * Creates a map of parameters according to the current JUnit module
743      * settings.<br />
744      * Note: The map may not contain all the necessary settings,
745      * i.g. name of a test class is missing.
746      *
747      * @param multipleFiles if {@code true}, the map should contain
748      * also settings need for creation of multiple
749      * tests
750      * @return map of settings to be used by a
751      * {@link org.netbeans.modules.junit.plugin JUnitPlugin}
752      * @see org.netbeans.modules.junit.plugin.JUnitPlugin
753      */

754     public static Map JavaDoc<CreateTestParam, Object JavaDoc> getSettingsMap(
755             boolean multipleFiles) {
756         final JUnitSettings settings = JUnitSettings.getDefault();
757         final Map JavaDoc<CreateTestParam, Object JavaDoc> params
758                     = new HashMap JavaDoc<CreateTestParam, Object JavaDoc>(17);
759         
760         params.put(CreateTestParam.INC_PUBLIC,
761                    Boolean.valueOf(settings.isMembersPublic()));
762         params.put(CreateTestParam.INC_PROTECTED,
763                    Boolean.valueOf(settings.isMembersProtected()));
764         params.put(CreateTestParam.INC_PKG_PRIVATE,
765                    Boolean.valueOf(settings.isMembersPackage()));
766         params.put(CreateTestParam.INC_CODE_HINT,
767                    Boolean.valueOf(settings.isBodyComments()));
768         params.put(CreateTestParam.INC_METHOD_BODIES,
769                    Boolean.valueOf(settings.isBodyContent()));
770         params.put(CreateTestParam.INC_JAVADOC,
771                    Boolean.valueOf(settings.isJavaDoc()));
772         
773         if (multipleFiles) {
774             params.put(CreateTestParam.INC_GENERATE_SUITE,
775                        Boolean.valueOf(settings.isGenerateSuiteClasses()));
776             params.put(CreateTestParam.INC_PKG_PRIVATE_CLASS,
777                     Boolean.valueOf(settings.isIncludePackagePrivateClasses()));
778             params.put(CreateTestParam.INC_ABSTRACT_CLASS,
779                        Boolean.valueOf(settings.isGenerateAbstractImpl()));
780             params.put(CreateTestParam.INC_EXCEPTION_CLASS,
781                        Boolean.valueOf(settings.isGenerateExceptionClasses()));
782         }
783         
784         params.put(CreateTestParam.INC_SETUP,
785                    Boolean.valueOf(settings.isGenerateSetUp()));
786         params.put(CreateTestParam.INC_TEAR_DOWN,
787                    Boolean.valueOf(settings.isGenerateTearDown()));
788         
789         return params;
790     }
791     
792     /**
793      *
794      */

795     static String JavaDoc getPackageName(String JavaDoc fullName) {
796         int i = fullName.lastIndexOf('.');
797         return (i != -1) ? fullName.substring(0, i)
798                          : ""; //NOI18N
799
}
800
801     /**
802      * Gets the last part of a fully qualified Java name.
803      */

804     static String JavaDoc getSimpleName(String JavaDoc fullName) {
805         int lastDotIndex = fullName.lastIndexOf('.');
806         return (lastDotIndex == -1) ? fullName
807                                     : fullName.substring(lastDotIndex + 1);
808     }
809     
810 }
811
Popular Tags