Source Code Cross Referenced for JavaProjectHelper.java in  » IDE-Eclipse » jdt » org » eclipse » jdt » testplugin » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » IDE Eclipse » jdt » org.eclipse.jdt.testplugin 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*******************************************************************************
002:         * Copyright (c) 2000, 2007 IBM Corporation and others.
003:         * All rights reserved. This program and the accompanying materials
004:         * are made available under the terms of the Eclipse Public License v1.0
005:         * which accompanies this distribution, and is available at
006:         * http://www.eclipse.org/legal/epl-v10.html
007:         *
008:         * Contributors:
009:         *     IBM Corporation - initial API and implementation
010:         *******************************************************************************/package org.eclipse.jdt.testplugin;
011:
012:        import java.io.File;
013:        import java.io.FileInputStream;
014:        import java.io.IOException;
015:        import java.io.InputStream;
016:        import java.lang.reflect.InvocationTargetException;
017:        import java.net.URL;
018:        import java.util.ArrayList;
019:        import java.util.Enumeration;
020:        import java.util.Map;
021:        import java.util.zip.ZipFile;
022:
023:        import junit.framework.Assert;
024:
025:        import org.eclipse.core.runtime.CoreException;
026:        import org.eclipse.core.runtime.IPath;
027:        import org.eclipse.core.runtime.IProgressMonitor;
028:        import org.eclipse.core.runtime.Path;
029:
030:        import org.eclipse.core.resources.IContainer;
031:        import org.eclipse.core.resources.IFile;
032:        import org.eclipse.core.resources.IFolder;
033:        import org.eclipse.core.resources.IProject;
034:        import org.eclipse.core.resources.IProjectDescription;
035:        import org.eclipse.core.resources.IResource;
036:        import org.eclipse.core.resources.IWorkspace;
037:        import org.eclipse.core.resources.IWorkspaceDescription;
038:        import org.eclipse.core.resources.IWorkspaceRoot;
039:        import org.eclipse.core.resources.IWorkspaceRunnable;
040:        import org.eclipse.core.resources.ResourcesPlugin;
041:
042:        import org.eclipse.ui.dialogs.IOverwriteQuery;
043:        import org.eclipse.ui.wizards.datatransfer.ImportOperation;
044:        import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider;
045:
046:        import org.eclipse.jdt.core.IClasspathEntry;
047:        import org.eclipse.jdt.core.IJavaElement;
048:        import org.eclipse.jdt.core.IJavaProject;
049:        import org.eclipse.jdt.core.IPackageFragmentRoot;
050:        import org.eclipse.jdt.core.JavaCore;
051:        import org.eclipse.jdt.core.JavaModelException;
052:        import org.eclipse.jdt.core.search.IJavaSearchConstants;
053:        import org.eclipse.jdt.core.search.SearchEngine;
054:        import org.eclipse.jdt.core.search.SearchPattern;
055:        import org.eclipse.jdt.core.search.TypeNameRequestor;
056:
057:        import org.eclipse.jdt.internal.ui.JavaPlugin;
058:        import org.eclipse.jdt.internal.ui.util.CoreUtility;
059:
060:        /**
061:         * Helper methods to set up a IJavaProject.
062:         */
063:        public class JavaProjectHelper {
064:
065:            /**
066:             * @deprecated
067:             * @see #RT_STUBS_15
068:             */
069:            public static final IPath RT_STUBS_13 = new Path(
070:                    "testresources/rtstubs.jar");
071:            /**
072:             * @deprecated
073:             * @see #JUNIT_SRC_381
074:             */
075:            public static final IPath JUNIT_SRC = new Path(
076:                    "testresources/junit37-noUI-src.zip");
077:
078:            public static final IPath RT_STUBS_15 = new Path(
079:                    "testresources/rtstubs15.jar");
080:            public static final IPath JUNIT_SRC_381 = new Path(
081:                    "testresources/junit381-noUI-src.zip");
082:            public static final String JUNIT_SRC_ENCODING = "ISO-8859-1";
083:
084:            public static final IPath MYLIB = new Path(
085:                    "testresources/mylib.jar");
086:            public static final IPath NLS_LIB = new Path(
087:                    "testresources/nls.jar");
088:
089:            private static final int MAX_RETRY = 5;
090:
091:            public static final int COUNT_CLASSES_RT_STUBS_15 = 661;
092:            public static final int COUNT_INTERFACES_RT_STUBS_15 = 135;
093:
094:            public static final int COUNT_CLASSES_JUNIT_SRC_381 = 76;
095:            public static final int COUNT_INTERFACES_JUNIT_SRC_381 = 8;
096:            public static final int COUNT_CLASSES_MYLIB = 3;
097:
098:            /**
099:             * If set to <code>true</code> all resources that are
100:             * deleted using {@link #delete(IJavaElement)} and that contain mixed
101:             * line delimiters will result in a test failure.
102:             * <p>
103:             * Should be <code>false</code> during normal and Releng test runs
104:             * due to performance impact and because the search plug-in gets
105:             * loaded which results in a test failure.
106:             * </p>
107:             */
108:            private static final boolean ASSERT_NO_MIXED_LINE_DELIMIERS = false;
109:
110:            /**
111:             * Creates a IJavaProject.
112:             * @param projectName The name of the project
113:             * @param binFolderName Name of the output folder
114:             * @return Returns the Java project handle
115:             * @throws CoreException Project creation failed
116:             */
117:            public static IJavaProject createJavaProject(String projectName,
118:                    String binFolderName) throws CoreException {
119:                IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
120:                IProject project = root.getProject(projectName);
121:                if (!project.exists()) {
122:                    project.create(null);
123:                } else {
124:                    project.refreshLocal(IResource.DEPTH_INFINITE, null);
125:                }
126:
127:                if (!project.isOpen()) {
128:                    project.open(null);
129:                }
130:
131:                IPath outputLocation;
132:                if (binFolderName != null && binFolderName.length() > 0) {
133:                    IFolder binFolder = project.getFolder(binFolderName);
134:                    if (!binFolder.exists()) {
135:                        CoreUtility.createFolder(binFolder, false, true, null);
136:                    }
137:                    outputLocation = binFolder.getFullPath();
138:                } else {
139:                    outputLocation = project.getFullPath();
140:                }
141:
142:                if (!project.hasNature(JavaCore.NATURE_ID)) {
143:                    addNatureToProject(project, JavaCore.NATURE_ID, null);
144:                }
145:
146:                IJavaProject jproject = JavaCore.create(project);
147:
148:                jproject.setOutputLocation(outputLocation, null);
149:                jproject.setRawClasspath(new IClasspathEntry[0], null);
150:
151:                return jproject;
152:            }
153:
154:            /**
155:             * Creates a Java project with JUnit source and rt.jar from
156:             * {@link #addVariableRTJar(IJavaProject, String, String, String)}.
157:             * 
158:             * @param projectName the project name
159:             * @param srcContainerName the source container name
160:             * @param outputFolderName the output folder name
161:             * @return the IJavaProject
162:             * @throws CoreException
163:             * @throws IOException
164:             * @throws InvocationTargetException
165:             * @since 3.1
166:             */
167:            public static IJavaProject createJavaProjectWithJUnitSource(
168:                    String projectName, String srcContainerName,
169:                    String outputFolderName) throws CoreException, IOException,
170:                    InvocationTargetException {
171:                IJavaProject project = createJavaProject(projectName,
172:                        outputFolderName); //$NON-NLS-2$
173:
174:                IPackageFragmentRoot jdk = JavaProjectHelper.addVariableRTJar(
175:                        project, "JRE_LIB_TEST", null, null);//$NON-NLS-1$
176:                Assert.assertNotNull(jdk);
177:
178:                File junitSrcArchive = JavaTestPlugin.getDefault()
179:                        .getFileInPlugin(JUNIT_SRC_381);
180:                Assert.assertTrue(junitSrcArchive != null
181:                        && junitSrcArchive.exists());
182:
183:                JavaProjectHelper.addSourceContainerWithImport(project,
184:                        srcContainerName, junitSrcArchive, JUNIT_SRC_ENCODING);
185:
186:                return project;
187:            }
188:
189:            /**
190:             * Sets the compiler options to 1.5 for the given project.
191:             * @param project the java project
192:             */
193:            public static void set15CompilerOptions(IJavaProject project) {
194:                Map options = project.getOptions(false);
195:                JavaProjectHelper.set15CompilerOptions(options);
196:                project.setOptions(options);
197:            }
198:
199:            /**
200:             * Sets the compiler options to 1.4 for the given project.
201:             * @param project the java project
202:             */
203:            public static void set14CompilerOptions(IJavaProject project) {
204:                Map options = project.getOptions(false);
205:                JavaProjectHelper.set14CompilerOptions(options);
206:                project.setOptions(options);
207:            }
208:
209:            /**
210:             * Sets the compiler options to 1.5
211:             * @param options The compiler options to configure
212:             */
213:            public static void set15CompilerOptions(Map options) {
214:                options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_5);
215:                options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER,
216:                        JavaCore.ERROR);
217:                options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER,
218:                        JavaCore.ERROR);
219:                options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_5);
220:                options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
221:                        JavaCore.VERSION_1_5);
222:            }
223:
224:            /**
225:             * Sets the compiler options to 1.4
226:             * @param options The compiler options to configure
227:             */
228:            public static void set14CompilerOptions(Map options) {
229:                options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_4);
230:                options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER,
231:                        JavaCore.ERROR);
232:                options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER,
233:                        JavaCore.WARNING);
234:                options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
235:                options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
236:                        JavaCore.VERSION_1_2);
237:            }
238:
239:            /**
240:             * Sets the compiler options to 1.3
241:             * @param options The compiler options to configure
242:             */
243:            public static void set13CompilerOptions(Map options) {
244:                options.put(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_3);
245:                options.put(JavaCore.COMPILER_PB_ASSERT_IDENTIFIER,
246:                        JavaCore.WARNING);
247:                options.put(JavaCore.COMPILER_PB_ENUM_IDENTIFIER,
248:                        JavaCore.WARNING);
249:                options.put(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_3);
250:                options.put(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
251:                        JavaCore.VERSION_1_2);
252:            }
253:
254:            /**
255:             * Removes a IJavaElement
256:             * 
257:             * @param elem The element to remove
258:             * @throws CoreException Removing failed
259:             * @see #ASSERT_NO_MIXED_LINE_DELIMIERS
260:             */
261:            public static void delete(final IJavaElement elem)
262:                    throws CoreException {
263:                if (ASSERT_NO_MIXED_LINE_DELIMIERS)
264:                    MixedLineDelimiterDetector
265:                            .assertNoMixedLineDelimiters(elem);
266:
267:                IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
268:                    public void run(IProgressMonitor monitor)
269:                            throws CoreException {
270:                        performDummySearch();
271:                        if (elem instanceof  IJavaProject) {
272:                            IJavaProject jproject = (IJavaProject) elem;
273:                            jproject.setRawClasspath(new IClasspathEntry[0],
274:                                    jproject.getProject().getFullPath(), null);
275:                        }
276:                        for (int i = 0; i < MAX_RETRY; i++) {
277:                            try {
278:                                elem.getResource().delete(true, null);
279:                                i = MAX_RETRY;
280:                            } catch (CoreException e) {
281:                                if (i == MAX_RETRY - 1) {
282:                                    JavaPlugin.log(e);
283:                                    throw e;
284:                                }
285:                                try {
286:                                    Thread.sleep(1000); // sleep a second
287:                                } catch (InterruptedException e1) {
288:                                }
289:                            }
290:                        }
291:                    }
292:                };
293:                ResourcesPlugin.getWorkspace().run(runnable, null);
294:
295:            }
296:
297:            /**
298:             * Removes all files in the project and sets the given classpath
299:             * @param jproject The project to clear
300:             * @param entries The default class path to set
301:             * @throws CoreException Clearing the project failed
302:             */
303:            public static void clear(final IJavaProject jproject,
304:                    final IClasspathEntry[] entries) throws CoreException {
305:                performDummySearch();
306:
307:                IWorkspaceRunnable runnable = new IWorkspaceRunnable() {
308:                    public void run(IProgressMonitor monitor)
309:                            throws CoreException {
310:                        jproject.setRawClasspath(entries, null);
311:
312:                        IResource[] resources = jproject.getProject().members();
313:                        for (int i = 0; i < resources.length; i++) {
314:                            if (!resources[i].getName().startsWith(".")) {
315:                                resources[i].delete(true, null);
316:                            }
317:                        }
318:                    }
319:                };
320:                ResourcesPlugin.getWorkspace().run(runnable, null);
321:            }
322:
323:            public static void performDummySearch() throws JavaModelException {
324:                new SearchEngine().searchAllTypeNames(
325:                        null,
326:                        SearchPattern.R_EXACT_MATCH,
327:                        "XXXXXXXXX".toCharArray(), // make sure we search a concrete name. This is faster according to Kent 
328:                        SearchPattern.R_EXACT_MATCH
329:                                | SearchPattern.R_CASE_SENSITIVE,
330:                        IJavaSearchConstants.CLASS, SearchEngine
331:                                .createJavaSearchScope(new IJavaElement[0]),
332:                        new Requestor(),
333:                        IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
334:            }
335:
336:            /**
337:             * Adds a source container to a IJavaProject.
338:             * @param jproject The parent project
339:             * @param containerName The name of the new source container
340:             * @return The handle to the new source container
341:             * @throws CoreException Creation failed
342:             */
343:            public static IPackageFragmentRoot addSourceContainer(
344:                    IJavaProject jproject, String containerName)
345:                    throws CoreException {
346:                return addSourceContainer(jproject, containerName, new Path[0]);
347:            }
348:
349:            /**
350:             * Adds a source container to a IJavaProject.
351:             * @param jproject The parent project
352:             * @param containerName The name of the new source container
353:             * @param exclusionFilters Exclusion filters to set
354:             * @return The handle to the new source container
355:             * @throws CoreException Creation failed
356:             */
357:            public static IPackageFragmentRoot addSourceContainer(
358:                    IJavaProject jproject, String containerName,
359:                    IPath[] exclusionFilters) throws CoreException {
360:                return addSourceContainer(jproject, containerName, new Path[0],
361:                        exclusionFilters);
362:            }
363:
364:            /**
365:             * Adds a source container to a IJavaProject.
366:             * @param jproject The parent project
367:             * @param containerName The name of the new source container
368:             * @param inclusionFilters Inclusion filters to set
369:             * @param exclusionFilters Exclusion filters to set
370:             * @return The handle to the new source container
371:             * @throws CoreException Creation failed
372:             */
373:            public static IPackageFragmentRoot addSourceContainer(
374:                    IJavaProject jproject, String containerName,
375:                    IPath[] inclusionFilters, IPath[] exclusionFilters)
376:                    throws CoreException {
377:                IProject project = jproject.getProject();
378:                IContainer container = null;
379:                if (containerName == null || containerName.length() == 0) {
380:                    container = project;
381:                } else {
382:                    IFolder folder = project.getFolder(containerName);
383:                    if (!folder.exists()) {
384:                        CoreUtility.createFolder(folder, false, true, null);
385:                    }
386:                    container = folder;
387:                }
388:                IPackageFragmentRoot root = jproject
389:                        .getPackageFragmentRoot(container);
390:
391:                IClasspathEntry cpe = JavaCore.newSourceEntry(root.getPath(),
392:                        inclusionFilters, exclusionFilters, null);
393:                addToClasspath(jproject, cpe);
394:                return root;
395:            }
396:
397:            /**
398:             * Adds a source container to a IJavaProject and imports all files contained
399:             * in the given ZIP file.
400:             * @param jproject The parent project
401:             * @param containerName Name of the source container
402:             * @param zipFile Archive to import
403:             * @param containerEncoding encoding for the generated source container
404:             * @return The handle to the new source container
405:             * @throws InvocationTargetException Creation failed
406:             * @throws CoreException Creation failed
407:             * @throws IOException Creation failed
408:             */
409:            public static IPackageFragmentRoot addSourceContainerWithImport(
410:                    IJavaProject jproject, String containerName, File zipFile,
411:                    String containerEncoding) throws InvocationTargetException,
412:                    CoreException, IOException {
413:                return addSourceContainerWithImport(jproject, containerName,
414:                        zipFile, containerEncoding, new Path[0]);
415:            }
416:
417:            /**
418:             * Adds a source container to a IJavaProject and imports all files contained
419:             * in the given ZIP file.
420:             * @param jproject The parent project
421:             * @param containerName Name of the source container
422:             * @param zipFile Archive to import
423:             * @param containerEncoding encoding for the generated source container
424:             * @param exclusionFilters Exclusion filters to set
425:             * @return The handle to the new source container
426:             * @throws InvocationTargetException Creation failed
427:             * @throws CoreException Creation failed
428:             * @throws IOException Creation failed
429:             */
430:            public static IPackageFragmentRoot addSourceContainerWithImport(
431:                    IJavaProject jproject, String containerName, File zipFile,
432:                    String containerEncoding, IPath[] exclusionFilters)
433:                    throws InvocationTargetException, CoreException,
434:                    IOException {
435:                ZipFile file = new ZipFile(zipFile);
436:                try {
437:                    IPackageFragmentRoot root = addSourceContainer(jproject,
438:                            containerName, exclusionFilters);
439:                    ((IContainer) root.getCorrespondingResource())
440:                            .setDefaultCharset(containerEncoding, null);
441:                    importFilesFromZip(file, root.getPath(), null);
442:                    return root;
443:                } finally {
444:                    if (file != null) {
445:                        file.close();
446:                    }
447:                }
448:            }
449:
450:            /**
451:             * Removes a source folder from a IJavaProject.
452:             * @param jproject The parent project
453:             * @param containerName Name of the source folder to remove
454:             * @throws CoreException Remove failed
455:             */
456:            public static void removeSourceContainer(IJavaProject jproject,
457:                    String containerName) throws CoreException {
458:                IFolder folder = jproject.getProject().getFolder(containerName);
459:                removeFromClasspath(jproject, folder.getFullPath());
460:                folder.delete(true, null);
461:            }
462:
463:            /**
464:             * Adds a library entry to a IJavaProject.
465:             * @param jproject The parent project
466:             * @param path The path of the library to add
467:             * @return The handle of the created root
468:             * @throws JavaModelException 
469:             */
470:            public static IPackageFragmentRoot addLibrary(
471:                    IJavaProject jproject, IPath path)
472:                    throws JavaModelException {
473:                return addLibrary(jproject, path, null, null);
474:            }
475:
476:            /**
477:             * Adds a library entry with source attachment to a IJavaProject.
478:             * @param jproject The parent project
479:             * @param path The path of the library to add
480:             * @param sourceAttachPath The source attachment path
481:             * @param sourceAttachRoot The source attachment root path
482:             * @return The handle of the created root
483:             * @throws JavaModelException 
484:             */
485:            public static IPackageFragmentRoot addLibrary(
486:                    IJavaProject jproject, IPath path, IPath sourceAttachPath,
487:                    IPath sourceAttachRoot) throws JavaModelException {
488:                IClasspathEntry cpe = JavaCore.newLibraryEntry(path,
489:                        sourceAttachPath, sourceAttachRoot);
490:                addToClasspath(jproject, cpe);
491:                return jproject.getPackageFragmentRoot(path.toString());
492:            }
493:
494:            /**
495:             * Copies the library into the project and adds it as library entry.
496:             * @param jproject The parent project
497:             * @param jarPath 
498:             * @param sourceAttachPath The source attachment path
499:             * @param sourceAttachRoot The source attachment root path
500:             * @return The handle of the created root
501:             * @throws IOException 
502:             * @throws CoreException 
503:             */
504:            public static IPackageFragmentRoot addLibraryWithImport(
505:                    IJavaProject jproject, IPath jarPath,
506:                    IPath sourceAttachPath, IPath sourceAttachRoot)
507:                    throws IOException, CoreException {
508:                IProject project = jproject.getProject();
509:                IFile newFile = project.getFile(jarPath.lastSegment());
510:                InputStream inputStream = null;
511:                try {
512:                    inputStream = new FileInputStream(jarPath.toFile());
513:                    newFile.create(inputStream, true, null);
514:                } finally {
515:                    if (inputStream != null) {
516:                        try {
517:                            inputStream.close();
518:                        } catch (IOException e) {
519:                        }
520:                    }
521:                }
522:                return addLibrary(jproject, newFile.getFullPath(),
523:                        sourceAttachPath, sourceAttachRoot);
524:            }
525:
526:            /**
527:             * Creates and adds a class folder to the class path.
528:             * @param jproject The parent project
529:             * @param containerName 
530:             * @param sourceAttachPath The source attachment path
531:             * @param sourceAttachRoot The source attachment root path
532:             * @return The handle of the created root
533:             * @throws CoreException 
534:             */
535:            public static IPackageFragmentRoot addClassFolder(
536:                    IJavaProject jproject, String containerName,
537:                    IPath sourceAttachPath, IPath sourceAttachRoot)
538:                    throws CoreException {
539:                IProject project = jproject.getProject();
540:                IContainer container = null;
541:                if (containerName == null || containerName.length() == 0) {
542:                    container = project;
543:                } else {
544:                    IFolder folder = project.getFolder(containerName);
545:                    if (!folder.exists()) {
546:                        CoreUtility.createFolder(folder, false, true, null);
547:                    }
548:                    container = folder;
549:                }
550:                IClasspathEntry cpe = JavaCore.newLibraryEntry(container
551:                        .getFullPath(), sourceAttachPath, sourceAttachRoot);
552:                addToClasspath(jproject, cpe);
553:                return jproject.getPackageFragmentRoot(container);
554:            }
555:
556:            /**
557:             * Creates and adds a class folder to the class path and imports all files
558:             * contained in the given ZIP file.
559:             * @param jproject The parent project
560:             * @param containerName 
561:             * @param sourceAttachPath The source attachment path
562:             * @param sourceAttachRoot The source attachment root path
563:             * @param zipFile 
564:             * @return The handle of the created root
565:             * @throws IOException 
566:             * @throws CoreException 
567:             * @throws InvocationTargetException 
568:             */
569:            public static IPackageFragmentRoot addClassFolderWithImport(
570:                    IJavaProject jproject, String containerName,
571:                    IPath sourceAttachPath, IPath sourceAttachRoot, File zipFile)
572:                    throws IOException, CoreException,
573:                    InvocationTargetException {
574:                ZipFile file = new ZipFile(zipFile);
575:                try {
576:                    IPackageFragmentRoot root = addClassFolder(jproject,
577:                            containerName, sourceAttachPath, sourceAttachRoot);
578:                    importFilesFromZip(file, root.getPath(), null);
579:                    return root;
580:                } finally {
581:                    if (file != null) {
582:                        file.close();
583:                    }
584:                }
585:            }
586:
587:            /**
588:             * Adds a library entry pointing to a JRE (stubs only)
589:             * and sets the right compiler options.
590:             * <p>Currently, the compiler compliance level is 1.5.
591:             * 
592:             * @param jproject target
593:             * @return the new package fragment root
594:             * @throws CoreException
595:             */
596:            public static IPackageFragmentRoot addRTJar(IJavaProject jproject)
597:                    throws CoreException {
598:                IPath[] rtJarPath = findRtJar(RT_STUBS_15);
599:                set15CompilerOptions(jproject);
600:                return addLibrary(jproject, rtJarPath[0], rtJarPath[1],
601:                        rtJarPath[2]);
602:            }
603:
604:            public static IPackageFragmentRoot addRTJar13(IJavaProject jproject)
605:                    throws CoreException {
606:                IPath[] rtJarPath = findRtJar(RT_STUBS_13);
607:
608:                Map options = jproject.getOptions(false);
609:                JavaProjectHelper.set13CompilerOptions(options);
610:                jproject.setOptions(options);
611:
612:                return addLibrary(jproject, rtJarPath[0], rtJarPath[1],
613:                        rtJarPath[2]);
614:            }
615:
616:            /**
617:             * Adds a variable entry with source attachment to a IJavaProject.
618:             * Can return null if variable can not be resolved.
619:             * @param jproject The parent project
620:             * @param path The variable path
621:             * @param sourceAttachPath The source attachment path (variable path)
622:             * @param sourceAttachRoot The source attachment root path (variable path)
623:             * @return The added package fragment root
624:             * @throws JavaModelException 
625:             */
626:            public static IPackageFragmentRoot addVariableEntry(
627:                    IJavaProject jproject, IPath path, IPath sourceAttachPath,
628:                    IPath sourceAttachRoot) throws JavaModelException {
629:                IClasspathEntry cpe = JavaCore.newVariableEntry(path,
630:                        sourceAttachPath, sourceAttachRoot);
631:                addToClasspath(jproject, cpe);
632:                IPath resolvedPath = JavaCore.getResolvedVariablePath(path);
633:                if (resolvedPath != null) {
634:                    return jproject.getPackageFragmentRoot(resolvedPath
635:                            .toString());
636:                }
637:                return null;
638:            }
639:
640:            public static IPackageFragmentRoot addVariableRTJar13(
641:                    IJavaProject jproject, String libVarName,
642:                    String srcVarName, String srcrootVarName)
643:                    throws CoreException {
644:                return addVariableRTJar(jproject, RT_STUBS_13, libVarName,
645:                        srcVarName, srcrootVarName);
646:            }
647:
648:            /**
649:             * Adds a variable entry pointing to a current JRE (stubs only)
650:             * and sets the compiler compliance level on the project accordingly.
651:             * The arguments specify the names of the variables to be used.
652:             * Currently, the compiler compliance level is set to 1.5.
653:             * 
654:             * @param jproject the project to add the variable RT JAR
655:             * @param libVarName Name of the variable for the library
656:             * @param srcVarName Name of the variable for the source attachment. Can be <code>null</code>.
657:             * @param srcrootVarName name of the variable for the source attachment root. Can be <code>null</code>.
658:             * @return the new package fragment root
659:             * @throws CoreException Creation failed
660:             */
661:            public static IPackageFragmentRoot addVariableRTJar(
662:                    IJavaProject jproject, String libVarName,
663:                    String srcVarName, String srcrootVarName)
664:                    throws CoreException {
665:                return addVariableRTJar(jproject, RT_STUBS_15, libVarName,
666:                        srcVarName, srcrootVarName);
667:            }
668:
669:            /**
670:             * Adds a variable entry pointing to a current JRE (stubs only).
671:             * The arguments specify the names of the variables to be used.
672:             * Clients must not forget to set the right compiler compliance level on the project.
673:             * 
674:             * @param jproject the project to add the variable RT JAR
675:             * @param rtStubsPath path to an rt.jar
676:             * @param libVarName name of the variable for the library
677:             * @param srcVarName Name of the variable for the source attachment. Can be <code>null</code>.
678:             * @param srcrootVarName Name of the variable for the source attachment root. Can be <code>null</code>.
679:             * @return the new package fragment root
680:             * @throws CoreException Creation failed
681:             */
682:            private static IPackageFragmentRoot addVariableRTJar(
683:                    IJavaProject jproject, IPath rtStubsPath,
684:                    String libVarName, String srcVarName, String srcrootVarName)
685:                    throws CoreException {
686:                IPath[] rtJarPaths = findRtJar(rtStubsPath);
687:                IPath libVarPath = new Path(libVarName);
688:                IPath srcVarPath = null;
689:                IPath srcrootVarPath = null;
690:                JavaCore.setClasspathVariable(libVarName, rtJarPaths[0], null);
691:                if (srcVarName != null) {
692:                    IPath varValue = rtJarPaths[1] != null ? rtJarPaths[1]
693:                            : Path.EMPTY;
694:                    JavaCore.setClasspathVariable(srcVarName, varValue, null);
695:                    srcVarPath = new Path(srcVarName);
696:                }
697:                if (srcrootVarName != null) {
698:                    IPath varValue = rtJarPaths[2] != null ? rtJarPaths[2]
699:                            : Path.EMPTY;
700:                    JavaCore.setClasspathVariable(srcrootVarName, varValue,
701:                            null);
702:                    srcrootVarPath = new Path(srcrootVarName);
703:                }
704:                return addVariableEntry(jproject, libVarPath, srcVarPath,
705:                        srcrootVarPath);
706:            }
707:
708:            /**
709:             * Adds a required project entry.
710:             * @param jproject Parent project
711:             * @param required Project to add to the build path
712:             * @throws JavaModelException Creation failed
713:             */
714:            public static void addRequiredProject(IJavaProject jproject,
715:                    IJavaProject required) throws JavaModelException {
716:                IClasspathEntry cpe = JavaCore.newProjectEntry(required
717:                        .getProject().getFullPath());
718:                addToClasspath(jproject, cpe);
719:            }
720:
721:            public static void removeFromClasspath(IJavaProject jproject,
722:                    IPath path) throws JavaModelException {
723:                IClasspathEntry[] oldEntries = jproject.getRawClasspath();
724:                int nEntries = oldEntries.length;
725:                ArrayList list = new ArrayList(nEntries);
726:                for (int i = 0; i < nEntries; i++) {
727:                    IClasspathEntry curr = oldEntries[i];
728:                    if (!path.equals(curr.getPath())) {
729:                        list.add(curr);
730:                    }
731:                }
732:                IClasspathEntry[] newEntries = (IClasspathEntry[]) list
733:                        .toArray(new IClasspathEntry[list.size()]);
734:                jproject.setRawClasspath(newEntries, null);
735:            }
736:
737:            /**
738:             * Sets auto-building state for the test workspace.
739:             * @param state The new auto building state
740:             * @return The previous state
741:             * @throws CoreException Change failed
742:             */
743:            public static boolean setAutoBuilding(boolean state)
744:                    throws CoreException {
745:                // disable auto build
746:                IWorkspace workspace = ResourcesPlugin.getWorkspace();
747:                IWorkspaceDescription desc = workspace.getDescription();
748:                boolean result = desc.isAutoBuilding();
749:                desc.setAutoBuilding(state);
750:                workspace.setDescription(desc);
751:                return result;
752:            }
753:
754:            public static void addToClasspath(IJavaProject jproject,
755:                    IClasspathEntry cpe) throws JavaModelException {
756:                IClasspathEntry[] oldEntries = jproject.getRawClasspath();
757:                for (int i = 0; i < oldEntries.length; i++) {
758:                    if (oldEntries[i].equals(cpe)) {
759:                        return;
760:                    }
761:                }
762:                int nEntries = oldEntries.length;
763:                IClasspathEntry[] newEntries = new IClasspathEntry[nEntries + 1];
764:                System.arraycopy(oldEntries, 0, newEntries, 0, nEntries);
765:                newEntries[nEntries] = cpe;
766:                jproject.setRawClasspath(newEntries, null);
767:            }
768:
769:            /**
770:             * @param rtStubsPath the path to the RT stubs
771:             * @return a rt.jar (stubs only)
772:             * @throws CoreException 
773:             */
774:            public static IPath[] findRtJar(IPath rtStubsPath)
775:                    throws CoreException {
776:                File rtStubs = JavaTestPlugin.getDefault().getFileInPlugin(
777:                        rtStubsPath);
778:                Assert.assertNotNull(rtStubs);
779:                Assert.assertTrue(rtStubs.exists());
780:                return new IPath[] { Path.fromOSString(rtStubs.getPath()),
781:                        null, null };
782:            }
783:
784:            private static void addNatureToProject(IProject proj,
785:                    String natureId, IProgressMonitor monitor)
786:                    throws CoreException {
787:                IProjectDescription description = proj.getDescription();
788:                String[] prevNatures = description.getNatureIds();
789:                String[] newNatures = new String[prevNatures.length + 1];
790:                System.arraycopy(prevNatures, 0, newNatures, 0,
791:                        prevNatures.length);
792:                newNatures[prevNatures.length] = natureId;
793:                description.setNatureIds(newNatures);
794:                proj.setDescription(description, monitor);
795:            }
796:
797:            private static void importFilesFromZip(ZipFile srcZipFile,
798:                    IPath destPath, IProgressMonitor monitor)
799:                    throws InvocationTargetException {
800:                ZipFileStructureProvider structureProvider = new ZipFileStructureProvider(
801:                        srcZipFile);
802:                try {
803:                    ImportOperation op = new ImportOperation(destPath,
804:                            structureProvider.getRoot(), structureProvider,
805:                            new ImportOverwriteQuery());
806:                    op.run(monitor);
807:                } catch (InterruptedException e) {
808:                    // should not happen
809:                }
810:            }
811:
812:            /**
813:             * Imports resources from <code>bundleSourcePath</code> to <code>importTarget</code>.
814:             * 
815:             * @param importTarget the parent container
816:             * @param bundleSourcePath the path to a folder containing resources
817:             * 
818:             * @throws CoreException import failed
819:             * @throws IOException import failed
820:             */
821:            public static void importResources(IContainer importTarget,
822:                    String bundleSourcePath) throws CoreException, IOException {
823:                Enumeration entryPaths = JavaTestPlugin.getDefault()
824:                        .getBundle().getEntryPaths(bundleSourcePath);
825:                while (entryPaths.hasMoreElements()) {
826:                    String path = (String) entryPaths.nextElement();
827:                    IPath name = new Path(path.substring(bundleSourcePath
828:                            .length()));
829:                    if (path.endsWith("/")) {
830:                        IFolder folder = importTarget.getFolder(name);
831:                        folder.create(false, true, null);
832:                        importResources(folder, path);
833:                    } else {
834:                        URL url = JavaTestPlugin.getDefault().getBundle()
835:                                .getEntry(path);
836:                        IFile file = importTarget.getFile(name);
837:                        file.create(url.openStream(), true, null);
838:                    }
839:                }
840:            }
841:
842:            private static class ImportOverwriteQuery implements 
843:                    IOverwriteQuery {
844:                public String queryOverwrite(String file) {
845:                    return ALL;
846:                }
847:            }
848:
849:            private static class Requestor extends TypeNameRequestor {
850:            }
851:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.