1 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 ; 26 import java.util.Collections ; 27 import java.util.logging.Logger ; 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 ; 48 import java.util.Collection ; 49 import java.util.HashMap ; 50 import java.util.List ; 51 import java.util.Map ; 52 import java.util.Set ; 53 import java.util.StringTokenizer ; 54 import java.util.logging.Level ; 55 import javax.lang.model.element.TypeElement; 56 import org.openide.util.Utilities; 57 58 59 65 public class TestUtil { 66 static private final String JAVA_SOURCES_SUFFIX = "java"; 67 private static final String JAVA_MIME_TYPE = "text/x-java"; 69 static private String getTestClassSuffix() { 70 return JUnitSettings.TEST_CLASSNAME_SUFFIX; 71 } 72 73 static private String getTestClassPrefix() { 74 return JUnitSettings.TEST_CLASSNAME_PREFIX; 75 } 76 77 static private String getTestSuiteSuffix() { 78 return JUnitSettings.SUITE_CLASSNAME_SUFFIX; 79 } 80 81 static private String getTestSuitePrefix() { 82 return JUnitSettings.SUITE_CLASSNAME_PREFIX; 83 } 84 85 static private String getRootSuiteName() { 86 return JUnitSettings.getDefault().getRootSuiteClassName(); 87 } 88 89 public static String getTestClassFullName(String sourceClassName, String packageName) { 93 String shortTestClassName = getTestClassName(sourceClassName); 94 return ((packageName == null) || (packageName.length() == 0)) 95 ? shortTestClassName 96 : packageName.replace('.','/') + '/' + shortTestClassName; 97 } 98 99 public static String getTestClassName(String sourceClassName) { 100 return getTestClassPrefix() + sourceClassName + getTestClassSuffix(); 101 } 102 103 104 108 109 115 public static String convertPackage2SuiteName(String packageFileName) { 116 if (packageFileName.length() == 0) { 117 return getRootSuiteName(); 118 } else { 119 int index = packageFileName.lastIndexOf('/'); 120 String 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 136 public static String convertClass2TestName(String classFileName) { 137 int index = classFileName.lastIndexOf('/'); 138 String pkg = index > -1 ? classFileName.substring(0, index) : ""; 139 String 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 150 public static void notifyUser(String msg) { 151 notifyUser(msg, NotifyDescriptor.ERROR_MESSAGE); 152 } 153 154 157 public static void notifyUser(String msg, int messageType) { 158 NotifyDescriptor descr = new NotifyDescriptor.Message(msg, messageType); 159 DialogDisplayer.getDefault().notify(descr); 160 } 161 162 163 164 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 return null; 188 } 189 190 192 static boolean isJavaFile(FileObject fileObj) { 193 return "java".equals(fileObj.getExt()) || "text/x-java".equals(FileUtil.getMIMEType(fileObj)); } 196 197 198 199 static boolean isClassTest(CompilationInfo compilationInfo, 200 TypeElement classElem) { 201 return isClassImplementingTestInterface(compilationInfo, classElem); 202 } 203 204 static boolean isClassImplementingTestInterface( 206 CompilationInfo compilationInfo, 207 TypeElement classElem) { 208 String testIfaceFullName = "junit.framework.Test"; TypeElement testIface = compilationInfo.getElements() 210 .getTypeElement(testIfaceFullName); 211 212 if (testIface == null) { 213 String msg = "junit: TestUtil.isClassImplementingTestInterface(...) " + "could not find TypeElement for " + testIfaceFullName; 216 Logger.getLogger("global").log(Level.WARNING, msg); return false; 218 } 219 220 return compilationInfo.getTypes().isSubtype(classElem.asType(), 221 testIface.asType()); 222 } 223 224 225 226 228 229 static boolean isClassException(CompilationInfo compilationInfo, 230 TypeElement classElem) { 231 String throwableFullName = "java.lang.Throwable"; TypeElement throwable = compilationInfo.getElements() 233 .getTypeElement(throwableFullName); 234 235 if (throwable == null) { 236 String msg = "junit: TestUtil.isClassException(...) " + "could not find TypeElement for " + throwableFullName; 239 Logger.getLogger("global").log(Level.SEVERE, msg); return false; 241 } 242 243 return compilationInfo.getTypes().isSubtype(classElem.asType(), 244 throwable.asType()); 245 } 246 247 248 256 public static ClassTree findMainClass(final CompilationInfo compInfo) { 257 final String className = compInfo.getFileObject().getName(); 258 259 CompilationUnitTree compUnitTree = compInfo.getCompilationUnit(); 260 String 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 281 static String fileToClassName(String fileName) { 282 if (fileName.endsWith(".java")) { return (fileName.substring(0, fileName.length()-5)).replace('/','.'); 284 } else 285 return null; 286 } 287 288 297 public static List <String > getJavaFileNames(FileObject packageFolder, ClassPath classPath) { 298 FileObject[] children = packageFolder.getChildren(); 299 if (children.length == 0) { 300 return Collections.<String >emptyList(); 301 } 302 303 List <String > result = new ArrayList <String >(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 } 321 return result.isEmpty() ? Collections.<String >emptyList() : result; 322 } 323 324 336 351 352 357 static public String createNewName(int i, Set usedNames) { 358 String ret; 359 do { 360 ret = "p" + i++; 361 } while (usedNames.contains(ret)); 362 return ret; 363 } 364 365 386 399 400 417 418 419 436 437 438 439 471 481 486 491 506 public static Object [] getTestTargets(FileObject fileObject) { 507 508 509 final Project project = FileOwnerQuery.getOwner(fileObject); 510 if (project == null) { 511 return new Object [0]; 512 } 513 514 SourceGroup sourceGroupOwner = findSourceGroupOwner(fileObject); 515 if (sourceGroupOwner == null) { 516 return new Object [0]; 517 } 518 519 520 final URL [] rootURLs = UnitTestForSourceQuery.findUnitTests( 521 sourceGroupOwner.getRootFolder()); 522 if (rootURLs.length == 0) { 523 return new Object [0]; 524 } 525 526 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 ( 535 "No FileObject found for the following URL: " + 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 ( 544 "Source root found by FileOwnerQuery points " + "to a different project for the following URL: " + 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 [0]; 557 } 558 sourceRoots = roots; 559 } 560 561 562 final Object [] targets = new Object [sourceRoots.length]; 563 Map <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 582 public static SourceGroup findSourceGroupOwner(FileObject file) { 583 final Project project = FileOwnerQuery.getOwner(file); 584 return findSourceGroupOwner(project, file); 585 } 586 587 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 624 public static Collection <SourceGroup> findSourceGroupOwners( 625 final Project project, 626 final String 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 relativePath = className.replace('.', '/') 634 + ".java"; 636 ArrayList <SourceGroup> result = new ArrayList <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 669 public static <T> T[] skipNulls(final T[] objs, final T[] type) { 670 List <T> resultList = new ArrayList <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 693 public static Map <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 <FileObject,SourceGroup> map; 705 map = new HashMap <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 public static boolean isValidPackageName(String str) { 718 if (str.length() > 0 && str.charAt(0) == '.') { 719 return false; 720 } 721 StringTokenizer tukac = new StringTokenizer (str, "."); 722 while (tukac.hasMoreTokens()) { 723 String 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 735 public static JUnitPlugin getPluginForProject(final Project project) { 736 Object pluginObj = project.getLookup().lookup(JUnitPlugin.class); 737 return (pluginObj != null) ? (JUnitPlugin) pluginObj 738 : new DefaultPlugin(); 739 } 740 741 754 public static Map <CreateTestParam, Object > getSettingsMap( 755 boolean multipleFiles) { 756 final JUnitSettings settings = JUnitSettings.getDefault(); 757 final Map <CreateTestParam, Object > params 758 = new HashMap <CreateTestParam, Object >(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 795 static String getPackageName(String fullName) { 796 int i = fullName.lastIndexOf('.'); 797 return (i != -1) ? fullName.substring(0, i) 798 : ""; } 800 801 804 static String getSimpleName(String fullName) { 805 int lastDotIndex = fullName.lastIndexOf('.'); 806 return (lastDotIndex == -1) ? fullName 807 : fullName.substring(lastDotIndex + 1); 808 } 809 810 } 811 | Popular Tags |