KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > loskutov > bco > ui > TestJdtUtils


1 package de.loskutov.bco.ui;
2
3 import java.io.File JavaDoc;
4 import java.io.FileOutputStream JavaDoc;
5 import java.io.IOException JavaDoc;
6 import java.net.URL JavaDoc;
7 import java.util.ArrayList JavaDoc;
8 import java.util.HashMap JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
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 JavaDoc EXTERNAL_JAR_DIR_PATH;
53     private IWorkspace workspace;
54     private IWorkspaceRoot root;
55     private IJavaProject project;
56
57     protected abstract String JavaDoc getFieldName() ;
58
59     protected abstract String JavaDoc getJdkVersion();
60
61     protected String JavaDoc getJavaProjectName() {
62         return "TestJdtUtils" + getFieldName();
63     }
64
65     protected void setUp() throws Exception JavaDoc {
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 JavaDoc {
78         deleteProject(project.getProject());
79         super.tearDown();
80     }
81
82
83     protected IJavaProject getJavaProject() {
84         return project;
85     }
86
87     protected ICompilationUnit getCompilationUnit(String JavaDoc cuName)
88         throws JavaModelException {
89
90         ICompilationUnit compilationUnit = getCompilationUnit("src", "inner", cuName);
91         return compilationUnit;
92     }
93
94     /**
95      * Returns the specified compilation unit in the given project, root, and package
96      * fragment or <code>null</code> if it does not exist.
97      */

98     protected ICompilationUnit getCompilationUnit(String JavaDoc rootPath,
99         String JavaDoc packageName, String JavaDoc 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     /**
108      * Returns the specified package fragment in the given project and root, or
109      * <code>null</code> if it does not exist. The rootPath must be specified as a
110      * project relative path. The empty path refers to the default package fragment.
111      */

112     protected IPackageFragment getPackageFragment(String JavaDoc rootPath,
113         String JavaDoc packageName) throws JavaModelException {
114         IPackageFragmentRoot root1 = getPackageFragmentRoot(rootPath);
115         if (root1 == null) {
116             return null;
117         }
118         return root1.getPackageFragment(packageName);
119     }
120
121     /**
122      * Returns the specified package fragment root in the given project, or
123      * <code>null</code> if it does not exist. If relative, the rootPath must be
124      * specified as a project relative path. The empty path refers to the package fragment
125      * root that is the project folder iteslf. If absolute, the rootPath refers to either
126      * an external jar, or a resource internal to the workspace
127      */

128     protected IPackageFragmentRoot getPackageFragmentRoot(String JavaDoc 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                 // external jar
143
root1 = project.getPackageFragmentRoot(rootPath);
144             } else {
145                 // resource in the workspace
146
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 JavaDoc projectName,
167         final String JavaDoc[] sourceFolders, final String JavaDoc[] libraries,
168         final String JavaDoc projectOutput, final String JavaDoc 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                 // create project
175
createProject(projectName);
176
177                 // set java nature
178
addJavaNature(projectName);
179
180                 // create classpath entries
181
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                         // create folder and its parents
193
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                     // create source entry
205
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 JavaDoc lib = libraries[i];
212                     if (lib.startsWith("JCL")) {
213                         // ensure JCL variables are set
214
try {
215                             setUpJCLClasspathVariables(compliance);
216                         } catch (IOException JavaDoc e) {
217                             e.printStackTrace();
218                         }
219                     }
220
221                     if (lib.indexOf(File.separatorChar) == -1
222                         && lib.charAt(0) != '/'
223                         && lib.equals(lib.toUpperCase())) { // all upper case is a var
224
char[][] vars = CharOperation.splitOn(',', lib
225                             .toCharArray());
226                         entries[sourceLength + i] = JavaCore.newVariableEntry(
227                             new Path(new String JavaDoc(vars[0])), vars.length > 1
228                                 ? new Path(new String JavaDoc(vars[1]))
229                                 : null, vars.length > 2
230                                 ? new Path(new String JavaDoc(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                 // create project's output folder
247
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                 // set classpath and output location
256
IJavaProject javaProject = JavaCore.create(project);
257                 javaProject.setRawClasspath(entries, projectPath
258                     .append(outputPath), null);
259
260                 // set compliance level options
261
if ("1.5".equals(compliance)) {
262                     Map JavaDoc options = new HashMap JavaDoc();
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 JavaDoc 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 JavaDoc projectName) throws CoreException {
300         IProject project1 = root.getProject(projectName);
301         IProjectDescription description = project1.getDescription();
302         description.setNatureIds(new String JavaDoc[]{JavaCore.NATURE_ID});
303         project1.setDescription(description, null);
304     }
305
306     protected void deleteProject(IProject project1) throws CoreException {
307         if (project1.exists() && !project1.isOpen()) { // force opening so that project
308
// can be deleted without logging
309
// (see bug 23629)
310
project1.open(null);
311         }
312         project1.delete(true, null);
313     }
314
315
316     protected IJavaProject setUpJavaProject(final String JavaDoc projectName,
317         String JavaDoc compliance) throws CoreException, IOException JavaDoc {
318         // copy files in project from source workspace to target workspace
319
String JavaDoc sourceWorkspacePath = getSourcesPath();
320
321         String JavaDoc targetWorkspacePath = root.getLocation().toFile()
322             .getCanonicalPath();
323         copyDirectory(new File JavaDoc(sourceWorkspacePath), new File JavaDoc(
324             targetWorkspacePath + "/" + projectName, "src"));
325
326         // ensure variables are set
327
setUpJCLClasspathVariables(compliance);
328
329         String JavaDoc sdkLib = "JCL15_LIB";
330         if(!"1.5".equals(compliance)){
331             sdkLib = "JCL_LIB";
332         }
333
334         // create project
335
IJavaProject javaProject = createJavaProject(
336             projectName, new String JavaDoc[]{"src"}, new String JavaDoc[] {sdkLib}, "bin", compliance);
337
338         setUpProjectCompliance(javaProject, compliance);
339         return javaProject;
340     }
341
342     protected void setUpProjectCompliance(IJavaProject javaProject,
343         String JavaDoc compliance) throws JavaModelException, IOException JavaDoc {
344         // Look for version to set and return if that's already done
345
String JavaDoc version = CompilerOptions.VERSION_1_4;
346         String JavaDoc jclLibString = null;
347         String JavaDoc 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         // ensure variables are set
371
setUpJCLClasspathVariables(compliance);
372
373         // set options
374
Map JavaDoc options = new HashMap JavaDoc();
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         // replace JCL_LIB with JCL15_LIB, and JCL_SRC with JCL15_SRC
381
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 JavaDoc compliance) throws JavaModelException, IOException JavaDoc {
397         if ("1.5".equals(compliance)) {
398             if (JavaCore.getClasspathVariable("JCL15_LIB") == null) {
399                 setupExternalJCL("jclMin1.5");
400                 JavaCore.setClasspathVariables(
401                     new String JavaDoc[] {"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 JavaDoc[] {"JCL_LIB", "JCL_SRC", "JCL_SRCROOT"},
410                     new IPath[] {getExternalJCLPath(), null, null},
411                     null);
412             }
413         }
414     }
415
416     /**
417      * Returns the IPath to the external java class library (e.g. jclMin.jar)
418      */

419     protected IPath getExternalJCLPath() {
420         return new Path(getExternalJCLPathString(""));
421     }
422     /**
423      * Returns the IPath to the external java class library (e.g. jclMin.jar)
424      */

425     protected IPath getExternalJCLPath(String JavaDoc compliance) {
426         return new Path(getExternalJCLPathString(compliance));
427     }
428
429     /**
430      * Returns the java.io path to the external java class library (e.g. jclMin.jar)
431      */

432     protected String JavaDoc getExternalJCLPathString(String JavaDoc compliance) {
433         return getExternalPath() + "jclMin" + compliance + ".jar";
434     }
435
436     /**
437      * Check locally for the required JCL files, <jclName>.jar and <jclName>src.zip.
438      * If not available, copy from the project resources.
439      */

440     protected void setupExternalJCL(String JavaDoc jclName) throws IOException JavaDoc {
441         String JavaDoc externalPath = getExternalPath();
442         String JavaDoc separator = java.io.File.separator;
443         String JavaDoc resourceJCLDir = getPluginDirectoryPath() + separator + "test" + separator + "JCL";
444         java.io.File JavaDoc jclDir = new java.io.File JavaDoc(externalPath);
445         java.io.File JavaDoc jclMin =
446             new java.io.File JavaDoc(externalPath + jclName + ".jar");
447         if (!jclDir.exists()) {
448             if (!jclDir.mkdir()) {
449                 //mkdir failed
450
throw new IOException JavaDoc("Could not create the directory " + jclDir);
451             }
452             //copy the file to the JCL directory
453
java.io.File JavaDoc resourceJCLMin =
454                 new java.io.File JavaDoc(resourceJCLDir + separator + jclName + ".jar");
455             copy(resourceJCLMin, jclMin);
456         } else {
457             //check that the file, jclMin.jar present
458
//copy either file that is missing or less recent than the one in workspace
459
java.io.File JavaDoc resourceJCLMin =
460                 new java.io.File JavaDoc(resourceJCLDir + separator + jclName + ".jar");
461             if ((jclMin.lastModified() < resourceJCLMin.lastModified())
462                     || (jclMin.length() != resourceJCLMin.length())) {
463                 copy(resourceJCLMin, jclMin);
464             }
465         }
466     }
467
468     /*
469      * Returns the OS path to the external directory that contains external jar files.
470      * This path ends with a File.separatorChar.
471      */

472     protected String JavaDoc getExternalPath() {
473         if (EXTERNAL_JAR_DIR_PATH == null)
474             try {
475                 String JavaDoc 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 JavaDoc e) {
481                 e.printStackTrace();
482             }
483         return EXTERNAL_JAR_DIR_PATH;
484     }
485
486     /**
487      * Copy the given source directory (and all its contents) to the given target
488      * directory.
489      */

490     protected void copyDirectory(File JavaDoc source, File JavaDoc target) throws IOException JavaDoc {
491         if (!target.exists()) {
492             target.mkdirs();
493         }
494         File JavaDoc[] files = source.listFiles();
495         if (files == null) {
496             return;
497         }
498         for (int i = 0; i < files.length; i++) {
499             File JavaDoc sourceChild = files[i];
500             String JavaDoc name = sourceChild.getName();
501             if (name.equals("CVS") || name.equals("loskutov")) {
502                 continue;
503             }
504             File JavaDoc targetChild = new File JavaDoc(target, name);
505             if (sourceChild.isDirectory()) {
506                 copyDirectory(sourceChild, targetChild);
507             } else {
508                 copy(sourceChild, targetChild);
509             }
510         }
511     }
512
513     /**
514      * Copy file from src (path to the original file) to dest (path to the destination
515      * file).
516      */

517     protected void copy(File JavaDoc src, File JavaDoc dest) throws IOException JavaDoc {
518         // read source bytes
519
byte[] srcBytes = this.read(src);
520
521         // write bytes to dest
522
FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(dest);
523         out.write(srcBytes);
524         out.close();
525     }
526
527     protected byte[] read(java.io.File JavaDoc file) throws java.io.IOException JavaDoc {
528         int fileLength;
529         byte[] fileBytes = new byte[fileLength = (int) file.length()];
530         java.io.FileInputStream JavaDoc stream = new java.io.FileInputStream JavaDoc(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     /**
543      * Returns the OS path to the directory that contains this plugin.
544      */

545     protected String JavaDoc getPluginDirectoryPath() {
546         try {
547             URL JavaDoc platformURL = Platform.getBundle("de.loskutov.BytecodeOutline")
548                 .getEntry("/");
549             return new File JavaDoc(FileLocator.toFileURL(platformURL).getFile())
550                 .getAbsolutePath();
551         } catch (IOException JavaDoc e) {
552             e.printStackTrace();
553         }
554         return null;
555     }
556
557     protected String JavaDoc getSourcesPath() {
558         return getPluginDirectoryPath() + java.io.File.separator + "test";
559     }
560
561     protected IType[] getAllTypes(ICompilationUnit cu) throws JavaModelException {
562         ArrayList JavaDoc list = new ArrayList JavaDoc();
563         collectAllTypes(cu, list);
564         return (IType[])list.toArray(new IType[list.size()]);
565     }
566
567     protected void collectAllTypes(IParent parent, List JavaDoc types) throws JavaModelException {
568         // this call has a (good) side effect that the IParent will be opened
569
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 JavaDoc topClassName) throws JavaModelException {
581         System.out.println("Test with " + topClassName + ".java");
582
583         ICompilationUnit cu = getCompilationUnit(topClassName + ".java");
584         assertNotNull(cu);
585
586         String JavaDoc packagePath = root.getLocation().append(getJavaProjectName()).append(
587             "bin").append("inner").toOSString()
588             + File.separator;
589
590         String JavaDoc 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 JavaDoc constant = (String JavaDoc) field.getConstant();
599             if(constant != null){
600                 constant = constant.substring(1, constant.length() - 1);
601             }
602             String JavaDoc name = JdtUtils.getByteCodePath(type);
603             String JavaDoc 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 JavaDoc {
616         while (true) {
617             synchronized (this) {
618                 wait(50);
619                 while (Display.getDefault().readAndDispatch()) {
620                     // do events
621
}
622             }
623             if (PlatformUI.getWorkbench().isClosing()) {
624                 break;
625             }
626         }
627     }
628 }
629
Popular Tags