1 package de.loskutov.bco.ui; 2 3 import java.io.File ; 4 import java.io.FileOutputStream ; 5 import java.io.IOException ; 6 import java.net.URL ; 7 import java.util.ArrayList ; 8 import java.util.HashMap ; 9 import java.util.List ; 10 import java.util.Map ; 11 12 import junit.framework.TestCase; 13 14 import org.eclipse.core.resources.IContainer; 15 import org.eclipse.core.resources.IFolder; 16 import org.eclipse.core.resources.IProject; 17 import org.eclipse.core.resources.IProjectDescription; 18 import org.eclipse.core.resources.IResource; 19 import org.eclipse.core.resources.IWorkspace; 20 import org.eclipse.core.resources.IWorkspaceRoot; 21 import org.eclipse.core.resources.IWorkspaceRunnable; 22 import org.eclipse.core.resources.IncrementalProjectBuilder; 23 import org.eclipse.core.resources.ResourcesPlugin; 24 import org.eclipse.core.runtime.CoreException; 25 import org.eclipse.core.runtime.FileLocator; 26 import org.eclipse.core.runtime.IPath; 27 import org.eclipse.core.runtime.IProgressMonitor; 28 import org.eclipse.core.runtime.NullProgressMonitor; 29 import org.eclipse.core.runtime.Path; 30 import org.eclipse.core.runtime.Platform; 31 import org.eclipse.jdt.core.IClasspathAttribute; 32 import org.eclipse.jdt.core.IClasspathEntry; 33 import org.eclipse.jdt.core.ICompilationUnit; 34 import org.eclipse.jdt.core.IField; 35 import org.eclipse.jdt.core.IJavaElement; 36 import org.eclipse.jdt.core.IJavaProject; 37 import org.eclipse.jdt.core.IPackageFragment; 38 import org.eclipse.jdt.core.IPackageFragmentRoot; 39 import org.eclipse.jdt.core.IParent; 40 import org.eclipse.jdt.core.IType; 41 import org.eclipse.jdt.core.JavaCore; 42 import org.eclipse.jdt.core.JavaModelException; 43 import org.eclipse.jdt.core.compiler.CharOperation; 44 import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; 45 import org.eclipse.jdt.internal.core.ClasspathEntry; 46 import org.eclipse.swt.widgets.Display; 47 import org.eclipse.ui.PlatformUI; 48 49 public abstract class TestJdtUtils extends TestCase { 50 51 private boolean onlyPrintOutError = false; 52 private static String EXTERNAL_JAR_DIR_PATH; 53 private IWorkspace workspace; 54 private IWorkspaceRoot root; 55 private IJavaProject project; 56 57 protected abstract String getFieldName() ; 58 59 protected abstract String getJdkVersion(); 60 61 protected String getJavaProjectName() { 62 return "TestJdtUtils" + getFieldName(); 63 } 64 65 protected void setUp() throws Exception { 66 super.setUp(); 67 if(project == null){ 68 workspace = ResourcesPlugin.getWorkspace(); 69 root = workspace.getRoot(); 70 project = setUpJavaProject(getJavaProjectName(), getJdkVersion()); 71 project.getProject().build( 72 IncrementalProjectBuilder.FULL_BUILD, new NullProgressMonitor()); 73 project.makeConsistent(null); 74 } 75 } 76 77 protected void tearDown() throws Exception { 78 deleteProject(project.getProject()); 79 super.tearDown(); 80 } 81 82 83 protected IJavaProject getJavaProject() { 84 return project; 85 } 86 87 protected ICompilationUnit getCompilationUnit(String cuName) 88 throws JavaModelException { 89 90 ICompilationUnit compilationUnit = getCompilationUnit("src", "inner", cuName); 91 return compilationUnit; 92 } 93 94 98 protected ICompilationUnit getCompilationUnit(String rootPath, 99 String packageName, String cuName) throws JavaModelException { 100 IPackageFragment pkg = getPackageFragment(rootPath, packageName); 101 if (pkg == null) { 102 return null; 103 } 104 return pkg.getCompilationUnit(cuName); 105 } 106 107 112 protected IPackageFragment getPackageFragment(String rootPath, 113 String packageName) throws JavaModelException { 114 IPackageFragmentRoot root1 = getPackageFragmentRoot(rootPath); 115 if (root1 == null) { 116 return null; 117 } 118 return root1.getPackageFragment(packageName); 119 } 120 121 128 protected IPackageFragmentRoot getPackageFragmentRoot(String rootPath) 129 throws JavaModelException { 130 131 IJavaProject project = getJavaProject(); 132 if (project == null) { 133 return null; 134 } 135 IPath path = new Path(rootPath); 136 if (path.isAbsolute()) { 137 IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace() 138 .getRoot(); 139 IResource resource = workspaceRoot.findMember(path); 140 IPackageFragmentRoot root1; 141 if (resource == null) { 142 root1 = project.getPackageFragmentRoot(rootPath); 144 } else { 145 root1 = project.getPackageFragmentRoot(resource); 147 } 148 return root1; 149 } 150 IPackageFragmentRoot[] roots = project.getPackageFragmentRoots(); 151 if (roots == null || roots.length == 0) { 152 return null; 153 } 154 for (int i = 0; i < roots.length; i++) { 155 IPackageFragmentRoot root1 = roots[i]; 156 if (!root1.isExternal() 157 && root1.getUnderlyingResource().getProjectRelativePath() 158 .equals(path)) { 159 return root1; 160 } 161 } 162 return null; 163 } 164 165 166 protected IJavaProject createJavaProject(final String projectName, 167 final String [] sourceFolders, final String [] libraries, 168 final String projectOutput, final String compliance) 169 throws CoreException { 170 final IJavaProject[] result = new IJavaProject[1]; 171 IWorkspaceRunnable create = new IWorkspaceRunnable() { 172 173 public void run(IProgressMonitor monitor) throws CoreException { 174 createProject(projectName); 176 177 addJavaNature(projectName); 179 180 IProject project = root.getProject(projectName); 182 IPath projectPath = project.getFullPath(); 183 int sourceLength = sourceFolders.length; 184 int libLength = libraries.length; 185 186 IClasspathEntry[] entries = new IClasspathEntry[sourceLength 187 + libLength]; 188 for (int i = 0; i < sourceLength; i++) { 189 IPath sourcePath = new Path(sourceFolders[i]); 190 int segmentCount = sourcePath.segmentCount(); 191 if (segmentCount > 0) { 192 IContainer container = project; 194 for (int j = 0; j < segmentCount; j++) { 195 IFolder folder = container.getFolder(new Path( 196 sourcePath.segment(j))); 197 if (!folder.exists()) { 198 folder.create(true, true, null); 199 } 200 container = folder; 201 } 202 } 203 204 entries[i] = JavaCore.newSourceEntry( 206 projectPath.append(sourcePath), new IPath[0], 207 new IPath[0], null); 208 } 209 210 for (int i = 0; i < libLength; i++) { 211 String lib = libraries[i]; 212 if (lib.startsWith("JCL")) { 213 try { 215 setUpJCLClasspathVariables(compliance); 216 } catch (IOException e) { 217 e.printStackTrace(); 218 } 219 } 220 221 if (lib.indexOf(File.separatorChar) == -1 222 && lib.charAt(0) != '/' 223 && lib.equals(lib.toUpperCase())) { char[][] vars = CharOperation.splitOn(',', lib 225 .toCharArray()); 226 entries[sourceLength + i] = JavaCore.newVariableEntry( 227 new Path(new String (vars[0])), vars.length > 1 228 ? new Path(new String (vars[1])) 229 : null, vars.length > 2 230 ? new Path(new String (vars[2])) 231 : null); 232 } else { 233 IPath libPath = new Path(lib); 234 if (!libPath.isAbsolute() && libPath.segmentCount() > 0 235 && libPath.getFileExtension() == null) { 236 project.getFolder(libPath).create(true, true, null); 237 libPath = projectPath.append(libPath); 238 } 239 entries[sourceLength + i] = JavaCore.newLibraryEntry( 240 libPath, null, null, ClasspathEntry.getAccessRules( 241 new IPath[0], new IPath[0]), 242 new IClasspathAttribute[0], false); 243 } 244 } 245 246 IPath outputPath = new Path(projectOutput); 248 if (outputPath.segmentCount() > 0) { 249 IFolder output = project.getFolder(outputPath); 250 if (!output.exists()) { 251 output.create(true, true, null); 252 } 253 } 254 255 IJavaProject javaProject = JavaCore.create(project); 257 javaProject.setRawClasspath(entries, projectPath 258 .append(outputPath), null); 259 260 if ("1.5".equals(compliance)) { 262 Map options = new HashMap (); 263 options.put( 264 CompilerOptions.OPTION_Compliance, 265 CompilerOptions.VERSION_1_5); 266 options.put( 267 CompilerOptions.OPTION_Source, 268 CompilerOptions.VERSION_1_5); 269 options.put( 270 CompilerOptions.OPTION_TargetPlatform, 271 CompilerOptions.VERSION_1_5); 272 javaProject.setOptions(options); 273 } 274 275 result[0] = javaProject; 276 } 277 }; 278 workspace.run(create, null); 279 return result[0]; 280 } 281 282 protected IProject createProject(final String projectName) 283 throws CoreException { 284 final IProject project1 = root.getProject(projectName); 285 286 deleteProject(project1); 287 288 IWorkspaceRunnable create = new IWorkspaceRunnable() { 289 290 public void run(IProgressMonitor monitor) throws CoreException { 291 project1.create(null); 292 project1.open(null); 293 } 294 }; 295 workspace.run(create, null); 296 return project1; 297 } 298 299 protected void addJavaNature(String projectName) throws CoreException { 300 IProject project1 = root.getProject(projectName); 301 IProjectDescription description = project1.getDescription(); 302 description.setNatureIds(new String []{JavaCore.NATURE_ID}); 303 project1.setDescription(description, null); 304 } 305 306 protected void deleteProject(IProject project1) throws CoreException { 307 if (project1.exists() && !project1.isOpen()) { project1.open(null); 311 } 312 project1.delete(true, null); 313 } 314 315 316 protected IJavaProject setUpJavaProject(final String projectName, 317 String compliance) throws CoreException, IOException { 318 String sourceWorkspacePath = getSourcesPath(); 320 321 String targetWorkspacePath = root.getLocation().toFile() 322 .getCanonicalPath(); 323 copyDirectory(new File (sourceWorkspacePath), new File ( 324 targetWorkspacePath + "/" + projectName, "src")); 325 326 setUpJCLClasspathVariables(compliance); 328 329 String sdkLib = "JCL15_LIB"; 330 if(!"1.5".equals(compliance)){ 331 sdkLib = "JCL_LIB"; 332 } 333 334 IJavaProject javaProject = createJavaProject( 336 projectName, new String []{"src"}, new String [] {sdkLib}, "bin", compliance); 337 338 setUpProjectCompliance(javaProject, compliance); 339 return javaProject; 340 } 341 342 protected void setUpProjectCompliance(IJavaProject javaProject, 343 String compliance) throws JavaModelException, IOException { 344 String version = CompilerOptions.VERSION_1_4; 346 String jclLibString = null; 347 String newJclLibString = null; 348 switch (compliance.charAt(2)) { 349 case '5' : 350 version = CompilerOptions.VERSION_1_5; 351 if (version.equals(javaProject.getOption( 352 CompilerOptions.OPTION_Compliance, false))) { 353 return; 354 } 355 jclLibString = "JCL_LIB"; 356 newJclLibString = "JCL15_LIB"; 357 break; 358 case '3' : 359 version = CompilerOptions.VERSION_1_3; 360 default : 361 if (version.equals(javaProject.getOption( 362 CompilerOptions.OPTION_Compliance, false))) { 363 return; 364 } 365 jclLibString = "JCL15_LIB"; 366 newJclLibString = "JCL_LIB"; 367 break; 368 } 369 370 setUpJCLClasspathVariables(compliance); 372 373 Map options = new HashMap (); 375 options.put(CompilerOptions.OPTION_Compliance, version); 376 options.put(CompilerOptions.OPTION_Source, version); 377 options.put(CompilerOptions.OPTION_TargetPlatform, version); 378 javaProject.setOptions(options); 379 380 IClasspathEntry[] classpath = javaProject.getRawClasspath(); 382 IPath jclLib = new Path(jclLibString); 383 for (int i = 0, length = classpath.length; i < length; i++) { 384 IClasspathEntry entry = classpath[i]; 385 if (entry.getPath().equals(jclLib)) { 386 classpath[i] = JavaCore.newVariableEntry( 387 new Path(newJclLibString), null, entry 388 .getSourceAttachmentRootPath(), entry.getAccessRules(), 389 new IClasspathAttribute[0], entry.isExported()); 390 break; 391 } 392 } 393 javaProject.setRawClasspath(classpath, null); 394 } 395 396 protected void setUpJCLClasspathVariables(String compliance) throws JavaModelException, IOException { 397 if ("1.5".equals(compliance)) { 398 if (JavaCore.getClasspathVariable("JCL15_LIB") == null) { 399 setupExternalJCL("jclMin1.5"); 400 JavaCore.setClasspathVariables( 401 new String [] {"JCL15_LIB", "JCL15_SRC", "JCL_SRCROOT"}, 402 new IPath[] {getExternalJCLPath(compliance), null, null}, 403 null); 404 } 405 } else { 406 if (JavaCore.getClasspathVariable("JCL_LIB") == null) { 407 setupExternalJCL("jclMin"); 408 JavaCore.setClasspathVariables( 409 new String [] {"JCL_LIB", "JCL_SRC", "JCL_SRCROOT"}, 410 new IPath[] {getExternalJCLPath(), null, null}, 411 null); 412 } 413 } 414 } 415 416 419 protected IPath getExternalJCLPath() { 420 return new Path(getExternalJCLPathString("")); 421 } 422 425 protected IPath getExternalJCLPath(String compliance) { 426 return new Path(getExternalJCLPathString(compliance)); 427 } 428 429 432 protected String getExternalJCLPathString(String compliance) { 433 return getExternalPath() + "jclMin" + compliance + ".jar"; 434 } 435 436 440 protected void setupExternalJCL(String jclName) throws IOException { 441 String externalPath = getExternalPath(); 442 String separator = java.io.File.separator; 443 String resourceJCLDir = getPluginDirectoryPath() + separator + "test" + separator + "JCL"; 444 java.io.File jclDir = new java.io.File (externalPath); 445 java.io.File jclMin = 446 new java.io.File (externalPath + jclName + ".jar"); 447 if (!jclDir.exists()) { 448 if (!jclDir.mkdir()) { 449 throw new IOException ("Could not create the directory " + jclDir); 451 } 452 java.io.File resourceJCLMin = 454 new java.io.File (resourceJCLDir + separator + jclName + ".jar"); 455 copy(resourceJCLMin, jclMin); 456 } else { 457 java.io.File resourceJCLMin = 460 new java.io.File (resourceJCLDir + separator + jclName + ".jar"); 461 if ((jclMin.lastModified() < resourceJCLMin.lastModified()) 462 || (jclMin.length() != resourceJCLMin.length())) { 463 copy(resourceJCLMin, jclMin); 464 } 465 } 466 } 467 468 472 protected String getExternalPath() { 473 if (EXTERNAL_JAR_DIR_PATH == null) 474 try { 475 String path = root.getLocation().toFile().getParentFile().getCanonicalPath(); 476 if (path.charAt(path.length()-1) != File.separatorChar) { 477 path += File.separatorChar; 478 } 479 EXTERNAL_JAR_DIR_PATH = path; 480 } catch (IOException e) { 481 e.printStackTrace(); 482 } 483 return EXTERNAL_JAR_DIR_PATH; 484 } 485 486 490 protected void copyDirectory(File source, File target) throws IOException { 491 if (!target.exists()) { 492 target.mkdirs(); 493 } 494 File [] files = source.listFiles(); 495 if (files == null) { 496 return; 497 } 498 for (int i = 0; i < files.length; i++) { 499 File sourceChild = files[i]; 500 String name = sourceChild.getName(); 501 if (name.equals("CVS") || name.equals("loskutov")) { 502 continue; 503 } 504 File targetChild = new File (target, name); 505 if (sourceChild.isDirectory()) { 506 copyDirectory(sourceChild, targetChild); 507 } else { 508 copy(sourceChild, targetChild); 509 } 510 } 511 } 512 513 517 protected void copy(File src, File dest) throws IOException { 518 byte[] srcBytes = this.read(src); 520 521 FileOutputStream out = new FileOutputStream (dest); 523 out.write(srcBytes); 524 out.close(); 525 } 526 527 protected byte[] read(java.io.File file) throws java.io.IOException { 528 int fileLength; 529 byte[] fileBytes = new byte[fileLength = (int) file.length()]; 530 java.io.FileInputStream stream = new java.io.FileInputStream (file); 531 int bytesRead = 0; 532 int lastReadSize = 0; 533 while ((lastReadSize != -1) && (bytesRead != fileLength)) { 534 lastReadSize = stream.read(fileBytes, bytesRead, fileLength 535 - bytesRead); 536 bytesRead += lastReadSize; 537 } 538 stream.close(); 539 return fileBytes; 540 } 541 542 545 protected String getPluginDirectoryPath() { 546 try { 547 URL platformURL = Platform.getBundle("de.loskutov.BytecodeOutline") 548 .getEntry("/"); 549 return new File (FileLocator.toFileURL(platformURL).getFile()) 550 .getAbsolutePath(); 551 } catch (IOException e) { 552 e.printStackTrace(); 553 } 554 return null; 555 } 556 557 protected String getSourcesPath() { 558 return getPluginDirectoryPath() + java.io.File.separator + "test"; 559 } 560 561 protected IType[] getAllTypes(ICompilationUnit cu) throws JavaModelException { 562 ArrayList list = new ArrayList (); 563 collectAllTypes(cu, list); 564 return (IType[])list.toArray(new IType[list.size()]); 565 } 566 567 protected void collectAllTypes(IParent parent, List types) throws JavaModelException { 568 IJavaElement[] children = parent.getChildren(); 570 for (int i = 0; i < children.length; i++) { 571 if(children[i] instanceof IType){ 572 types.add(children[i]); 573 collectAllTypes((IParent) children[i], types); 574 } else if (children[i] instanceof IParent){ 575 collectAllTypes((IParent) children[i], types); 576 } 577 } 578 } 579 580 protected void doTest(String topClassName) throws JavaModelException { 581 System.out.println("Test with " + topClassName + ".java"); 582 583 ICompilationUnit cu = getCompilationUnit(topClassName + ".java"); 584 assertNotNull(cu); 585 586 String packagePath = root.getLocation().append(getJavaProjectName()).append( 587 "bin").append("inner").toOSString() 588 + File.separator; 589 590 String fieldName = getFieldName(); 591 IType[] allTypes = getAllTypes(cu); 592 for (int i = 0; i < allTypes.length; i++) { 593 IType type = allTypes[i]; 594 IField field = type.getField(fieldName); 595 if (field == null) { 596 continue; 597 } 598 String constant = (String ) field.getConstant(); 599 if(constant != null){ 600 constant = constant.substring(1, constant.length() - 1); 601 } 602 String name = JdtUtils.getByteCodePath(type); 603 String expectedPath = packagePath + constant + ".class"; 604 if(!(expectedPath).equals(name)){ 605 System.out.println("Expected/received: \nok -> " + expectedPath + "\nbad -> " + name + "\n"); 606 if(!onlyPrintOutError) { 607 assertEquals(expectedPath, name); 608 } 609 } else { 610 System.out.println("OK: " + name); 611 } 612 } 613 } 614 615 protected void pauseTests() throws InterruptedException { 616 while (true) { 617 synchronized (this) { 618 wait(50); 619 while (Display.getDefault().readAndDispatch()) { 620 } 622 } 623 if (PlatformUI.getWorkbench().isClosing()) { 624 break; 625 } 626 } 627 } 628 } 629 | Popular Tags |