KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > ant > internal > ui > datatransfer > BuildFileCreator


1 /*******************************************************************************
2  * Copyright (c) 2004, 2007 Richard Hoefter and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * Richard Hoefter (richard.hoefter@web.de) - initial API and implementation, bugs 95297, 97051, 128103
10  * IBM Corporation - nlsing and incorporating into Eclipse, bug 108276, bug 124210, bug 161845, bug 177833
11  * Nikolay Metchev (N.Metchev@teamphone.com) - bug 108276
12  *******************************************************************************/

13
14 package org.eclipse.ant.internal.ui.datatransfer;
15
16 import java.io.ByteArrayInputStream JavaDoc;
17 import java.io.File JavaDoc;
18 import java.io.FilenameFilter JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.io.UnsupportedEncodingException JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Arrays JavaDoc;
24 import java.util.Collections JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.LinkedHashMap JavaDoc;
27 import java.util.List JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.Set JavaDoc;
30 import java.util.StringTokenizer JavaDoc;
31 import java.util.TreeMap JavaDoc;
32 import java.util.TreeSet JavaDoc;
33
34 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
35 import javax.xml.parsers.ParserConfigurationException JavaDoc;
36 import javax.xml.transform.TransformerConfigurationException JavaDoc;
37 import javax.xml.transform.TransformerException JavaDoc;
38 import javax.xml.transform.TransformerFactoryConfigurationError JavaDoc;
39
40 import org.eclipse.ant.internal.ui.AntUIPlugin;
41 import org.eclipse.core.resources.IFile;
42 import org.eclipse.core.runtime.CoreException;
43 import org.eclipse.core.runtime.IPath;
44 import org.eclipse.core.runtime.IProgressMonitor;
45 import org.eclipse.core.runtime.Path;
46 import org.eclipse.core.variables.VariablesPlugin;
47 import org.eclipse.debug.core.DebugPlugin;
48 import org.eclipse.debug.core.ILaunchConfiguration;
49 import org.eclipse.debug.core.ILaunchManager;
50 import org.eclipse.jdt.core.IClasspathContainer;
51 import org.eclipse.jdt.core.IClasspathEntry;
52 import org.eclipse.jdt.core.IJavaProject;
53 import org.eclipse.jdt.core.IType;
54 import org.eclipse.jdt.core.JavaCore;
55 import org.eclipse.jdt.core.JavaModelException;
56 import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
57 import org.eclipse.jface.dialogs.MessageDialog;
58 import org.eclipse.swt.widgets.Shell;
59 import org.w3c.dom.Comment JavaDoc;
60 import org.w3c.dom.Document JavaDoc;
61 import org.w3c.dom.Element JavaDoc;
62 import org.w3c.dom.Node JavaDoc;
63 import org.w3c.dom.ProcessingInstruction JavaDoc;
64 import org.xml.sax.SAXException JavaDoc;
65
66 /**
67  * Creates build.xml file.
68  */

69 public class BuildFileCreator
70 {
71     protected static final String JavaDoc IMPORT_BUILDFILE_PROCESSING_TARGET = "eclipse.ant.import"; //$NON-NLS-1$
72
protected static final String JavaDoc WARNING = " WARNING: Eclipse auto-generated file." + ExportUtil.NEWLINE + //$NON-NLS-1$
73
" Any modifications will be overwritten."; //$NON-NLS-1$
74
protected static final String JavaDoc NOTE = " To include a user specific buildfile here, " + //$NON-NLS-1$
75
"simply create one in the same" + ExportUtil.NEWLINE + //$NON-NLS-1$
76
" directory with the processing instruction " + //$NON-NLS-1$
77
"<?" + IMPORT_BUILDFILE_PROCESSING_TARGET + "?>" + ExportUtil.NEWLINE + //$NON-NLS-1$ //$NON-NLS-2$
78
" as the first entry and export the buildfile again. "; //$NON-NLS-1$
79

80     protected static String JavaDoc BUILD_XML = "build.xml"; //$NON-NLS-1$
81
protected static String JavaDoc JUNIT_OUTPUT_DIR = "junit"; //$NON-NLS-1$
82
protected static boolean CHECK_SOURCE_CYCLES = true;
83     protected static boolean CREATE_ECLIPSE_COMPILE_TARGET = true;
84     
85     private Document JavaDoc doc;
86     private Element JavaDoc root;
87     private IJavaProject project;
88     private String JavaDoc projectName;
89     private String JavaDoc projectRoot;
90     private Map JavaDoc variable2valueMap;
91     private Shell shell;
92     private Set JavaDoc visited = new TreeSet JavaDoc(); // record used subclasspaths
93
private Node JavaDoc classpathNode;
94     
95     /**
96      * Constructor. Please prefer {@link #createBuildFiles(Set, Shell, IProgressMonitor)} if
97      * you do not want call the various createXXX() methods yourself.
98      *
99      * @param project create buildfile for this project
100      * @param shell parent instance for dialogs
101      */

102     public BuildFileCreator(IJavaProject project, Shell shell) throws ParserConfigurationException JavaDoc
103     {
104         this.project = project;
105         this.projectName = project.getProject().getName();
106         this.projectRoot = ExportUtil.getProjectRoot(project);
107         this.variable2valueMap = new LinkedHashMap JavaDoc();
108         DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
109         this.doc = dbf.newDocumentBuilder().newDocument();
110         this.shell = shell;
111     }
112       
113     /**
114      * Create buildfile for given projects.
115      *
116      * @param projects create buildfiles for these <code>IJavaProject</code>
117      * objects
118      * @param shell parent instance for dialogs
119      * @return project names for which buildfiles were created
120      * @throws InterruptedException thrown when user cancels task
121      */

122     public static List JavaDoc createBuildFiles(Set JavaDoc projects, Shell shell, IProgressMonitor pm)
123         throws JavaModelException, ParserConfigurationException JavaDoc,
124                TransformerConfigurationException JavaDoc, TransformerException JavaDoc,
125                IOException JavaDoc, CoreException, InterruptedException JavaDoc
126     {
127         List JavaDoc res = new ArrayList JavaDoc();
128         try {
129             createBuildFilesLoop(projects, shell, pm, res);
130         } finally {
131             if (pm != null) {
132                 pm.done();
133             }
134         }
135         return res;
136     }
137
138     private static void createBuildFilesLoop(Set JavaDoc projects, Shell shell, IProgressMonitor pm,
139             List JavaDoc res) throws CoreException, ParserConfigurationException JavaDoc,
140             JavaModelException, TransformerConfigurationException JavaDoc,
141             TransformerFactoryConfigurationError JavaDoc, TransformerException JavaDoc,
142             UnsupportedEncodingException JavaDoc, InterruptedException JavaDoc {
143
144         // determine files to create/change
145
List JavaDoc files = new ArrayList JavaDoc();
146         for (Iterator JavaDoc iter = projects.iterator(); iter.hasNext();)
147         {
148             IJavaProject currentProject = (IJavaProject) iter.next();
149             IFile file = currentProject.getProject().getFile(BuildFileCreator.BUILD_XML);
150             files.add(file);
151         }
152
153         // trigger checkout
154
Set JavaDoc confirmedFiles = ExportUtil.validateEdit(shell, files);
155
156         if (pm != null) {
157             pm.beginTask(DataTransferMessages.AntBuildfileExportPage_0,
158                     confirmedFiles.size());
159         }
160         
161         int i = 0;
162         for (Iterator JavaDoc iter = projects.iterator(); iter.hasNext(); i++)
163         {
164             IJavaProject currentProject = (IJavaProject) iter.next();
165             IFile file = currentProject.getProject().getFile(BuildFileCreator.BUILD_XML);
166             if (! confirmedFiles.contains(file))
167             {
168                 continue;
169             }
170             
171             if (pm != null) {
172                 pm.subTask(currentProject.getProject().getName());
173             }
174             
175             BuildFileCreator instance = new BuildFileCreator(currentProject, shell);
176             instance.createRoot();
177             instance.createImports();
178             EclipseClasspath classpath = new EclipseClasspath(currentProject);
179             if (CHECK_SOURCE_CYCLES) {
180                 SourceAnalyzer.checkCycles(currentProject, classpath, shell);
181             }
182             instance.createClasspaths(classpath);
183             instance.createInit(classpath.srcDirs, classpath.classDirs);
184             instance.createClean(classpath.classDirs);
185             instance.createCleanAll();
186             instance.createBuild(classpath.srcDirs, classpath.classDirs,
187                                  classpath.inclusionLists, classpath.exclusionLists);
188             instance.createBuildRef();
189             if (CREATE_ECLIPSE_COMPILE_TARGET) {
190                 instance.addInitEclipseCompiler();
191                 instance.addBuildEclipse();
192             }
193             instance.createRun();
194             instance.addSubProperties(currentProject, classpath);
195             instance.createProperty();
196
197             // write build file
198
String JavaDoc xml = ExportUtil.toString(instance.doc);
199             InputStream JavaDoc is = new ByteArrayInputStream JavaDoc(xml.getBytes("UTF-8")); //$NON-NLS-1$
200
if (file.exists())
201             {
202                 file.setContents(is, true, true, null);
203             }
204             else
205             {
206                 file.create(is, true, null);
207             }
208
209             if (pm != null) {
210                 pm.worked(1);
211                 if (pm.isCanceled()) {
212                     throw new InterruptedException JavaDoc();
213                 }
214             }
215             res.add(instance.projectName);
216         }
217     }
218
219     /**
220      * Add property tag.
221      */

222     public void createProperty()
223     {
224         // read debug options from Eclipse settings
225
boolean source = JavaCore.GENERATE.equals(project.getOption(JavaCore.COMPILER_SOURCE_FILE_ATTR, true));
226         boolean lines = JavaCore.GENERATE.equals(project.getOption(JavaCore.COMPILER_LINE_NUMBER_ATTR, true));
227         boolean vars = JavaCore.GENERATE.equals(project.getOption(JavaCore.COMPILER_LOCAL_VARIABLE_ATTR, true));
228         
229         List JavaDoc debuglevel = new ArrayList JavaDoc();
230         if (source)
231         {
232             debuglevel.add("source"); //$NON-NLS-1$
233
}
234         if (lines)
235         {
236             debuglevel.add("lines"); //$NON-NLS-1$
237
}
238         if (vars)
239         {
240             debuglevel.add("vars"); //$NON-NLS-1$
241
}
242         if (debuglevel.size() == 0)
243         {
244             debuglevel.add("none"); //$NON-NLS-1$
245
}
246         variable2valueMap.put("debuglevel", ExportUtil.toString(debuglevel, ",")); //$NON-NLS-1$ //$NON-NLS-2$
247

248         // "Generated .class files compatibility"
249
String JavaDoc target = project.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
250         variable2valueMap.put("target", target); //$NON-NLS-1$
251

252         // "Compiler compliance level"
253
//String compliance = project.getOption(JavaCore.COMPILER_COMPLIANCE, true);
254

255         // "Source compatibility"
256
String JavaDoc sourceLevel = project.getOption(JavaCore.COMPILER_SOURCE, true);
257         variable2valueMap.put("source", sourceLevel); //$NON-NLS-1$
258

259         // <property name="x" value="y"/>
260
boolean first = true;
261         Node JavaDoc node = root.getFirstChild();
262         for (Iterator JavaDoc iterator = variable2valueMap.keySet().iterator(); iterator.hasNext();)
263         {
264             String JavaDoc key = (String JavaDoc) iterator.next();
265             String JavaDoc value = (String JavaDoc) variable2valueMap.get(key);
266             Element JavaDoc prop = doc.createElement("property"); //$NON-NLS-1$
267
prop.setAttribute("name", key); //$NON-NLS-1$
268
prop.setAttribute("value", value); //$NON-NLS-1$
269
if (first)
270             {
271                 first = false;
272             }
273             else
274             {
275                 node = node.getNextSibling();
276             }
277             node = root.insertBefore(prop, node);
278         }
279         
280         // <property environment="env"/>
281
Element JavaDoc env = doc.createElement("property"); //$NON-NLS-1$
282
env.setAttribute("environment", "env"); //$NON-NLS-1$ //$NON-NLS-2$
283
root.insertBefore(env, root.getFirstChild());
284     }
285
286     /**
287      * Create project tag.
288      */

289     public void createRoot()
290     {
291         // <project name="hello" default="build" basedir=".">
292
root = doc.createElement("project"); //$NON-NLS-1$
293
root.setAttribute("name" , projectName); //$NON-NLS-1$
294
root.setAttribute("default" , "build"); //$NON-NLS-1$ //$NON-NLS-2$
295
root.setAttribute("basedir" , "."); //$NON-NLS-1$ //$NON-NLS-2$
296
doc.appendChild(root);
297         
298         // <!-- warning -->
299
Comment JavaDoc comment = doc.createComment(WARNING + ExportUtil.NEWLINE + NOTE);
300         doc.insertBefore(comment, root);
301     }
302     
303     /**
304      * Find buildfiles in projectroot directory and automatically import them.
305      */

306     public void createImports()
307     {
308         // <import file="javadoc.xml"/>
309
File JavaDoc dir = new File JavaDoc(projectRoot);
310         FilenameFilter JavaDoc filter = new FilenameFilter JavaDoc()
311         {
312             public boolean accept(File JavaDoc acceptDir, String JavaDoc name)
313             {
314                 return name.endsWith(".xml") && !name.endsWith(BUILD_XML); //$NON-NLS-1$
315
}
316         };
317
318         File JavaDoc[] files = dir.listFiles(filter);
319         if (files == null)
320         {
321             return;
322         }
323         for (int i = 0; i < files.length; i++)
324         {
325             // import file if it is an XML document with marker comment as first
326
// child
327
File JavaDoc file = files[i];
328             Document JavaDoc docCandidate;
329             try {
330                 docCandidate = ExportUtil.parseXmlFile(file);
331                 Node JavaDoc node = docCandidate.getFirstChild();
332                 if (node instanceof ProcessingInstruction JavaDoc &&
333                         IMPORT_BUILDFILE_PROCESSING_TARGET.equals(((ProcessingInstruction JavaDoc) node).getTarget().trim())) {
334                     Element JavaDoc element = doc.createElement("import"); //$NON-NLS-1$
335
element.setAttribute("file", file.getName()); //$NON-NLS-1$
336
root.appendChild(element);
337                 }
338             } catch (ParserConfigurationException JavaDoc e){
339                 AntUIPlugin.log("invalid XML file not imported: " + file.getAbsolutePath(), e); //$NON-NLS-1$
340
} catch (SAXException JavaDoc e) {
341                 AntUIPlugin.log("invalid XML file not imported: " + file.getAbsolutePath(), e); //$NON-NLS-1$
342
} catch (IOException JavaDoc e) {
343                 AntUIPlugin.log("invalid XML file not imported: " + file.getAbsolutePath(), e); //$NON-NLS-1$
344
}
345         }
346     }
347
348     /**
349      * Create classpath tags.
350      */

351     public void createClasspaths(EclipseClasspath classpath) throws JavaModelException
352     {
353         createClasspaths(null, project, classpath);
354     }
355     
356     /**
357      * Create classpath tags. Allows to specify ID.
358      * @param pathId specify id, if null project name is used
359      */

360     public void createClasspaths(String JavaDoc pathId, IJavaProject currentProject, EclipseClasspath classpath)
361         throws JavaModelException
362     {
363         if (currentProject == null)
364         {
365             AntUIPlugin.log("project is not loaded in workspace: " + pathId, null); //$NON-NLS-1$
366
return;
367         }
368         // <path id="hello.classpath">
369
// <pathelement location="${hello.location}/classes"/>
370
// <pathelement location="${hello.location}/x.jar"/>
371
// <path refid="${goodbye.classpath}"/>
372
// </path>
373
Element JavaDoc element = doc.createElement("path"); //$NON-NLS-1$
374
if (pathId == null)
375         {
376             pathId = currentProject.getProject().getName() + ".classpath"; //$NON-NLS-1$
377
}
378         element.setAttribute("id", pathId); //$NON-NLS-1$
379
visited.add(pathId);
380         variable2valueMap.putAll(classpath.variable2valueMap);
381         for (Iterator JavaDoc iter = ExportUtil.removeDuplicates(classpath.rawClassPathEntries).iterator(); iter.hasNext();)
382         {
383             String JavaDoc entry = (String JavaDoc) iter.next();
384             if (EclipseClasspath.isProjectReference(entry))
385             {
386                 Element JavaDoc pathElement = doc.createElement("path"); //$NON-NLS-1$
387
IJavaProject referencedProject = EclipseClasspath.resolveProjectReference(entry);
388                 if (referencedProject == null)
389                 {
390                     AntUIPlugin.log("project is not loaded in workspace: " + pathId, null); //$NON-NLS-1$
391
continue;
392                 }
393                 String JavaDoc refPathId = referencedProject.getProject().getName() + ".classpath"; //$NON-NLS-1$
394
pathElement.setAttribute("refid", refPathId); //$NON-NLS-1$
395
element.appendChild(pathElement);
396                 if (visited.add(refPathId))
397                 {
398                     createClasspaths(null, referencedProject, new EclipseClasspath(referencedProject)); // recursion
399
}
400             }
401             else if (EclipseClasspath.isUserLibraryReference(entry) ||
402                      EclipseClasspath.isUserSystemLibraryReference(entry) ||
403                      EclipseClasspath.isLibraryReference(entry))
404             {
405                 addUserLibrary(element, entry);
406             }
407             else
408             {
409                 // prefix with ${project.location}
410
String JavaDoc prefix = ""; //$NON-NLS-1$
411
if (!entry.startsWith("${") && // no variable ${var}/classes //$NON-NLS-1$
412
!projectName.equals(currentProject.getProject().getName())) // not main project
413
{
414                     String JavaDoc currentProjectRoot= ExportUtil.getProjectRoot(currentProject);
415                     entry= ExportUtil.getRelativePath(entry, currentProjectRoot);
416                     if (!new Path(entry).isAbsolute()) {
417                         prefix = "${" + currentProject.getProject().getName() + ".location}/"; //$NON-NLS-1$ //$NON-NLS-2$
418
}
419                 }
420                 Element JavaDoc pathElement = doc.createElement("pathelement"); //$NON-NLS-1$
421
String JavaDoc path = ExportUtil.getRelativePath(prefix + entry, projectRoot);
422                 pathElement.setAttribute("location", path); //$NON-NLS-1$
423
element.appendChild(pathElement);
424             }
425         }
426         addToClasspathBlock(element);
427     }
428
429     private void addUserLibrary(Element JavaDoc element, String JavaDoc entry)
430     {
431         // add classpath reference
432
Element JavaDoc pathElement = doc.createElement("path"); //$NON-NLS-1$
433
IClasspathContainer container = EclipseClasspath.resolveUserLibraryReference(entry);
434         String JavaDoc name = ExportUtil.removePrefixAndSuffix(entry, "${", "}"); //$NON-NLS-1$ //$NON-NLS-2$
435
pathElement.setAttribute("refid", name); //$NON-NLS-1$
436
if (!EclipseClasspath.isUserSystemLibraryReference(entry))
437         {
438             element.appendChild(pathElement);
439         }
440
441         // add classpath
442
if (visited.add(entry))
443         {
444             Element JavaDoc userElement = doc.createElement("path"); //$NON-NLS-1$
445
userElement.setAttribute("id", name); //$NON-NLS-1$
446
IClasspathEntry entries[] = container.getClasspathEntries();
447             for (int i = 0; i < entries.length; i++)
448             {
449                 String JavaDoc jarFile = entries[i].getPath().toString();
450                 // use ECLIPSE_HOME variable for library jars
451
if (EclipseClasspath.isLibraryReference(entry))
452                 {
453                     IPath home = JavaCore.getClasspathVariable("ECLIPSE_HOME"); //$NON-NLS-1$
454
if (home != null && home.isPrefixOf(entries[i].getPath()))
455                     {
456                         variable2valueMap.put("ECLIPSE_HOME", home.toString()); //$NON-NLS-1$
457
jarFile = "${ECLIPSE_HOME}" + jarFile.substring(home.toString().length()); //$NON-NLS-1$
458
}
459                     else if (! new File JavaDoc(jarFile).exists() &&
460                             jarFile.startsWith('/' + projectName) &&
461                             new File JavaDoc(projectRoot, jarFile.substring(('/' + projectName).length())).exists())
462                     {
463                         // workaround that additional jars are stored with
464
// leading project root in container object, although
465
// they are relative and indeed correctly stored in
466
// build.properties (jars.extra.classpath)
467
jarFile = jarFile.substring(('/' + projectName).length() + 1);
468                     }
469                 }
470                 jarFile = ExportUtil.getRelativePath(jarFile, projectRoot);
471                 Element JavaDoc userPathElement = doc.createElement("pathelement"); //$NON-NLS-1$
472
userPathElement.setAttribute("location", jarFile); //$NON-NLS-1$
473
userElement.appendChild(userPathElement);
474             }
475             addToClasspathBlock(userElement);
476         }
477     }
478
479     private void addToClasspathBlock(Element JavaDoc element)
480     {
481         // remember node to insert all classpaths at same location
482
if (classpathNode == null)
483         {
484             classpathNode = root.appendChild(element);
485         }
486         else
487         {
488             classpathNode = classpathNode.getNextSibling();
489             classpathNode = root.insertBefore(element, classpathNode);
490         }
491     }
492     
493     /**
494      * Add properties of subprojects to internal properties map.
495      */

496     public void addSubProperties(IJavaProject subproject, EclipseClasspath classpath) throws JavaModelException
497     {
498         for (Iterator JavaDoc iterator = ExportUtil.getClasspathProjectsRecursive(subproject).iterator(); iterator.hasNext();)
499         {
500             IJavaProject subProject = (IJavaProject) iterator.next();
501             String JavaDoc location = subProject.getProject().getName() + ".location"; //$NON-NLS-1$
502
// add subproject properties to variable2valueMap
503
String JavaDoc subProjectRoot = ExportUtil.getProjectRoot(subProject);
504             String JavaDoc relativePath = ExportUtil.getRelativePath(subProjectRoot,
505                     projectRoot);
506             variable2valueMap.put(location, relativePath);
507             variable2valueMap.putAll(classpath.variable2valueMap);
508         }
509     }
510
511     /**
512      * Create init target. Creates directories and copies resources.
513      * @param srcDirs source directories to copy resources from
514      * @param classDirs classes directories to copy resources to
515      */

516     public void createInit(List JavaDoc srcDirs, List JavaDoc classDirs)
517     {
518         // <target name="init">
519
// <mkdir dir="classes"/>
520
// </target>
521
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
522
element.setAttribute("name", "init"); //$NON-NLS-1$ //$NON-NLS-2$
523
List JavaDoc classDirsUnique = ExportUtil.removeDuplicates(classDirs);
524         for (Iterator JavaDoc iterator = classDirsUnique.iterator(); iterator.hasNext();)
525         {
526             String JavaDoc classDir = (String JavaDoc) iterator.next();
527             if (!classDir.equals(".") && //$NON-NLS-1$
528
!EclipseClasspath.isReference(classDir))
529             {
530                 Element JavaDoc pathElement = doc.createElement("mkdir"); //$NON-NLS-1$
531
pathElement.setAttribute("dir", classDir); //$NON-NLS-1$
532
element.appendChild(pathElement);
533             }
534         }
535         root.appendChild(element);
536
537         createCopyResources(srcDirs, classDirs, element);
538     }
539
540     private void createCopyResources(List JavaDoc srcDirs, List JavaDoc classDirs, Element JavaDoc element)
541     {
542         // Check filter for copying resources
543
String JavaDoc filter = project.getOption(JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER, true);
544         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(filter, ","); //$NON-NLS-1$
545
List JavaDoc filters = Collections.list(tokenizer);
546         filters.add("*.java"); //$NON-NLS-1$
547

548         // prefix filters with wildcard
549
for (int i = 0; i < filters.size(); i++)
550         {
551             String JavaDoc item = ((String JavaDoc) filters.get(i)).trim();
552             if (item.equals("*")) //$NON-NLS-1$
553
{
554                 // everything is excluded from copying
555
return;
556             }
557             filters.set(i, "**/" + item); //$NON-NLS-1$
558
}
559         
560         // <copy todir="classes" includeemptydirs="false">
561
// <fileset dir="src" excludes="**/*.java"/>
562
// </copy>
563
for (int i = 0; i < srcDirs.size(); i++)
564         {
565             String JavaDoc srcDir = (String JavaDoc) srcDirs.get(i);
566             String JavaDoc classDir = (String JavaDoc) classDirs.get(i);
567             if (! EclipseClasspath.isReference(classDir))
568             {
569                 Element JavaDoc copyElement = doc.createElement("copy"); //$NON-NLS-1$
570
copyElement.setAttribute("todir", classDir); //$NON-NLS-1$
571
copyElement.setAttribute("includeemptydirs", "false"); //$NON-NLS-1$ //$NON-NLS-2$
572
Element JavaDoc filesetElement = doc.createElement("fileset"); //$NON-NLS-1$
573
filesetElement.setAttribute("dir", srcDir); //$NON-NLS-1$
574
filesetElement.setAttribute("excludes", ExportUtil.toString(filters, ", ")); //$NON-NLS-1$ //$NON-NLS-2$
575
copyElement.appendChild(filesetElement);
576                 element.appendChild(copyElement);
577             }
578         }
579     }
580
581     /**
582      * Create clean target.
583      * @param classDirs classes directories to delete
584      */

585     public void createClean(List JavaDoc classDirs)
586     {
587         // <target name="clean">
588
// <delete dir="classes"/>
589
// </target>
590
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
591
element.setAttribute("name", "clean"); //$NON-NLS-1$ //$NON-NLS-2$
592
List JavaDoc classDirUnique = ExportUtil.removeDuplicates(classDirs);
593         for (Iterator JavaDoc iterator = classDirUnique.iterator(); iterator.hasNext();)
594         {
595             String JavaDoc classDir = (String JavaDoc) iterator.next();
596             if (!classDir.equals(".") && //$NON-NLS-1$
597
!EclipseClasspath.isReference(classDir))
598             {
599                 Element JavaDoc deleteElement = doc.createElement("delete"); //$NON-NLS-1$
600
deleteElement.setAttribute("dir", classDir); //$NON-NLS-1$
601
element.appendChild(deleteElement);
602             }
603         }
604         root.appendChild(element);
605
606         // <target name="clean">
607
// <delete>
608
// <fileset dir="." includes="**/*.class"/>
609
// </delete>
610
// </target>
611
if (classDirs.contains(".")) //$NON-NLS-1$
612
{
613             Element JavaDoc deleteElement = doc.createElement("delete"); //$NON-NLS-1$
614
Element JavaDoc filesetElement = doc.createElement("fileset"); //$NON-NLS-1$
615
filesetElement.setAttribute("dir", "."); //$NON-NLS-1$ //$NON-NLS-2$
616
filesetElement.setAttribute("includes", "**/*.class"); //$NON-NLS-1$ //$NON-NLS-2$
617
deleteElement.appendChild(filesetElement);
618             element.appendChild(deleteElement);
619         }
620     }
621     
622     /**
623      * Create cleanall target.
624      */

625     public void createCleanAll() throws JavaModelException
626     {
627         // <target name="cleanall" depends="clean">
628
// <ant antfile="${hello.location}/build.xml" inheritAll="false" target="clean"/>
629
// </target>
630
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
631
element.setAttribute("name", "cleanall"); //$NON-NLS-1$ //$NON-NLS-2$
632
element.setAttribute("depends", "clean"); //$NON-NLS-1$ //$NON-NLS-2$
633
List JavaDoc subProjects = ExportUtil.getClasspathProjectsRecursive(project);
634         for (Iterator JavaDoc iterator = subProjects.iterator(); iterator.hasNext();)
635         {
636             IJavaProject subProject = (IJavaProject) iterator.next();
637             Element JavaDoc antElement = doc.createElement("ant"); //$NON-NLS-1$
638
antElement.setAttribute("antfile", "${" + subProject.getProject().getName() + ".location}/" + BUILD_XML); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
639
antElement.setAttribute("target", "clean"); //$NON-NLS-1$ //$NON-NLS-2$
640
antElement.setAttribute("inheritAll", "false"); //$NON-NLS-1$ //$NON-NLS-2$
641
element.appendChild(antElement);
642         }
643         root.appendChild(element);
644     }
645
646     /**
647      * Create build target.
648      * @param srcDirs source directories of mainproject
649      * @param classDirs class directories of mainproject
650      * @param inclusionLists inclusion filters of mainproject
651      * @param exclusionLists exclusion filters of mainproject
652      */

653     public void createBuild(List JavaDoc srcDirs, List JavaDoc classDirs, List JavaDoc inclusionLists, List JavaDoc exclusionLists) throws JavaModelException
654     {
655         // <target name="build" depends="build-subprojects,build-project"/>
656
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
657
element.setAttribute("name", "build"); //$NON-NLS-1$ //$NON-NLS-2$
658
element.setAttribute("depends", "build-subprojects,build-project"); //$NON-NLS-1$ //$NON-NLS-2$
659
root.appendChild(element);
660         
661         // <target name="build-subprojects">
662
// <ant antfile="${hello.location}/build.xml" inheritAll="false" target="build-project"/>
663
// </target>
664
element = doc.createElement("target"); //$NON-NLS-1$
665
element.setAttribute("name", "build-subprojects"); //$NON-NLS-1$ //$NON-NLS-2$
666
List JavaDoc subProjects = ExportUtil.getClasspathProjectsRecursive(project);
667         for (Iterator JavaDoc iterator = subProjects.iterator(); iterator.hasNext();)
668         {
669             IJavaProject subProject = (IJavaProject) iterator.next();
670             Element JavaDoc antElement = doc.createElement("ant"); //$NON-NLS-1$
671
antElement.setAttribute("antfile", "${" + subProject.getProject().getName() + ".location}/" + BUILD_XML); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
672
antElement.setAttribute("target", "build-project"); //$NON-NLS-1$ //$NON-NLS-2$
673
antElement.setAttribute("inheritAll", "false"); //$NON-NLS-1$ //$NON-NLS-2$
674
if (CREATE_ECLIPSE_COMPILE_TARGET) {
675                 Element JavaDoc propertysetElement = doc.createElement("propertyset"); //$NON-NLS-1$
676
Element JavaDoc propertyrefElement = doc.createElement("propertyref"); //$NON-NLS-1$
677
propertyrefElement.setAttribute("name", "build.compiler"); //$NON-NLS-1$ //$NON-NLS-2$
678
propertysetElement.appendChild(propertyrefElement);
679                 antElement.appendChild(propertysetElement);
680             }
681             element.appendChild(antElement);
682         }
683         root.appendChild(element);
684         
685         // <target name="build-project" depends="init">
686
// <echo message="${ant.project.name}: ${ant.file}"/>
687
// <javac destdir="classes">
688
// <src path="src"/>
689
// <include name=""/>
690
// <exclude name=""/>
691
// <classpath refid="project.classpath"/>
692
// </javac>
693
// </target>
694
element = doc.createElement("target"); //$NON-NLS-1$
695
element.setAttribute("name", "build-project"); //$NON-NLS-1$ //$NON-NLS-2$
696
element.setAttribute("depends", "init"); //$NON-NLS-1$ //$NON-NLS-2$
697
Element JavaDoc echoElement = doc.createElement("echo"); //$NON-NLS-1$
698
echoElement.setAttribute("message", "${ant.project.name}: ${ant.file}"); //$NON-NLS-1$ //$NON-NLS-2$
699
element.appendChild(echoElement);
700         for (int i = 0; i < srcDirs.size(); i++)
701         {
702             String JavaDoc srcDir = (String JavaDoc) srcDirs.get(i);
703             if (!EclipseClasspath.isReference(srcDir))
704             {
705                 String JavaDoc classDir = (String JavaDoc) classDirs.get(i);
706                 List JavaDoc inclusions = (List JavaDoc) inclusionLists.get(i);
707                 List JavaDoc exclusions = (List JavaDoc) exclusionLists.get(i);
708                 Element JavaDoc javacElement = doc.createElement("javac"); //$NON-NLS-1$
709
javacElement.setAttribute("destdir", classDir); //$NON-NLS-1$
710
javacElement.setAttribute("debug", "true"); //$NON-NLS-1$ //$NON-NLS-2$
711
javacElement.setAttribute("debuglevel", "${debuglevel}"); //$NON-NLS-1$ //$NON-NLS-2$
712
javacElement.setAttribute("source", "${source}"); //$NON-NLS-1$ //$NON-NLS-2$
713
javacElement.setAttribute("target", "${target}"); //$NON-NLS-1$ //$NON-NLS-2$
714

715                 Element JavaDoc srcElement = doc.createElement("src"); //$NON-NLS-1$
716
srcElement.setAttribute("path", srcDir); //$NON-NLS-1$
717
javacElement.appendChild(srcElement);
718     
719                 for (Iterator JavaDoc iter = inclusions.iterator(); iter.hasNext();)
720                 {
721                     String JavaDoc inclusion = (String JavaDoc) iter.next();
722                     Element JavaDoc includeElement = doc.createElement("include"); //$NON-NLS-1$
723
includeElement.setAttribute("name", inclusion); //$NON-NLS-1$
724
javacElement.appendChild(includeElement);
725                 }
726                 for (Iterator JavaDoc iter = exclusions.iterator(); iter.hasNext();)
727                 {
728                     String JavaDoc exclusion = (String JavaDoc) iter.next();
729                     Element JavaDoc excludeElement = doc.createElement("exclude"); //$NON-NLS-1$
730
excludeElement.setAttribute("name", exclusion); //$NON-NLS-1$
731
javacElement.appendChild(excludeElement);
732                 }
733                 Element JavaDoc classpathRefElement = doc.createElement("classpath"); //$NON-NLS-1$
734
classpathRefElement.setAttribute("refid", projectName + ".classpath"); //$NON-NLS-1$ //$NON-NLS-2$
735
javacElement.appendChild(classpathRefElement);
736                 element.appendChild(javacElement);
737                 
738                 addCompilerBootClasspath(srcDirs, javacElement);
739             }
740         }
741         root.appendChild(element);
742     }
743     
744     /**
745      * Create target build-refprojects which compiles projects which reference
746      * current project.
747      */

748     private void createBuildRef() throws JavaModelException {
749         
750         Set JavaDoc refProjects = new TreeSet JavaDoc(ExportUtil.getJavaProjectComparator());
751         IJavaProject[] projects = project.getJavaModel().getJavaProjects();
752         for (int i = 0; i < projects.length; i++) {
753             List JavaDoc subProjects = ExportUtil.getClasspathProjects(projects[i]);
754             for (Iterator JavaDoc iter = subProjects.iterator(); iter.hasNext();) {
755                 IJavaProject p = (IJavaProject) iter.next();
756                 if (projectName.equals(p.getProject().getName())) {
757                     refProjects.add(projects[i]);
758                 }
759             }
760         }
761         
762         // <target name="build-refprojects">
763
// <ant antfile="${hello.location}/build.xml" target="clean" inheritAll="false"/>
764
// <ant antfile="${hello.location}/build.xml" target="build" inheritAll="false"/>
765
// </target>
766
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
767
element.setAttribute("name", "build-refprojects"); //$NON-NLS-1$ //$NON-NLS-2$
768
element.setAttribute("description", "Build all projects which " + //$NON-NLS-1$ //$NON-NLS-2$
769
"reference this project. Useful to propagate changes."); //$NON-NLS-1$
770
for (Iterator JavaDoc iter = refProjects.iterator(); iter.hasNext();) {
771             IJavaProject p = (IJavaProject) iter.next();
772             String JavaDoc location = p.getProject().getName() + ".location"; //$NON-NLS-1$
773
String JavaDoc refProjectRoot = ExportUtil.getProjectRoot(p);
774             String JavaDoc relativePath = ExportUtil.getRelativePath(refProjectRoot,
775                     projectRoot);
776             variable2valueMap.put(location, relativePath);
777
778             Element JavaDoc antElement = doc.createElement("ant"); //$NON-NLS-1$
779
antElement.setAttribute("antfile", "${" + p.getProject().getName() + ".location}/" + BUILD_XML); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
780
antElement.setAttribute("target", "clean"); //$NON-NLS-1$ //$NON-NLS-2$
781
antElement.setAttribute("inheritAll", "false"); //$NON-NLS-1$ //$NON-NLS-2$
782
element.appendChild(antElement);
783             
784             antElement = doc.createElement("ant"); //$NON-NLS-1$
785
antElement.setAttribute("antfile", "${" + p.getProject().getName() + ".location}/" + BUILD_XML); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
786
antElement.setAttribute("target", "build"); //$NON-NLS-1$ //$NON-NLS-2$
787
antElement.setAttribute("inheritAll", "false"); //$NON-NLS-1$ //$NON-NLS-2$
788
if (CREATE_ECLIPSE_COMPILE_TARGET) {
789                 Element JavaDoc propertysetElement = doc.createElement("propertyset"); //$NON-NLS-1$
790
Element JavaDoc propertyrefElement = doc.createElement("propertyref"); //$NON-NLS-1$
791
propertyrefElement.setAttribute("name", "build.compiler"); //$NON-NLS-1$ //$NON-NLS-2$
792
propertysetElement.appendChild(propertyrefElement);
793                 antElement.appendChild(propertysetElement);
794             }
795             element.appendChild(antElement);
796         }
797         root.appendChild(element);
798     }
799     
800     /**
801      * Add target to initialize Eclipse compiler. It copies required jars to ant
802      * lib directory.
803      */

804     public void addInitEclipseCompiler()
805     {
806         // use ECLIPSE_HOME classpath variable
807
IPath value = JavaCore.getClasspathVariable("ECLIPSE_HOME"); //$NON-NLS-1$
808
if (value != null) {
809             variable2valueMap.put("ECLIPSE_HOME", ExportUtil.getRelativePath( //$NON-NLS-1$
810
value.toString(), projectRoot));
811         }
812         // <target name="init-eclipse-compiler" description="copy Eclipse compiler jars to ant lib directory">
813
// <property name="ECLIPSE_HOME" value="C:/Programme/eclipse-3.1" />
814
// <copy todir="${ant.library.dir}">
815
// <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar" />
816
// </copy>
817
// <unzip dest="${ant.library.dir}">
818
// <patternset includes="jdtCompilerAdapter.jar" />
819
// <fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar" />
820
// </unzip>
821
// </target>
822
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
823
element.setAttribute("name", "init-eclipse-compiler"); //$NON-NLS-1$ //$NON-NLS-2$
824
element.setAttribute("description", "copy Eclipse compiler jars to ant lib directory"); //$NON-NLS-1$ //$NON-NLS-2$
825
Element JavaDoc copyElement = doc.createElement("copy"); //$NON-NLS-1$
826
copyElement.setAttribute("todir", "${ant.library.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
827
Element JavaDoc filesetElement = doc.createElement("fileset"); //$NON-NLS-1$
828
filesetElement.setAttribute("dir", "${ECLIPSE_HOME}/plugins"); //$NON-NLS-1$ //$NON-NLS-2$
829
filesetElement.setAttribute("includes", "org.eclipse.jdt.core_*.jar"); //$NON-NLS-1$ //$NON-NLS-2$
830
copyElement.appendChild(filesetElement);
831         element.appendChild(copyElement);
832         Element JavaDoc unzipElement = doc.createElement("unzip"); //$NON-NLS-1$
833
unzipElement.setAttribute("dest", "${ant.library.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
834
Element JavaDoc patternsetElement = doc.createElement("patternset"); //$NON-NLS-1$
835
patternsetElement.setAttribute("includes", "jdtCompilerAdapter.jar"); //$NON-NLS-1$ //$NON-NLS-2$
836
unzipElement.appendChild(patternsetElement);
837         unzipElement.appendChild(filesetElement.cloneNode(false));
838         element.appendChild(unzipElement);
839         root.appendChild(element);
840     }
841
842     /**
843      * Add target to compile project using Eclipse compiler.
844      */

845     public void addBuildEclipse()
846     {
847         // <target name="build-eclipse-compiler" description="compile project with Eclipse compiler">
848
// <property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter" />
849
// <antcall target="build" />
850
// </target>
851
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
852
element.setAttribute("name", "build-eclipse-compiler"); //$NON-NLS-1$ //$NON-NLS-2$
853
element.setAttribute("description", "compile project with Eclipse compiler"); //$NON-NLS-1$ //$NON-NLS-2$
854
Element JavaDoc propertyElement = doc.createElement("property"); //$NON-NLS-1$
855
propertyElement.setAttribute("name", "build.compiler"); //$NON-NLS-1$ //$NON-NLS-2$
856
propertyElement.setAttribute("value", "org.eclipse.jdt.core.JDTCompilerAdapter"); //$NON-NLS-1$ //$NON-NLS-2$
857
element.appendChild(propertyElement);
858         Element JavaDoc antcallElement = doc.createElement("antcall"); //$NON-NLS-1$
859
antcallElement.setAttribute("target", "build"); //$NON-NLS-1$ //$NON-NLS-2$
860
element.appendChild(antcallElement);
861         root.appendChild(element);
862     }
863
864     /**
865      * Add add all bootclasspaths in srcDirs to given javacElement.
866      */

867     private void addCompilerBootClasspath(List JavaDoc srcDirs, Element JavaDoc javacElement)
868     {
869         // <bootclasspath>
870
// <path refid="mylib.bootclasspath"/>
871
// </bootclasspath>
872
Element JavaDoc bootclasspathElement = doc.createElement("bootclasspath"); //$NON-NLS-1$
873
boolean bootclasspathUsed = false;
874         for (Iterator JavaDoc iter = srcDirs.iterator(); iter.hasNext();)
875         {
876             String JavaDoc entry = (String JavaDoc) iter.next();
877             if (EclipseClasspath.isUserSystemLibraryReference(entry))
878             {
879                 Element JavaDoc pathElement = doc.createElement("path"); //$NON-NLS-1$
880
pathElement.setAttribute("refid", ExportUtil.removePrefixAndSuffix(entry, "${", "}")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
881
bootclasspathElement.appendChild(pathElement);
882                 bootclasspathUsed = true;
883             }
884         }
885         if (bootclasspathUsed)
886         {
887             javacElement.appendChild(bootclasspathElement);
888         }
889     }
890
891     /**
892      * Add run targets.
893      * @throws CoreException thrown if problem accessing the launch configuration
894      * @throws TransformerFactoryConfigurationError thrown if applet file could not get created
895      * @throws UnsupportedEncodingException thrown if applet file could not get created
896      */

897     public void createRun() throws CoreException, TransformerFactoryConfigurationError JavaDoc, UnsupportedEncodingException JavaDoc
898     {
899         // <target name="run">
900
// <java fork="yes" classname="class" failonerror="true" dir="." newenvironment="true">
901
// <env key="a" value="b"/>
902
// <jvmarg value="-Dx=y"/>
903
// <arg value="arg"/>
904
// <classpath refid="project.classpath"/>
905
// </java>
906
// </target>
907
ILaunchConfiguration[] confs = DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurations();
908         boolean junitUsed = false;
909         for (int i = 0; i < confs.length; i++)
910         {
911             ILaunchConfiguration conf = confs[i];
912             if (!projectName.equals(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""))) //$NON-NLS-1$
913
{
914                 continue;
915             }
916                     
917             if (conf.getType().getIdentifier().equals(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION))
918             {
919                 addJavaApplication(variable2valueMap, conf);
920             }
921             else if (conf.getType().getIdentifier().equals(IJavaLaunchConfigurationConstants.ID_JAVA_APPLET))
922             {
923                 addApplet(variable2valueMap, conf);
924             }
925             else if (conf.getType().getIdentifier().equals("org.eclipse.jdt.junit.launchconfig" /*JUnitLaunchConfiguration.ID_JUNIT_APPLICATION*/)) //$NON-NLS-1$
926
{
927                 addJUnit(variable2valueMap, conf);
928                 junitUsed = true;
929             }
930         }
931         
932         if (junitUsed)
933         {
934             addJUnitReport();
935         }
936     }
937
938     /**
939      * Convert Java application launch configuration to ant target and add it to a document.
940      * @param variable2value adds Eclipse variables to this map,
941      * if run configuration makes use of this feature
942      * @param conf Java application launch configuration
943      */

944     public void addJavaApplication(Map JavaDoc variable2value, ILaunchConfiguration conf) throws CoreException
945     {
946         Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
947
element.setAttribute("name", conf.getName()); //$NON-NLS-1$
948
Element JavaDoc javaElement = doc.createElement("java"); //$NON-NLS-1$
949
javaElement.setAttribute("fork", "yes"); //$NON-NLS-1$ //$NON-NLS-2$
950
javaElement.setAttribute("classname", conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, "")); //$NON-NLS-1$ //$NON-NLS-2$
951
javaElement.setAttribute("failonerror", "true"); //$NON-NLS-1$ //$NON-NLS-2$
952
String JavaDoc dir = conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, ""); //$NON-NLS-1$
953
ExportUtil.addVariable(variable2value, dir, projectRoot);
954         if (!dir.equals("")) //$NON-NLS-1$
955
{
956             javaElement.setAttribute("dir", ExportUtil.getRelativePath(dir, projectRoot)); //$NON-NLS-1$
957
}
958         if (!conf.getAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true))
959         {
960             javaElement.setAttribute("newenvironment", "true"); //$NON-NLS-1$ //$NON-NLS-2$
961
}
962         Map JavaDoc props = conf.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, new TreeMap JavaDoc());
963         addElements(props, doc, javaElement, "env", "key", "value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
964
addElement(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, ""), doc, javaElement, "jvmarg", "line", variable2value, projectRoot); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
965
addElement(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, ""), doc, javaElement, "arg", "line", variable2value, projectRoot); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
966
element.appendChild(javaElement);
967         
968         addRuntimeClasspath(conf, javaElement);
969         addRuntimeBootClasspath(conf, javaElement);
970         root.appendChild(element);
971     }
972
973     /**
974      * Convert applet launch configuration to Ant target and add it to a document.
975      * @param variable2value adds Eclipse variables to this map,
976      * if run configuration makes use of this feature
977      * @param conf applet configuration
978      * @throws CoreException thrown if problem dealing with launch configuration or underlying resources
979      * @throws TransformerFactoryConfigurationError thrown if applet file could not get created
980      * @throws UnsupportedEncodingException thrown if applet file could not get created
981      */

982     public void addApplet(Map JavaDoc variable2value, ILaunchConfiguration conf) throws CoreException, TransformerFactoryConfigurationError JavaDoc, UnsupportedEncodingException JavaDoc
983     {
984         String JavaDoc dir = conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, ""); //$NON-NLS-1$
985
if (dir.equals("")) //$NON-NLS-1$
986
{
987             dir = projectRoot;
988         }
989         ExportUtil.addVariable(variable2value, dir, projectRoot);
990         String JavaDoc value;
991         try
992         {
993             value = VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(dir);
994         }
995         catch (CoreException e)
996         {
997             // cannot resolve variable
998
value = null;
999         }
1000
1001        String JavaDoc htmlfile = ((value != null) ? value : dir) + '/' + conf.getName() + ".html"; //$NON-NLS-1$
1002
// confirm overwrite
1003
if (ExportUtil.existsUserFile(htmlfile) && !MessageDialog.openConfirm(shell, DataTransferMessages.AntBuildfileExportPage_4, DataTransferMessages.AntBuildfileExportPage_4 + ": " + htmlfile)) //$NON-NLS-1$
1004
{
1005            return;
1006        }
1007        IJavaProject javaProject = ExportUtil.getJavaProjectByName(projectName);
1008        IFile file = javaProject.getProject().getFile(conf.getName() + ".html"); //$NON-NLS-1$
1009
if (ExportUtil.validateEdit(shell, file)) // checkout file if required
1010
{
1011            // write build file
1012
String JavaDoc html = AppletUtil.buildHTMLFile(conf);
1013            InputStream JavaDoc is = new ByteArrayInputStream JavaDoc(html.getBytes("UTF-8")); //$NON-NLS-1$
1014
if (file.exists())
1015            {
1016                file.setContents(is, true, true, null);
1017            }
1018            else
1019            {
1020                file.create(is, true, null);
1021            }
1022        }
1023        
1024        Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
1025
element.setAttribute("name", conf.getName()); //$NON-NLS-1$
1026
Element JavaDoc javaElement = doc.createElement("java"); //$NON-NLS-1$
1027
javaElement.setAttribute("fork", "yes"); //$NON-NLS-1$//$NON-NLS-2$
1028
javaElement.setAttribute("classname", conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_APPLET_APPLETVIEWER_CLASS, "sun.applet.AppletViewer")); //$NON-NLS-1$ //$NON-NLS-2$
1029
javaElement.setAttribute("failonerror", "true"); //$NON-NLS-1$ //$NON-NLS-2$
1030
if (value != null)
1031        {
1032            javaElement.setAttribute("dir", ExportUtil.getRelativePath(dir, projectRoot)); //$NON-NLS-1$
1033
}
1034        addElement(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, ""), doc, javaElement, "jvmarg", "line", variable2value, projectRoot); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1035
addElement(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, ""), doc, javaElement, "arg", "line", variable2value, projectRoot); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
1036
addElement(conf.getName() + ".html", doc, javaElement, "arg", "line", variable2value, projectRoot); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1037
element.appendChild(javaElement);
1038        addRuntimeClasspath(conf, javaElement);
1039        addRuntimeBootClasspath(conf, javaElement);
1040        root.appendChild(element);
1041    }
1042    
1043    /**
1044     * Convert JUnit launch configuration to JUnit task and add it to a document.
1045     * @param variable2value adds Eclipse variables to this map,
1046     * if run configuration makes use of this feature
1047     * @param conf applet configuration
1048     */

1049    public void addJUnit(Map JavaDoc variable2value, ILaunchConfiguration conf) throws CoreException
1050    {
1051        // <target name="runtest">
1052
// <mkdir dir="junit"/>
1053
// <junit fork="yes" printsummary="withOutAndErr">
1054
// <formatter type="xml"/>
1055
// <test name="testclass"/>
1056
// <env key="a" value="b"/>
1057
// <jvmarg value="-Dx=y"/>
1058
// <classpath refid="project.classpath"/>
1059
// </junit>
1060
// </target>
1061
String JavaDoc testClass = conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
1062
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
1063
element.setAttribute("name", conf.getName()); //$NON-NLS-1$
1064

1065        Element JavaDoc mkdirElement = doc.createElement("mkdir"); //$NON-NLS-1$
1066
mkdirElement.setAttribute("dir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1067
element.appendChild(mkdirElement);
1068        
1069        Element JavaDoc junitElement = doc.createElement("junit"); //$NON-NLS-1$
1070
junitElement.setAttribute("fork", "yes"); //$NON-NLS-1$ //$NON-NLS-2$
1071
junitElement.setAttribute("printsummary", "withOutAndErr"); //$NON-NLS-1$ //$NON-NLS-2$
1072
String JavaDoc dir = conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY, ""); //$NON-NLS-1$
1073
ExportUtil.addVariable(variable2value, dir, projectRoot);
1074        if (!dir.equals("")) //$NON-NLS-1$
1075
{
1076            junitElement.setAttribute("dir", ExportUtil.getRelativePath(dir, projectRoot)); //$NON-NLS-1$
1077
}
1078        if (!conf.getAttribute(ILaunchManager.ATTR_APPEND_ENVIRONMENT_VARIABLES, true))
1079        {
1080            junitElement.setAttribute("newenvironment", "true"); //$NON-NLS-1$ //$NON-NLS-2$
1081
}
1082        Element JavaDoc formatterElement = doc.createElement("formatter"); //$NON-NLS-1$
1083
formatterElement.setAttribute("type", "xml"); //$NON-NLS-1$//$NON-NLS-2$
1084
junitElement.appendChild(formatterElement);
1085        if (!testClass.equals("")) //$NON-NLS-1$
1086
{
1087            // Case 1: Single JUnit class
1088
Element JavaDoc testElement = doc.createElement("test"); //$NON-NLS-1$
1089
testElement.setAttribute("name", testClass); //$NON-NLS-1$
1090
testElement.setAttribute("todir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1091
junitElement.appendChild(testElement);
1092        }
1093        else
1094        {
1095            // Case 2: Run all tests in project, package or source folder
1096
String JavaDoc container = conf.getAttribute("org.eclipse.jdt.junit.CONTAINER" /*JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR*/, ""); //$NON-NLS-1$ //$NON-NLS-2$
1097
IType[] types = ExportUtil.findTestsInContainer(container);
1098            Set JavaDoc sortedTypes = new TreeSet JavaDoc(ExportUtil.getITypeComparator());
1099            sortedTypes.addAll(Arrays.asList(types));
1100            for (Iterator JavaDoc iter = sortedTypes.iterator(); iter.hasNext();) {
1101                IType type = (IType) iter.next();
1102                Element JavaDoc testElement = doc.createElement("test"); //$NON-NLS-1$
1103
testElement.setAttribute("name", type.getFullyQualifiedName()); //$NON-NLS-1$
1104
testElement.setAttribute("todir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1105
junitElement.appendChild(testElement);
1106            }
1107        }
1108        Map JavaDoc props = conf.getAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES, new TreeMap JavaDoc());
1109        addElements(props, doc, junitElement, "env", "key", "value"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1110
addElement(conf.getAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_ARGUMENTS, ""), doc, junitElement, "jvmarg", "line", variable2value, projectRoot); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
1111
element.appendChild(junitElement);
1112        addRuntimeClasspath(conf, junitElement);
1113        addRuntimeBootClasspath(conf, junitElement);
1114        root.appendChild(element);
1115    }
1116    
1117    /**
1118     * Add junitreport target.
1119     */

1120    public void addJUnitReport()
1121    {
1122        variable2valueMap.put("junit.output.dir", JUNIT_OUTPUT_DIR); //$NON-NLS-1$
1123

1124        // <target name="junitreport">
1125
// <junitreport todir="junit">
1126
// <fileset dir="junit">
1127
// <include name="TEST-*.xml"/>
1128
// </fileset>
1129
// <report format="frames" todir="junit"/>
1130
// </junitreport>
1131
// </target>
1132
Element JavaDoc element = doc.createElement("target"); //$NON-NLS-1$
1133
element.setAttribute("name", "junitreport"); //$NON-NLS-1$ //$NON-NLS-2$
1134
Element JavaDoc junitreport = doc.createElement("junitreport"); //$NON-NLS-1$
1135
junitreport.setAttribute("todir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1136
Element JavaDoc fileset = doc.createElement("fileset"); //$NON-NLS-1$
1137
fileset.setAttribute("dir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1138
junitreport.appendChild(fileset);
1139        Element JavaDoc include = doc.createElement("include"); //$NON-NLS-1$
1140
include.setAttribute("name", "TEST-*.xml"); //$NON-NLS-1$ //$NON-NLS-2$
1141
fileset.appendChild(include);
1142        Element JavaDoc report = doc.createElement("report"); //$NON-NLS-1$
1143
report.setAttribute("format", "frames"); //$NON-NLS-1$ //$NON-NLS-2$
1144
report.setAttribute("todir", "${junit.output.dir}"); //$NON-NLS-1$ //$NON-NLS-2$
1145
junitreport.appendChild(report);
1146        element.appendChild(junitreport);
1147        root.appendChild(element);
1148    }
1149
1150    /**
1151     * Add classpath tag to given javaElement.
1152     */

1153    private void addRuntimeClasspath(ILaunchConfiguration conf, Element JavaDoc javaElement) throws JavaModelException
1154    {
1155        // <classpath refid="hello.classpath"/>
1156
Element JavaDoc classpathRefElement = doc.createElement("classpath"); //$NON-NLS-1$
1157
EclipseClasspath runtimeClasspath = new EclipseClasspath(project, conf, false);
1158        if (ExportUtil.isDefaultClasspath(project, runtimeClasspath))
1159        {
1160            classpathRefElement.setAttribute("refid", projectName + ".classpath"); //$NON-NLS-1$ //$NON-NLS-2$
1161
}
1162        else
1163        {
1164            String JavaDoc pathId = "run." + conf.getName() + ".classpath"; //$NON-NLS-1$ //$NON-NLS-2$
1165
classpathRefElement.setAttribute("refid", pathId); //$NON-NLS-1$
1166
createClasspaths(pathId, project, runtimeClasspath);
1167        }
1168        javaElement.appendChild(classpathRefElement);
1169    }
1170    
1171    /**
1172     * Add bootclasspath tag to given javaElement.
1173     */

1174    private void addRuntimeBootClasspath(ILaunchConfiguration conf, Element JavaDoc javaElement) throws JavaModelException
1175    {
1176        // <bootclasspath>
1177
// <path refid="hello.bootclasspath"/>
1178
// <fileset dir="${java.home}/lib" includes="*.jar"/>
1179
// </bootclasspath>
1180
EclipseClasspath bootClasspath = new EclipseClasspath(project, conf, true);
1181        if (bootClasspath.rawClassPathEntries.size() > 0)
1182        {
1183            String JavaDoc pathId = "run." + conf.getName() + ".bootclasspath"; //$NON-NLS-1$ //$NON-NLS-2$
1184
createClasspaths(pathId, project, bootClasspath);
1185            Element JavaDoc bootclasspath = doc.createElement("bootclasspath"); //$NON-NLS-1$
1186
Element JavaDoc classpathRefElement = doc.createElement("path"); //$NON-NLS-1$
1187
classpathRefElement.setAttribute("refid", pathId); //$NON-NLS-1$
1188
bootclasspath.appendChild(classpathRefElement);
1189            Element JavaDoc jrelib = doc.createElement("fileset"); //$NON-NLS-1$
1190
jrelib.setAttribute("dir", "${java.home}/lib"); //$NON-NLS-1$ //$NON-NLS-2$
1191
jrelib.setAttribute("includes", "*.jar"); //$NON-NLS-1$ //$NON-NLS-2$
1192
bootclasspath.appendChild(jrelib);
1193            javaElement.appendChild(bootclasspath);
1194        }
1195    }
1196
1197    /**
1198     * Create child node from <code>cmdLine</code> and add it to <code>element</code> which is part of
1199     * <code>doc</code>.
1200     *
1201     * @param cmdLineArgs command line arguments, separated with spaces or within double quotes, may also contain Eclipse variables
1202     * @param doc XML document
1203     * @param element node to add child to
1204     * @param elementName name of new child node
1205     * @param attributeName name of attribute for child node
1206     * @param variable2valueMap adds Eclipse variables to this map,
1207     * if command line makes use of this feature
1208     */

1209    private static void addElement(String JavaDoc cmdLineArgs, Document JavaDoc doc,
1210            Element JavaDoc element, String JavaDoc elementName, String JavaDoc attributeName,
1211            Map JavaDoc variable2valueMap, String JavaDoc projectRoot) {
1212
1213        if (cmdLineArgs == null || cmdLineArgs.length() == 0) {
1214            return;
1215        }
1216        ExportUtil.addVariable(variable2valueMap, cmdLineArgs, projectRoot);
1217        Element JavaDoc itemElement = doc.createElement(elementName);
1218        itemElement.setAttribute(attributeName, cmdLineArgs);
1219        element.appendChild(itemElement);
1220    }
1221    
1222    /**
1223     * Create child nodes from string map and add them to <code>element</code> which is part of
1224     * <code>doc</code>.
1225     *
1226     * @param map key/value string pairs
1227     * @param doc XML document
1228     * @param element node to add children to
1229     * @param elementName name of new child node
1230     * @param keyAttributeName name of key attribute
1231     * @param valueAttributeName name of value attribute
1232     */

1233    private static void addElements(Map JavaDoc map, Document JavaDoc doc, Element JavaDoc element, String JavaDoc elementName,
1234                                    String JavaDoc keyAttributeName, String JavaDoc valueAttributeName)
1235    {
1236        for (Iterator JavaDoc iter = map.keySet().iterator(); iter.hasNext();)
1237        {
1238            String JavaDoc key = (String JavaDoc) iter.next();
1239            String JavaDoc value = (String JavaDoc) map.get(key);
1240            Element JavaDoc itemElement = doc.createElement(elementName);
1241            itemElement.setAttribute(keyAttributeName, key);
1242            itemElement.setAttribute(valueAttributeName, value);
1243            element.appendChild(itemElement);
1244        }
1245    }
1246    
1247    /**
1248     * Set config options.
1249     * @param buildfilename name for Ant buildfile
1250     * @param junitdir name of JUnit output directory
1251     * @param checkcycles check project for Ant compatibility
1252     * @param eclipsecompiler generate target for compiling project with Eclipse compiler
1253     */

1254    public static void setOptions(String JavaDoc buildfilename, String JavaDoc junitdir,
1255            boolean checkcycles, boolean eclipsecompiler) {
1256
1257        if (buildfilename.length() > 0) {
1258            BUILD_XML = buildfilename;
1259        }
1260        if (junitdir.length() > 0) {
1261            JUNIT_OUTPUT_DIR = junitdir;
1262        }
1263        CHECK_SOURCE_CYCLES = checkcycles;
1264        CREATE_ECLIPSE_COMPILE_TARGET = eclipsecompiler;
1265    }
1266}
Popular Tags