KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > build > builder > ModelBuildScriptGenerator


1 /*******************************************************************************
2  * Copyright (c) 2000, 2007 IBM Corporation 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  * IBM - Initial API and implementation
10  * Prosyst - create proper OSGi bundles (bug 174157)
11  *******************************************************************************/

12 package org.eclipse.pde.internal.build.builder;
13
14 import java.io.*;
15 import java.util.*;
16 import org.eclipse.core.runtime.*;
17 import org.eclipse.osgi.service.resolver.BundleDescription;
18 import org.eclipse.osgi.util.NLS;
19 import org.eclipse.pde.internal.build.*;
20 import org.eclipse.pde.internal.build.ant.*;
21 import org.eclipse.pde.internal.build.builder.ClasspathComputer3_0.ClasspathElement;
22 import org.eclipse.update.core.IPluginEntry;
23
24 /**
25  * Generic class for generating scripts for plug-ins and fragments.
26  */

27 public class ModelBuildScriptGenerator extends AbstractBuildScriptGenerator {
28     private static final String JavaDoc SRC_ZIP = "src.zip"; //$NON-NLS-1$
29
public static final String JavaDoc EXPANDED_DOT = "@dot"; //$NON-NLS-1$
30
public static final String JavaDoc DOT = "."; //$NON-NLS-1$
31

32     /**
33      * Represents a entry that must be compiled and which is listed in the build.properties file.
34      */

35     protected class CompiledEntry {
36         static final byte JAR = 0;
37         static final byte FOLDER = 1;
38         private String JavaDoc name;
39         private String JavaDoc resolvedName;
40         private String JavaDoc[] source;
41         private String JavaDoc[] output;
42         private String JavaDoc[] extraClasspath;
43         private String JavaDoc excludedFromJar;
44         byte type;
45
46         protected CompiledEntry(String JavaDoc entryName, String JavaDoc[] entrySource, String JavaDoc[] entryOutput, String JavaDoc[] entryExtraClasspath, String JavaDoc excludedFromJar, byte entryType) {
47             this.name = entryName;
48             this.source = entrySource;
49             this.output = entryOutput;
50             this.extraClasspath = entryExtraClasspath;
51             this.type = entryType;
52             this.excludedFromJar = excludedFromJar;
53         }
54
55         protected String JavaDoc getName(boolean resolved) {
56             if (!resolved)
57                 return name;
58
59             if (resolvedName == null)
60                 resolvedName = replaceVariables(name, true);
61
62             return resolvedName;
63         }
64
65         protected String JavaDoc[] getSource() {
66             return source;
67         }
68
69         public String JavaDoc[] getOutput() {
70             return output;
71         }
72
73         public String JavaDoc[] getExtraClasspath() {
74             return extraClasspath;
75         }
76
77         public byte getType() {
78             return type;
79         }
80
81         public String JavaDoc getExcludedFromJar() {
82             return excludedFromJar;
83         }
84     }
85
86     /**
87      * Bundle for which we are generating the script.
88      */

89     protected BundleDescription model;
90     /**
91      * PluginEntry corresponding to the bundle
92      */

93     private IPluginEntry associatedEntry;
94
95     protected String JavaDoc fullName;
96     protected String JavaDoc pluginZipDestination;
97     protected String JavaDoc pluginUpdateJarDestination;
98
99     private FeatureBuildScriptGenerator featureGenerator;
100
101     /** constants */
102     protected final String JavaDoc PLUGIN_DESTINATION = Utils.getPropertyFormat(PROPERTY_PLUGIN_DESTINATION);
103
104     private Properties permissionProperties;
105
106     private String JavaDoc propertiesFileName = PROPERTIES_FILE;
107     private String JavaDoc buildScriptFileName = DEFAULT_BUILD_SCRIPT_FILENAME;
108     private String JavaDoc customBuildCallbacks = null;
109     private String JavaDoc customCallbacksBuildpath = null;
110     private String JavaDoc customCallbacksFailOnError = null;
111     private String JavaDoc customCallbacksInheritAll = null;
112     //This list is initialized by the generateBuildJarsTarget
113
private ArrayList compiledJarNames;
114     private boolean dotOnTheClasspath = false;
115     private boolean binaryPlugin = false;
116     private boolean signJars = false;
117
118     /**
119      * @see AbstractScriptGenerator#generate()
120      */

121     public void generate() throws CoreException {
122         //If it is a binary plugin, then we don't generate scripts
123
if (binaryPlugin)
124             return;
125
126         if (model == null) {
127             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_ELEMENT_MISSING, Messages.error_missingElement, null));
128         }
129
130         // If the the plugin we want to generate is a source plugin, and the feature that required the generation of this plugin is not being asked to build the source
131
// we want to leave. This is particularly usefull for the case of the pde.source building (at least for now since the source of pde is not in a feature)
132
if (featureGenerator != null && featureGenerator.isSourceFeatureGeneration() == false && featureGenerator.getBuildProperties().containsKey(GENERATION_SOURCE_PLUGIN_PREFIX + model.getSymbolicName()))
133             return;
134
135         if (!AbstractScriptGenerator.isBuildingOSGi())
136             checkBootAndRuntime();
137
138         initializeVariables();
139         if (BundleHelper.getDefault().isDebugging())
140             System.out.println("Generating plugin " + model.getSymbolicName()); //$NON-NLS-1$
141

142         String JavaDoc custom = (String JavaDoc) getBuildProperties().get(PROPERTY_CUSTOM);
143         if (custom != null && custom.equalsIgnoreCase("true")) { //$NON-NLS-1$
144
updateExistingScript();
145             return;
146         }
147
148         openScript(getLocation(model), buildScriptFileName);
149         try {
150             generateBuildScript();
151         } finally {
152             closeScript();
153         }
154     }
155
156     /**
157      * Check that boot and runtime are available, otherwise throws an exception because the build will fail.
158      */

159     private void checkBootAndRuntime() throws CoreException {
160         if (getSite(false).getRegistry().getResolvedBundle(PI_BOOT) == null) {
161             IStatus status = new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_PLUGIN_MISSING, NLS.bind(Messages.exception_missingPlugin, PI_BOOT), null);
162             throw new CoreException(status);
163         }
164         if (getSite(false).getRegistry().getResolvedBundle(PI_RUNTIME) == null) {
165             IStatus status = new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_PLUGIN_MISSING, NLS.bind(Messages.exception_missingPlugin, PI_RUNTIME), null);
166             throw new CoreException(status);
167         }
168     }
169
170     public static String JavaDoc getNormalizedName(BundleDescription bundle) {
171         return bundle.getSymbolicName() + '_' + bundle.getVersion();
172     }
173
174     private void initializeVariables() throws CoreException {
175         fullName = getNormalizedName(model);
176         pluginZipDestination = PLUGIN_DESTINATION + '/' + fullName + ".zip"; //$NON-NLS-1$
177
pluginUpdateJarDestination = PLUGIN_DESTINATION + '/' + fullName + ".jar"; //$NON-NLS-1$
178
String JavaDoc[] classpathInfo = getClasspathEntries(model);
179         dotOnTheClasspath = specialDotProcessing(getBuildProperties(), classpathInfo);
180
181         //Persist this information for use in the assemble script generation
182
Properties bundleProperties = (Properties) model.getUserObject();
183         bundleProperties.put(WITH_DOT, Boolean.valueOf(dotOnTheClasspath));
184
185         Properties properties = getBuildProperties();
186         customBuildCallbacks = properties.getProperty(PROPERTY_CUSTOM_BUILD_CALLBACKS);
187         if (TRUE.equalsIgnoreCase(customBuildCallbacks))
188             customBuildCallbacks = DEFAULT_CUSTOM_BUILD_CALLBACKS_FILE;
189         else if (FALSE.equalsIgnoreCase(customBuildCallbacks))
190             customBuildCallbacks = null;
191
192         customCallbacksBuildpath = properties.getProperty(PROPERTY_CUSTOM_CALLBACKS_BUILDPATH, "."); //$NON-NLS-1$
193
customCallbacksFailOnError = properties.getProperty(PROPERTY_CUSTOM_CALLBACKS_FAILONERROR, FALSE);
194         customCallbacksInheritAll = properties.getProperty(PROPERTY_CUSTOM_CALLBACKS_INHERITALL);
195     }
196
197     protected static boolean findAndReplaceDot(String JavaDoc[] classpathInfo) {
198         for (int i = 0; i < classpathInfo.length; i++) {
199             if (DOT.equals(classpathInfo[i])) {
200                 classpathInfo[i] = EXPANDED_DOT;
201                 return true;
202             }
203         }
204         return false;
205     }
206
207     public static boolean specialDotProcessing(Properties properties, String JavaDoc[] classpathInfo) {
208         findAndReplaceDot(classpathInfo);
209         String JavaDoc sourceFolder = properties.getProperty(PROPERTY_SOURCE_PREFIX + DOT);
210         if (sourceFolder != null) {
211             properties.setProperty(PROPERTY_SOURCE_PREFIX + EXPANDED_DOT, sourceFolder);
212             properties.remove(PROPERTY_SOURCE_PREFIX + DOT);
213
214             String JavaDoc outputValue = properties.getProperty(PROPERTY_OUTPUT_PREFIX + DOT);
215             if (outputValue != null) {
216                 properties.setProperty(PROPERTY_OUTPUT_PREFIX + EXPANDED_DOT, outputValue);
217                 properties.remove(PROPERTY_OUTPUT_PREFIX + DOT);
218             }
219             String JavaDoc excludedFromJar = properties.getProperty(PROPERTY_EXCLUDE_PREFIX + DOT);
220             if (excludedFromJar != null) {
221                 properties.setProperty(PROPERTY_EXCLUDE_PREFIX + EXPANDED_DOT, excludedFromJar);
222                 properties.remove(PROPERTY_EXCLUDE_PREFIX + DOT);
223             }
224             String JavaDoc buildOrder = properties.getProperty(PROPERTY_JAR_ORDER);
225             if (buildOrder != null) {
226                 String JavaDoc[] order = Utils.getArrayFromString(buildOrder);
227                 for (int i = 0; i < order.length; i++)
228                     if (order[i].equals(DOT))
229                         order[i] = EXPANDED_DOT;
230                 properties.setProperty(PROPERTY_JAR_ORDER, Utils.getStringFromArray(order, ",")); //$NON-NLS-1$
231
}
232
233             String JavaDoc extraEntries = properties.getProperty(PROPERTY_EXTRAPATH_PREFIX + '.');
234             if (extraEntries != null) {
235                 properties.setProperty(PROPERTY_EXTRAPATH_PREFIX + EXPANDED_DOT, extraEntries);
236             }
237
238             String JavaDoc includeString = properties.getProperty(PROPERTY_BIN_INCLUDES);
239             if (includeString != null) {
240                 String JavaDoc[] includes = Utils.getArrayFromString(includeString);
241                 for (int i = 0; i < includes.length; i++)
242                     if (includes[i].equals(DOT))
243                         includes[i] = EXPANDED_DOT + '/';
244                 properties.setProperty(PROPERTY_BIN_INCLUDES, Utils.getStringFromArray(includes, ",")); //$NON-NLS-1$
245
}
246             return true;
247         }
248         return false;
249     }
250
251     /**
252      * Main call for generating the script.
253      *
254      * @throws CoreException
255      */

256     private void generateBuildScript() throws CoreException {
257         generatePrologue();
258         generateBuildUpdateJarTarget();
259
260         if (getBuildProperties().getProperty(SOURCE_PLUGIN, null) == null) {
261             generateBuildJarsTarget(model);
262         } else {
263             generateBuildJarsTargetForSourceGathering();
264             generateEmptyBuildSourcesTarget();
265         }
266         generateGatherBinPartsTarget();
267         generateBuildZipsTarget();
268         generateGatherSourcesTarget();
269         generateGatherLogTarget();
270         generateCleanTarget();
271         generateRefreshTarget();
272         generateZipPluginTarget();
273         generateEpilogue();
274     }
275
276     /**
277      * Method generateEmptyBuildSourceTarget.
278      */

279     private void generateEmptyBuildSourcesTarget() {
280         script.printTargetDeclaration(TARGET_BUILD_SOURCES, null, null, null, null);
281         script.printTargetEnd();
282     }
283
284     /**
285      * Method generateBuildJarsTargetForSourceGathering.
286      */

287     private void generateBuildJarsTargetForSourceGathering() {
288         script.printTargetDeclaration(TARGET_BUILD_JARS, null, null, null, null);
289         compiledJarNames = new ArrayList(0);
290
291         Config configInfo;
292         if (associatedEntry.getOS() == null && associatedEntry.getWS() == null && associatedEntry.getOSArch() == null)
293             configInfo = Config.genericConfig();
294         else
295             configInfo = new Config(associatedEntry.getOS(), associatedEntry.getWS(), associatedEntry.getOSArch());
296
297         Set pluginsToGatherSourceFrom = (Set) featureGenerator.sourceToGather.getElementEntries().get(configInfo);
298         if (pluginsToGatherSourceFrom != null) {
299             for (Iterator iter = pluginsToGatherSourceFrom.iterator(); iter.hasNext();) {
300                 BundleDescription plugin = (BundleDescription) iter.next();
301                 if (plugin.getSymbolicName().equals(model.getSymbolicName())) // We are not trying to gather the source from ourself since we are generated and we know we don't have source...
302
continue;
303
304                 // The two steps are required, because some plugins (xerces, junit, ...) don't build their source: the source already comes zipped
305
IPath location = Utils.makeRelative(new Path(getLocation(plugin)), new Path(getLocation(model)));
306                 script.printAntTask(DEFAULT_BUILD_SCRIPT_FILENAME, location.toOSString(), TARGET_BUILD_SOURCES, null, null, null);
307                 HashMap params = new HashMap(1);
308                 params.put(PROPERTY_DESTINATION_TEMP_FOLDER, Utils.getPropertyFormat(PROPERTY_BASEDIR) + "/src"); //$NON-NLS-1$
309
script.printAntTask(DEFAULT_BUILD_SCRIPT_FILENAME, location.toOSString(), TARGET_GATHER_SOURCES, null, null, params);
310             }
311         }
312         script.printTargetEnd();
313     }
314
315     /**
316      * Add the <code>clean</code> target to the given Ant script.
317      *
318      * @throws CoreException
319      */

320     private void generateCleanTarget() throws CoreException {
321         script.println();
322         Properties properties = getBuildProperties();
323         CompiledEntry[] availableJars = extractEntriesToCompile(properties);
324         script.printTargetDeclaration(TARGET_CLEAN, TARGET_INIT, null, null, NLS.bind(Messages.build_plugin_clean, model.getSymbolicName()));
325
326         Map params = null;
327         if (customBuildCallbacks != null) {
328             params = new HashMap(3);
329             params.put(PROPERTY_PLUGIN_DESTINATION, PLUGIN_DESTINATION);
330             params.put(PROPERTY_TEMP_FOLDER, Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER));
331             params.put(PROPERTY_BUILD_RESULT_FOLDER, Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER));
332             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_CLEAN, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
333         }
334         for (int i = 0; i < availableJars.length; i++) {
335             String JavaDoc jarName = availableJars[i].getName(true);
336             String JavaDoc jarLocation = getJARLocation(jarName);
337             //avoid destructive cleans
338
if (jarLocation.equals("") || jarLocation.startsWith(DOT + DOT) || jarLocation.equals(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER))) //$NON-NLS-1$
339
continue;
340             if (availableJars[i].type == CompiledEntry.JAR) {
341                 script.printDeleteTask(null, jarLocation, null);
342             } else {
343                 script.printDeleteTask(jarLocation, null, null);
344             }
345             script.printDeleteTask(null, getSRCLocation(jarName), null);
346         }
347         script.printDeleteTask(null, pluginUpdateJarDestination, null);
348         script.printDeleteTask(null, pluginZipDestination, null);
349         script.printDeleteTask(Utils.getPropertyFormat(IXMLConstants.PROPERTY_TEMP_FOLDER), null, null);
350
351         if (customBuildCallbacks != null) {
352             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_CLEAN, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
353         }
354         script.printTargetEnd();
355     }
356
357     /**
358      * Add the <code>gather.logs</code> target to the given Ant script.
359      *
360      * @throws CoreException
361      */

362     private void generateGatherLogTarget() throws CoreException {
363         script.println();
364         script.printTargetDeclaration(TARGET_GATHER_LOGS, TARGET_INIT, PROPERTY_DESTINATION_TEMP_FOLDER, null, null);
365         IPath baseDestination = new Path(Utils.getPropertyFormat(PROPERTY_DESTINATION_TEMP_FOLDER));
366         baseDestination = baseDestination.append(fullName);
367         Map params = null;
368         if (customBuildCallbacks != null) {
369             params = new HashMap(1);
370             params.put(PROPERTY_DESTINATION_TEMP_FOLDER, baseDestination.toString());
371             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_GATHER_LOGS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
372         }
373         List destinations = new ArrayList(5);
374         Properties properties = getBuildProperties();
375         CompiledEntry[] availableJars = extractEntriesToCompile(properties);
376         for (int i = 0; i < availableJars.length; i++) {
377             String JavaDoc name = availableJars[i].getName(true);
378             IPath destination = baseDestination.append(name).removeLastSegments(1); // remove the jar name
379
if (!destinations.contains(destination)) {
380                 script.printMkdirTask(destination.toString());
381                 destinations.add(destination);
382             }
383             Path logPath = new Path(getTempJARFolderLocation(name) + Utils.getPropertyFormat(PROPERTY_LOG_EXTENSION));
384             FileSet logSet = new FileSet(logPath.removeLastSegments(1).toString(), null, logPath.lastSegment(), null, null, null, null);
385             script.printCopyTask(null, destination.toString(), new FileSet[] { logSet }, false, false);
386         }
387
388         if (customBuildCallbacks != null) {
389             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_GATHER_LOGS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
390         }
391         script.printTargetEnd();
392     }
393
394     /**
395      *
396      * @param zipName
397      * @param source
398      */

399     private void generateZipIndividualTarget(String JavaDoc zipName, String JavaDoc source) {
400         script.println();
401         script.printTargetDeclaration(zipName, TARGET_INIT, null, null, null);
402         IPath root = new Path(Utils.getPropertyFormat(IXMLConstants.PROPERTY_BASEDIR));
403         script.printZipTask(root.append(zipName).toString(), root.append(source).toString(), false, false, null);
404         script.printTargetEnd();
405     }
406
407     /**
408      * Add the <code>gather.sources</code> target to the given Ant script.
409      *
410      * @throws CoreException
411      */

412     private void generateGatherSourcesTarget() throws CoreException {
413         script.println();
414         script.printTargetDeclaration(TARGET_GATHER_SOURCES, TARGET_INIT, PROPERTY_DESTINATION_TEMP_FOLDER, null, null);
415
416         IPath baseDestination = new Path(Utils.getPropertyFormat(PROPERTY_DESTINATION_TEMP_FOLDER));
417         baseDestination = baseDestination.append(fullName);
418         Map params = null;
419         if (customBuildCallbacks != null) {
420             params = new HashMap(1);
421             params.put(PROPERTY_TARGET_FOLDER, baseDestination.toString());
422             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_GATHER_SOURCES, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
423         }
424         List destinations = new ArrayList(5);
425         Properties properties = getBuildProperties();
426         CompiledEntry[] availableJars = extractEntriesToCompile(properties);
427         for (int i = 0; i < availableJars.length; i++) {
428             String JavaDoc jar = availableJars[i].getName(true);
429             IPath destination = baseDestination.append(jar).removeLastSegments(1); // remove the jar name
430
if (!destinations.contains(destination)) {
431                 script.printMkdirTask(destination.toString());
432                 destinations.add(destination);
433             }
434             script.printCopyTask(getSRCLocation(jar), destination.toString(), null, false, false);
435         }
436         String JavaDoc include = (String JavaDoc) getBuildProperties().get(PROPERTY_SRC_INCLUDES);
437         String JavaDoc exclude = (String JavaDoc) getBuildProperties().get(PROPERTY_SRC_EXCLUDES);
438         if (include != null || exclude != null) {
439             FileSet fileSet = new FileSet(Utils.getPropertyFormat(PROPERTY_BASEDIR), null, include, null, exclude, null, null);
440             script.printCopyTask(null, baseDestination.toString(), new FileSet[] {fileSet}, false, false);
441         }
442
443         if (customBuildCallbacks != null) {
444             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_GATHER_SOURCES, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
445         }
446         script.printTargetEnd();
447     }
448
449     /**
450      * Add the <code>gather.bin.parts</code> target to the given Ant script.
451      *
452      * @throws CoreException
453      */

454     private void generateGatherBinPartsTarget() throws CoreException {
455         script.println();
456         script.printTargetDeclaration(TARGET_GATHER_BIN_PARTS, TARGET_INIT, PROPERTY_DESTINATION_TEMP_FOLDER, null, null);
457         IPath destination = new Path(Utils.getPropertyFormat(PROPERTY_DESTINATION_TEMP_FOLDER));
458         destination = destination.append(fullName);
459         String JavaDoc root = destination.toString();
460         script.printMkdirTask(root);
461
462         Map params = null;
463         if (customBuildCallbacks != null) {
464             params = new HashMap(3);
465             params.put(PROPERTY_TARGET_FOLDER, root);
466             params.put(PROPERTY_BUILD_RESULT_FOLDER, Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER));
467             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_GATHER_BIN_PARTS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
468         }
469
470         List destinations = new ArrayList(5);
471         destinations.add(destination);
472         String JavaDoc include = (String JavaDoc) getBuildProperties().get(PROPERTY_BIN_INCLUDES);
473         String JavaDoc exclude = (String JavaDoc) getBuildProperties().get(PROPERTY_BIN_EXCLUDES);
474
475         //Copy only the jars that has been compiled and are listed in the includes
476
String JavaDoc[] splitIncludes = Utils.getArrayFromString(include);
477         String JavaDoc[] fileSetValues = new String JavaDoc[compiledJarNames.size()];
478         int count = 0;
479
480         boolean dotIncluded = false; //This flag indicates if . should be gathered
481
int pos = Utils.isStringIn(splitIncludes, EXPANDED_DOT + '/');
482         if (pos != -1) {
483             splitIncludes[pos] = null;
484             dotIncluded = true;
485         }
486
487         //Iterate over the classpath
488
for (Iterator iter = compiledJarNames.iterator(); iter.hasNext();) {
489             CompiledEntry entry = (CompiledEntry) iter.next();
490             String JavaDoc formatedName = entry.getName(false) + (entry.getType() == CompiledEntry.FOLDER ? "/" : ""); //$NON-NLS-1$//$NON-NLS-2$
491
if (dotOnTheClasspath && formatedName.startsWith(EXPANDED_DOT)) {
492                 dotIncluded = dotIncluded & true;
493                 continue;
494             }
495             fileSetValues[count++] = formatedName;
496             continue;
497         }
498         if (count != 0) {
499             FileSet fileSet = new FileSet(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER), null, Utils.getStringFromArray(fileSetValues, ","), null, replaceVariables(exclude, true), null, null); //$NON-NLS-1$
500
script.printCopyTask(null, root, new FileSet[] {fileSet}, true, false);
501         }
502         //Dot on the classpath need to be copied in a special way
503
if (dotIncluded) {
504             FileSet fileSet = new FileSet(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER) + '/' + EXPANDED_DOT, null, "**", null, replaceVariables(exclude, true), null, null); //$NON-NLS-1$
505
script.printCopyTask(null, root, new FileSet[] {fileSet}, true, false);
506         }
507         //General copy of the files listed in the includes
508
if (include != null || exclude != null) {
509             String JavaDoc includeSet = replaceVariables(Utils.getStringFromArray(splitIncludes, ","), true); //$NON-NLS-1$
510
if(includeSet != null && includeSet.length() > 0) {
511                 FileSet fileSet = new FileSet(Utils.getPropertyFormat(PROPERTY_BASEDIR), null, includeSet, null, replaceVariables(exclude, true), null, null);
512                 script.printCopyTask(null, root, new FileSet[] {fileSet}, true, false);
513             }
514         }
515         generatePermissionProperties(root);
516         genarateIdReplacementCall(destination.toString());
517
518         if (customBuildCallbacks != null) {
519             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_GATHER_BIN_PARTS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
520         }
521
522         script.printTargetEnd();
523     }
524
525     private void genarateIdReplacementCall(String JavaDoc location) {
526         Properties bundleProperties = (Properties) model.getUserObject();
527         if (bundleProperties == null)
528             return;
529
530         String JavaDoc qualifier = bundleProperties.getProperty(PROPERTY_QUALIFIER);
531         if (qualifier == null)
532             return;
533         script.println("<eclipse.versionReplacer path=\"" + AntScript.getEscaped(location) + "\" version=\"" + model.getVersion() + "\"/>"); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
534
}
535
536     private void generatePermissionProperties(String JavaDoc directory) throws CoreException {
537         getPermissionProperties();
538         for (Iterator iter = permissionProperties.entrySet().iterator(); iter.hasNext();) {
539             Map.Entry permission = (Map.Entry) iter.next();
540             String JavaDoc instruction = (String JavaDoc) permission.getKey();
541             String JavaDoc parameters = (String JavaDoc) permission.getValue();
542             int index;
543             if ((index = instruction.indexOf(PERMISSIONS)) != -1) {
544                 generateChmodInstruction(directory, instruction.substring(index + PERMISSIONS.length() + 1), parameters);
545                 continue;
546             }
547             if (instruction.startsWith(LINK)) {
548                 generateLinkInstruction(directory, parameters);
549             }
550         }
551     }
552
553     private void generateChmodInstruction(String JavaDoc dir, String JavaDoc rights, String JavaDoc files) {
554         // TO CHECK We only consider rights specified with numbers
555
if (rights.equals(EXECUTABLE)) {
556             rights = "755"; //$NON-NLS-1$
557
}
558         script.printChmod(dir, rights, files);
559     }
560
561     private void generateLinkInstruction(String JavaDoc dir, String JavaDoc files) {
562         String JavaDoc[] links = Utils.getArrayFromString(files, ","); //$NON-NLS-1$
563
List arguments = new ArrayList(2);
564         for (int i = 0; i < links.length; i += 2) {
565             arguments.add(links[i]);
566             arguments.add(links[i + 1]);
567             script.printExecTask("ln -s", dir, arguments, "Linux"); //$NON-NLS-1$ //$NON-NLS-2$
568
arguments.clear();
569         }
570     }
571
572     protected Properties getPermissionProperties() throws CoreException {
573         if (permissionProperties == null) {
574             permissionProperties = readProperties(getLocation(model), PERMISSIONS_FILE, IStatus.INFO);
575         }
576         return permissionProperties;
577     }
578
579     /**
580      * Add the <code>zip.plugin</code> target to the given Ant script.
581      */

582     private void generateZipPluginTarget() {
583         script.println();
584         script.printTargetDeclaration(TARGET_ZIP_PLUGIN, TARGET_INIT, null, null, NLS.bind(Messages.build_plugin_zipPlugin, model.getSymbolicName()));
585         script.printDeleteTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), null, null);
586         script.printMkdirTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER));
587         script.printAntCallTask(TARGET_BUILD_JARS, true, null);
588         script.printAntCallTask(TARGET_BUILD_SOURCES, true, null);
589         Map params = new HashMap(1);
590         params.put(PROPERTY_DESTINATION_TEMP_FOLDER, Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER) + '/');
591         script.printAntCallTask(TARGET_GATHER_BIN_PARTS, true, params);
592         script.printAntCallTask(TARGET_GATHER_SOURCES, true, params);
593         FileSet fileSet = new FileSet(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), null, "**/*.bin" + Utils.getPropertyFormat(PROPERTY_LOG_EXTENSION), null, null, null, null); //$NON-NLS-1$
594
script.printDeleteTask(null, null, new FileSet[] {fileSet});
595         script.printZipTask(pluginZipDestination, Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), true, false, null);
596         script.printDeleteTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), null, null);
597         script.printTargetEnd();
598     }
599
600     /**
601      * Add the <code>build.update.jar</code> target to the given Ant script.
602      */

603     private void generateBuildUpdateJarTarget() {
604         script.println();
605         script.printTargetDeclaration(TARGET_BUILD_UPDATE_JAR, TARGET_INIT, null, null, NLS.bind(Messages.build_plugin_buildUpdateJar, model.getSymbolicName()));
606         script.printDeleteTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), null, null);
607         script.printMkdirTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER));
608         script.printAntCallTask(TARGET_BUILD_JARS, true, null);
609         Map params = new HashMap(1);
610         params.put(PROPERTY_DESTINATION_TEMP_FOLDER, Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER) + '/');
611         script.printAntCallTask(TARGET_GATHER_BIN_PARTS, true, params);
612         script.printJarTask(pluginUpdateJarDestination, Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER) + '/' + fullName, null, "merge"); //$NON-NLS-1$
613
script.printDeleteTask(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER), null, null);
614         if (signJars)
615             script.println("<eclipse.jarProcessor sign=\"" + Utils.getPropertyFormat(PROPERTY_SIGN) + "\" pack=\"" + Utils.getPropertyFormat(PROPERTY_PACK)+ "\" unsign=\"" + Utils.getPropertyFormat(PROPERTY_UNSIGN) + "\" jar=\"" + AntScript.getEscaped(pluginUpdateJarDestination) + "\" alias=\"" + Utils.getPropertyFormat(PROPERTY_SIGN_ALIAS) + "\" keystore=\"" + Utils.getPropertyFormat(PROPERTY_SIGN_KEYSTORE) + "\" storepass=\"" + Utils.getPropertyFormat(PROPERTY_SIGN_STOREPASS) + "\"/>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$
616
script.printTargetEnd();
617     }
618
619     /**
620      * Add the <code>refresh</code> target to the given Ant script.
621      */

622     private void generateRefreshTarget() {
623         script.println();
624         script.printTargetDeclaration(TARGET_REFRESH, TARGET_INIT, PROPERTY_ECLIPSE_RUNNING, null, Messages.build_plugin_refresh);
625         script.printConvertPathTask(new Path(getLocation(model)).removeLastSegments(0).toOSString().replace('\\', '/'), PROPERTY_RESOURCE_PATH, false);
626         script.printRefreshLocalTask(Utils.getPropertyFormat(PROPERTY_RESOURCE_PATH), "infinite"); //$NON-NLS-1$
627
script.printTargetEnd();
628     }
629
630     /**
631      * End the script by closing the project element.
632      */

633     private void generateEpilogue() {
634         script.println();
635         script.printProjectEnd();
636     }
637
638     /**
639      * Defines, the XML declaration, Ant project and targets init and initTemplate.
640      */

641     private void generatePrologue() {
642         script.printProjectDeclaration(model.getSymbolicName(), TARGET_BUILD_JARS, DOT);
643         script.println();
644
645         script.printProperty(PROPERTY_BASE_WS, Utils.getPropertyFormat(PROPERTY_WS));
646         script.printProperty(PROPERTY_BASE_OS, Utils.getPropertyFormat(PROPERTY_OS));
647         script.printProperty(PROPERTY_BASE_ARCH, Utils.getPropertyFormat(PROPERTY_ARCH));
648         script.printProperty(PROPERTY_BASE_NL, Utils.getPropertyFormat(PROPERTY_NL));
649         script.printProperty(PROPERTY_BUNDLE_ID, model.getSymbolicName());
650         script.printProperty(PROPERTY_BUNDLE_VERSION, model.getVersion().toString());
651         script.println();
652
653         if (customBuildCallbacks != null && !customBuildCallbacks.equals(FALSE)) {
654             script.printAvailableTask(PROPERTY_CUSTOM_BUILD_CALLBACKS, customCallbacksBuildpath + '/' + customBuildCallbacks, customBuildCallbacks);
655             script.println();
656         }
657
658         generateCompilerSettings();
659
660         script.printTargetDeclaration(TARGET_INIT, TARGET_PROPERTIES, null, null, null);
661         script.printConditionIsSet(PROPERTY_PLUGIN_TEMP, Utils.getPropertyFormat(PROPERTY_BUILD_TEMP) + '/' + DEFAULT_PLUGIN_LOCATION, PROPERTY_BUILD_TEMP);
662         script.printProperty(PROPERTY_PLUGIN_TEMP, Utils.getPropertyFormat(PROPERTY_BASEDIR));
663         script.printConditionIsSet(PROPERTY_BUILD_RESULT_FOLDER, Utils.getPropertyFormat(PROPERTY_PLUGIN_TEMP) + '/' + model.getSymbolicName() + '_' + model.getVersion(), PROPERTY_BUILD_TEMP);
664         script.printProperty(PROPERTY_BUILD_RESULT_FOLDER, Utils.getPropertyFormat(PROPERTY_BASEDIR));
665
666         script.printProperty(PROPERTY_TEMP_FOLDER, Utils.getPropertyFormat(PROPERTY_BASEDIR) + '/' + PROPERTY_TEMP_FOLDER);
667         script.printProperty(PROPERTY_PLUGIN_DESTINATION, Utils.getPropertyFormat(PROPERTY_BASEDIR));
668         script.printTargetEnd();
669         script.println();
670         script.printTargetDeclaration(TARGET_PROPERTIES, null, PROPERTY_ECLIPSE_RUNNING, null, null);
671         script.printProperty(PROPERTY_BUILD_COMPILER, JDT_COMPILER_ADAPTER);
672         script.println();
673
674         script.printTargetEnd();
675     }
676
677     private void generateCompilerSettings() {
678         String JavaDoc javacSource = null;
679         String JavaDoc javacTarget = null;
680         String JavaDoc bootClasspath = null;
681         String JavaDoc jreProfile = null;
682         try {
683             Properties properties = getBuildProperties();
684             javacSource = properties.getProperty(IBuildPropertiesConstants.PROPERTY_JAVAC_SOURCE);
685             javacTarget = properties.getProperty(IBuildPropertiesConstants.PROPERTY_JAVAC_TARGET);
686             bootClasspath = properties.getProperty(IBuildPropertiesConstants.PROPERTY_BOOT_CLASSPATH);
687             jreProfile = properties.getProperty(IBuildPropertiesConstants.PROPERTY_JRE_COMPILATION_PROFILE);
688         } catch (CoreException e) {
689             //ignore
690
}
691
692         script.printComment(Messages.build_compilerSetting);
693         script.printProperty(PROPERTY_JAVAC_FAIL_ON_ERROR, "false"); //$NON-NLS-1$
694
script.printProperty(PROPERTY_JAVAC_DEBUG_INFO, "on"); //$NON-NLS-1$
695
script.printProperty(PROPERTY_JAVAC_VERBOSE, "false"); //$NON-NLS-1$
696
script.printProperty(PROPERTY_LOG_EXTENSION, ".log"); //$NON-NLS-1$
697
script.printProperty(PROPERTY_JAVAC_COMPILERARG, ""); //$NON-NLS-1$
698

699         if (javacSource == null)
700             script.printProperty(IXMLConstants.PROPERTY_JAVAC_SOURCE, "1.3"); //$NON-NLS-1$
701
if (javacTarget == null)
702             script.printProperty(IXMLConstants.PROPERTY_JAVAC_TARGET, "1.2"); //$NON-NLS-1$
703
if (bootClasspath == null) {
704             script.println("<condition property=\"dir_bootclasspath\" value=\"${java.home}/../Classes\">");//$NON-NLS-1$
705
script.println("\t<os family=\"mac\"/>");//$NON-NLS-1$
706
script.println("</condition>");//$NON-NLS-1$
707
script.println("<property name=\"dir_bootclasspath\" value=\"${java.home}/lib\"/>");//$NON-NLS-1$
708
script.println("<path id=\"path_bootclasspath\">");//$NON-NLS-1$
709
script.println("\t<fileset dir=\"${dir_bootclasspath}\">");//$NON-NLS-1$
710
script.println("\t\t<include name=\"*.jar\"/>");//$NON-NLS-1$
711
script.println("\t</fileset>");//$NON-NLS-1$
712
script.println("</path>");//$NON-NLS-1$
713
script.printPropertyRefid(PROPERTY_BOOTCLASSPATH, "path_bootclasspath"); //$NON-NLS-1$
714
}
715
716         Properties environmentMappings = getExecutionEnvironmentMappings();
717         if (jreProfile != null && !environmentMappings.containsKey(jreProfile + '.' + IXMLConstants.PROPERTY_JAVAC_SOURCE)) {
718             if (reportResolutionErrors) {
719                 IStatus status = new Status(IStatus.ERROR, model.getSymbolicName(), IStatus.ERROR, NLS.bind(Messages.build_plugin_unrecognizedJRE, jreProfile), null);
720                 BundleHelper.getDefault().getLog().log(status);
721             }
722             jreProfile = null;
723         }
724
725         if (javacSource != null)
726             script.printProperty(PROPERTY_BUNDLE_JAVAC_SOURCE, javacSource);
727         if (javacTarget != null)
728             script.printProperty(PROPERTY_BUNDLE_JAVAC_TARGET, javacTarget);
729         if (bootClasspath != null)
730             script.printProperty(PROPERTY_BUNDLE_BOOTCLASSPATH, bootClasspath);
731
732         String JavaDoc source, target = null;
733         String JavaDoc[] modelEnvironments = model.getExecutionEnvironments();
734         String JavaDoc[] environments = null;
735         if (jreProfile != null) {
736             environments = new String JavaDoc[modelEnvironments.length + 1];
737             environments[0] = jreProfile;
738             System.arraycopy(modelEnvironments, 0, environments, 1, modelEnvironments.length);
739         } else {
740             environments = modelEnvironments;
741         }
742         for (int i = 0; i < environments.length; i++) {
743             if (bootClasspath == null)
744                 script.printConditionIsSet(PROPERTY_BUNDLE_BOOTCLASSPATH, Utils.getPropertyFormat(environments[i]), environments[i]);
745
746             source = (String JavaDoc) environmentMappings.get(environments[i] + '.' + IXMLConstants.PROPERTY_JAVAC_SOURCE);
747             target = (String JavaDoc) environmentMappings.get(environments[i] + '.' + IXMLConstants.PROPERTY_JAVAC_TARGET);
748             if (javacSource == null && source != null)
749                 script.printConditionIsSet(PROPERTY_BUNDLE_JAVAC_SOURCE, source, environments[i]);
750             if (javacTarget == null && target != null)
751                 script.printConditionIsSet(PROPERTY_BUNDLE_JAVAC_TARGET, target, environments[i]);
752         }
753
754         if (javacSource == null)
755             script.printProperty(PROPERTY_BUNDLE_JAVAC_SOURCE, Utils.getPropertyFormat(IXMLConstants.PROPERTY_JAVAC_SOURCE));
756         if (javacTarget == null)
757             script.printProperty(PROPERTY_BUNDLE_JAVAC_TARGET, Utils.getPropertyFormat(IXMLConstants.PROPERTY_JAVAC_TARGET));
758         if (bootClasspath == null)
759             script.printProperty(PROPERTY_BUNDLE_BOOTCLASSPATH, Utils.getPropertyFormat(PROPERTY_BOOTCLASSPATH));
760         script.println();
761     }
762
763     /**
764      * Sets the PluginModel to generate script from.
765      *
766      * @param model
767      * @throws CoreException
768      */

769     public void setModel(BundleDescription model) throws CoreException {
770         if (model == null) {
771             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_ELEMENT_MISSING, Messages.error_missingElement, null));
772         }
773         model = getSite(false).getRegistry().getVersionReplacement(model);
774         this.model = model;
775         if (getBuildProperties() == AbstractScriptGenerator.MissingProperties.getInstance()) {
776             //if there were no build.properties, then it is a binary plugin
777
binaryPlugin = true;
778         } else {
779             getCompiledElements().add(model.getSymbolicName());
780         }
781         Properties bundleProperties = (Properties) model.getUserObject();
782         if (bundleProperties == null) {
783             bundleProperties = new Properties();
784             model.setUserObject(bundleProperties);
785         }
786         bundleProperties.put(IS_COMPILED, binaryPlugin ? Boolean.FALSE : Boolean.TRUE);
787     }
788
789     /**
790      * Sets model to generate scripts from.
791      *
792      * @param modelId
793      * @throws CoreException
794      */

795     public void setModelId(String JavaDoc modelId, String JavaDoc modelVersion) throws CoreException {
796         BundleDescription newModel = getModel(modelId, modelVersion);
797         if (newModel == null) {
798             String JavaDoc message = NLS.bind(Messages.exception_missingElement, modelId);
799             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_ELEMENT_MISSING, message, null));
800         }
801         setModel(newModel);
802     }
803
804     /**
805      * Add the <code>build.zips</code> target to the given Ant script.
806      *
807      * @throws CoreException
808      */

809     private void generateBuildZipsTarget() throws CoreException {
810         StringBuffer JavaDoc zips = new StringBuffer JavaDoc();
811         Properties props = getBuildProperties();
812         for (Iterator iterator = props.entrySet().iterator(); iterator.hasNext();) {
813             Map.Entry entry = (Map.Entry) iterator.next();
814             String JavaDoc key = (String JavaDoc) entry.getKey();
815             if (key.startsWith(PROPERTY_SOURCE_PREFIX) && key.endsWith(PROPERTY_ZIP_SUFFIX)) {
816                 String JavaDoc zipName = key.substring(PROPERTY_SOURCE_PREFIX.length());
817                 zips.append(',');
818                 zips.append(zipName);
819                 generateZipIndividualTarget(zipName, (String JavaDoc) entry.getValue());
820             }
821         }
822         script.println();
823         script.printTargetDeclaration(TARGET_BUILD_ZIPS, TARGET_INIT + zips.toString(), null, null, null);
824         script.printTargetEnd();
825     }
826
827     /**
828      * Sets the featureGenerator.
829      * @param featureGenerator The featureGenerator to set
830      */

831     public void setFeatureGenerator(FeatureBuildScriptGenerator featureGenerator) {
832         this.featureGenerator = featureGenerator;
833     }
834
835     /**
836      * Add the "build.jars" target to the given Ant script using the specified plug-in model.
837      *
838      * @param pluginModel the plug-in model to reference
839      * @throws CoreException
840      */

841     private void generateBuildJarsTarget(BundleDescription pluginModel) throws CoreException {
842         Properties properties = getBuildProperties();
843         CompiledEntry[] availableJars = extractEntriesToCompile(properties);
844         compiledJarNames = new ArrayList(availableJars.length);
845         Map jars = new HashMap(availableJars.length);
846         for (int i = 0; i < availableJars.length; i++)
847             jars.put(availableJars[i].getName(false), availableJars[i]);
848
849         // Put the jars in a correct compile order
850
String JavaDoc jarOrder = (String JavaDoc) getBuildProperties().get(PROPERTY_JAR_ORDER);
851         IClasspathComputer classpath;
852         if (AbstractScriptGenerator.isBuildingOSGi())
853             classpath = new ClasspathComputer3_0(this);
854         else
855             classpath = new ClasspathComputer2_1(this);
856
857         if (jarOrder != null) {
858             String JavaDoc[] order = Utils.getArrayFromString(jarOrder);
859             for (int i = 0; i < order.length; i++) {
860                 CompiledEntry jar = (CompiledEntry) jars.get(order[i]);
861                 if (jar == null)
862                     continue;
863
864                 compiledJarNames.add(jar);
865                 generateCompilationTarget(classpath.getClasspath(pluginModel, jar), jar);
866                 generateSRCTarget(jar);
867                 jars.remove(order[i]);
868             }
869         }
870         for (Iterator iterator = jars.values().iterator(); iterator.hasNext();) {
871             CompiledEntry jar = (CompiledEntry) iterator.next();
872             compiledJarNames.add(jar);
873             generateCompilationTarget(classpath.getClasspath(pluginModel, jar), jar);
874             generateSRCTarget(jar);
875         }
876         script.println();
877         script.printTargetDeclaration(TARGET_BUILD_JARS, TARGET_INIT, null, null, NLS.bind(Messages.build_plugin_buildJars, pluginModel.getSymbolicName()));
878         Map params = null;
879         if (customBuildCallbacks != null) {
880             params = new HashMap(1);
881             params.put(PROPERTY_BUILD_RESULT_FOLDER, Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER));
882             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_BUILD_JARS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
883         }
884         for (Iterator iter = compiledJarNames.iterator(); iter.hasNext();) {
885             String JavaDoc name = ((CompiledEntry) iter.next()).getName(false);
886             script.printAvailableTask(name, replaceVariables(getJARLocation(name), true));
887             script.printAntCallTask(name, true, null);
888         }
889         if (customBuildCallbacks != null) {
890             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_BUILD_JARS, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
891         }
892         script.printTargetEnd();
893
894         script.println();
895         script.printTargetDeclaration(TARGET_BUILD_SOURCES, TARGET_INIT, null, null, null);
896         if (customBuildCallbacks != null) {
897             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + TARGET_BUILD_SOURCES, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
898         }
899         for (Iterator iter = compiledJarNames.iterator(); iter.hasNext();) {
900             String JavaDoc jarName = ((CompiledEntry) iter.next()).getName(false);
901             String JavaDoc srcName = getSRCName(jarName);
902             script.printAvailableTask(srcName, getSRCLocation(jarName));
903             script.printAntCallTask(srcName, true, null);
904         }
905         if (customBuildCallbacks != null) {
906             script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + TARGET_BUILD_SOURCES, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, null);
907         }
908         script.printTargetEnd();
909     }
910
911     /**
912      * generate compile settings for compiling this entry
913      * warning levels, default encoding, custom encodings
914      * @param javac
915      * @param entry
916      */

917     private void generateCompilerSettings(JavacTask javac, CompiledEntry entry, List classpath) {
918         final String JavaDoc ADAPTER_ENCODING = "#ADAPTER#ENCODING#"; //$NON-NLS-1$
919
final String JavaDoc ADAPTER_ACCESS = "#ADAPTER#ACCESS#"; //$NON-NLS-1$
920

921         Properties properties = null;
922         try {
923             properties = getBuildProperties();
924         } catch (CoreException e) {
925             return;
926         }
927         if (properties == null && classpath.size() == 0)
928             return;
929
930         String JavaDoc name = entry.getName(false);
931         if (name.equals(EXPANDED_DOT))
932             name = DOT;
933
934         String JavaDoc defaultEncodingVal = properties.getProperty(PROPERTY_JAVAC_DEFAULT_ENCODING_PREFIX + name);
935         if (defaultEncodingVal != null)
936             javac.setEncoding(defaultEncodingVal);
937
938         String JavaDoc customEncodingsVal = properties.getProperty(PROPERTY_JAVAC_CUSTOM_ENCODINGS_PREFIX + name);
939         String JavaDoc warningLevels = properties.getProperty(PROPERTY_JAVAC_WARNINGS_PREFIX + name);
940
941         if (customEncodingsVal == null && warningLevels == null && classpath.size() == 0) {
942             return;
943         }
944
945         String JavaDoc root = getLocation(model);
946         File file = new File(root, "javaCompiler." + name.replaceAll("[\\\\/]", "_") + ".args"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
947
if (file.exists()) {
948             file.delete();
949         }
950         Writer writer = null;
951         try {
952             try {
953                 //only create the file if we are going to write something in it
954
if (warningLevels != null || customEncodingsVal != null)
955                     writer = new BufferedWriter(new FileWriter(file));
956
957                 if (warningLevels != null) {
958                     writer.write("-warn:" + warningLevels + "\n"); //$NON-NLS-1$//$NON-NLS-2$
959
}
960
961                 if (customEncodingsVal != null) {
962                     String JavaDoc[] encodings = customEncodingsVal.split(","); //$NON-NLS-1$
963
if (encodings.length > 0) {
964                         for (int i = 0; i < encodings.length; i++) {
965                             writer.write(ADAPTER_ENCODING + encodings[i] + "\n"); //$NON-NLS-1$
966
}
967                     }
968                 }
969                 //handle access rules if we are using ClasspathComputer3_0
970
if (classpath.size() > 0 && classpath.get(0) instanceof ClasspathElement) {
971                     for (Iterator iterator = classpath.iterator(); iterator.hasNext();) {
972                         ClasspathElement element = (ClasspathElement) iterator.next();
973                         if (element.getPath() != null && element.getPath().length() > 0 && element.getAccessRules().length() > 0) {
974                             String JavaDoc path = element.getPath();
975                             if (path.startsWith(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER))) {
976                                 //remove leading ${build.result.folder}/
977
path = path.substring(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER).length() + 1);
978                             }
979                             //remove leading ../../..
980
path = path.replaceFirst("^(\\.\\.[\\\\/])*", ""); //$NON-NLS-1$//$NON-NLS-2$
981
if (writer == null)
982                                 writer = new BufferedWriter(new FileWriter(file));
983                             writer.write(ADAPTER_ACCESS + path + element.getAccessRules() + "\n"); //$NON-NLS-1$
984
}
985                     }
986                 }
987                 if (writer != null)
988                     javac.setCompileArgsFile(Utils.getPropertyFormat(PROPERTY_BASEDIR) + "/" + file.getName()); //$NON-NLS-1$
989
} finally {
990                 if (writer != null)
991                     writer.close();
992             }
993         } catch (IOException e1) {
994             //ignore
995
}
996     }
997
998     /**
999      * Add the "jar" target to the given Ant script using the given classpath and
1000     * jar as parameters.
1001     *
1002     * @param classpath the classpath for the jar command
1003     * @param entry
1004     */

1005    private void generateCompilationTarget(List classpath, CompiledEntry entry) {
1006        script.println();
1007        String JavaDoc name = entry.getName(false);
1008        script.printTargetDeclaration(name, TARGET_INIT, null, entry.getName(true), NLS.bind(Messages.build_plugin_jar, model.getSymbolicName() + ' ' + name));
1009        String JavaDoc destdir = getTempJARFolderLocation(entry.getName(true));
1010        script.printDeleteTask(destdir, null, null);
1011        script.printMkdirTask(destdir);
1012        script.printPathStructure("path", name + PROPERTY_CLASSPATH, classpath); //$NON-NLS-1$
1013

1014        String JavaDoc[] sources = entry.getSource();
1015        Map params = null, references = null;
1016        if (customBuildCallbacks != null) {
1017            params = new HashMap(2);
1018            params.put(PROPERTY_TARGET_FOLDER, destdir);
1019            for (int i = 1; i <= sources.length; i++) {
1020                params.put(PROPERTY_SOURCE_FOLDER + i, sources[i - 1]);
1021            }
1022
1023            references = new HashMap(1);
1024            references.put(name + PROPERTY_CLASSPATH, null);
1025            script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_PRE + name, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, references);
1026        }
1027
1028        script.printComment("compile the source code"); //$NON-NLS-1$
1029
JavacTask javac = new JavacTask();
1030        javac.setClasspathId(name + PROPERTY_CLASSPATH);
1031        javac.setBootClasspath(Utils.getPropertyFormat(PROPERTY_BUNDLE_BOOTCLASSPATH));
1032        javac.setDestdir(destdir);
1033        javac.setFailOnError(Utils.getPropertyFormat(PROPERTY_JAVAC_FAIL_ON_ERROR));
1034        javac.setDebug(Utils.getPropertyFormat(PROPERTY_JAVAC_DEBUG_INFO));
1035        javac.setVerbose(Utils.getPropertyFormat(PROPERTY_JAVAC_VERBOSE));
1036        javac.setIncludeAntRuntime("no"); //$NON-NLS-1$
1037
javac.setSource(Utils.getPropertyFormat(PROPERTY_BUNDLE_JAVAC_SOURCE));
1038        javac.setTarget(Utils.getPropertyFormat(PROPERTY_BUNDLE_JAVAC_TARGET));
1039        javac.setCompileArgs(Utils.getPropertyFormat(PROPERTY_JAVAC_COMPILERARG));
1040        javac.setSrcdir(sources);
1041        javac.setLogExtension(Utils.getPropertyFormat(PROPERTY_LOG_EXTENSION));
1042        generateCompilerSettings(javac, entry, classpath);
1043
1044        script.print(javac);
1045        script.printComment("Copy necessary resources"); //$NON-NLS-1$
1046
FileSet[] fileSets = new FileSet[sources.length];
1047        for (int i = 0; i < sources.length; i++) {
1048            String JavaDoc excludes = "**/*.java, **/package.htm*"; //$NON-NLS-1$
1049
String JavaDoc excludedFromJar = entry.getExcludedFromJar();
1050            if (excludedFromJar != null)
1051                excludes += ',' + excludedFromJar;
1052
1053            fileSets[i] = new FileSet(sources[i], null, null, null, excludes, null, null);
1054        }
1055
1056        script.printCopyTask(null, destdir, fileSets, true, false);
1057
1058        if (customBuildCallbacks != null) {
1059            script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST_COMPILE + name, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, references);
1060        }
1061
1062        String JavaDoc jarLocation = getJARLocation(entry.getName(true));
1063        script.printMkdirTask(new Path(jarLocation).removeLastSegments(1).toString());
1064
1065        if (entry.getType() == CompiledEntry.FOLDER) {
1066            FileSet[] binFolder = new FileSet[] {new FileSet(destdir, null, null, null, null, null, null)};
1067            script.printCopyTask(null, jarLocation, binFolder, true, false);
1068        } else {
1069            script.printJarTask(jarLocation, destdir, getEmbeddedManifestFile(entry, destdir));
1070        }
1071        script.printDeleteTask(destdir, null, null);
1072
1073        if (customBuildCallbacks != null) {
1074            params.clear();
1075            params.put(PROPERTY_JAR_LOCATION, jarLocation);
1076            script.printSubantTask(Utils.getPropertyFormat(PROPERTY_CUSTOM_BUILD_CALLBACKS), PROPERTY_POST + name, customCallbacksBuildpath, customCallbacksFailOnError, customCallbacksInheritAll, params, references);
1077        }
1078        script.printTargetEnd();
1079    }
1080
1081    private String JavaDoc getEmbeddedManifestFile(CompiledEntry jarEntry, String JavaDoc destdir) {
1082        try {
1083            String JavaDoc manifestName = getBuildProperties().getProperty(PROPERTY_MANIFEST_PREFIX + jarEntry.getName(true));
1084            if (manifestName == null)
1085                return null;
1086            return destdir + '/' + manifestName;
1087        } catch (CoreException e) {
1088            return null;
1089        }
1090    }
1091
1092    /**
1093     *
1094     * @param properties
1095     * @return JAR[]
1096     */

1097    protected CompiledEntry[] extractEntriesToCompile(Properties properties) throws CoreException {
1098        List result = new ArrayList(5);
1099        int prefixLength = PROPERTY_SOURCE_PREFIX.length();
1100        for (Iterator iterator = properties.entrySet().iterator(); iterator.hasNext();) {
1101            Map.Entry entry = (Map.Entry) iterator.next();
1102            String JavaDoc key = (String JavaDoc) entry.getKey();
1103            if (!(key.startsWith(PROPERTY_SOURCE_PREFIX)))
1104                continue;
1105            key = key.substring(prefixLength);
1106            String JavaDoc[] source = Utils.getArrayFromString((String JavaDoc) entry.getValue());
1107            if (source.length == 0) {
1108                String JavaDoc message = NLS.bind(Messages.error_missingSourceFolder, model.getSymbolicName(), entry.getKey());
1109                throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_GENERIC, message, null));
1110            }
1111            String JavaDoc[] output = Utils.getArrayFromString(properties.getProperty(PROPERTY_OUTPUT_PREFIX + key));
1112            String JavaDoc[] extraClasspath = Utils.getArrayFromString(properties.getProperty(PROPERTY_EXTRAPATH_PREFIX + key));
1113            String JavaDoc excludedFromJar = properties.getProperty(PROPERTY_EXCLUDE_PREFIX + key);
1114            CompiledEntry newEntry = new CompiledEntry(key, source, output, extraClasspath, excludedFromJar, key.endsWith(PROPERTY_JAR_SUFFIX) ? CompiledEntry.JAR : CompiledEntry.FOLDER);
1115            result.add(newEntry);
1116        }
1117        return (CompiledEntry[]) result.toArray(new CompiledEntry[result.size()]);
1118    }
1119
1120    /**
1121     * Add the "src" target to the given Ant script.
1122     *
1123     * @param jar
1124     */

1125    private void generateSRCTarget(CompiledEntry jar) {
1126        script.println();
1127        String JavaDoc name = jar.getName(false);
1128        String JavaDoc srcName = getSRCName(name);
1129        script.printTargetDeclaration(srcName, TARGET_INIT, null, srcName, null);
1130        String JavaDoc[] sources = jar.getSource();
1131        filterNonExistingSourceFolders(sources);
1132        FileSet[] fileSets = new FileSet[sources.length];
1133        int count = 0;
1134        for (int i = 0; i < sources.length; i++) {
1135            if (sources[i] != null)
1136                fileSets[count++] = new FileSet(sources[i], null, "**/*.java", null, null, null, null); //$NON-NLS-1$
1137
}
1138
1139        String JavaDoc srcLocation = getSRCLocation(name);
1140        script.printMkdirTask(new Path(srcLocation).removeLastSegments(1).toString());
1141
1142        if (count != 0)
1143            script.printZipTask(srcLocation, null, false, false, fileSets);
1144
1145        script.printTargetEnd();
1146    }
1147
1148    private void filterNonExistingSourceFolders(String JavaDoc[] sources) {
1149        File pluginRoot;
1150        pluginRoot = new File(getLocation(model));
1151        for (int i = 0; i < sources.length; i++) {
1152            File file = new File(pluginRoot, sources[i]);
1153            if (!file.exists()) {
1154                sources[i] = null;
1155                IStatus status = new Status(IStatus.WARNING, PI_PDEBUILD, EXCEPTION_SOURCE_LOCATION_MISSING, NLS.bind(Messages.warning_cannotLocateSource, file.getAbsolutePath()), null);
1156                BundleHelper.getDefault().getLog().log(status);
1157            }
1158        }
1159    }
1160
1161    /**
1162     * Return the name of the zip file for the source for the jar with
1163     * the given name.
1164     *
1165     * @param jarName the name of the jar file
1166     * @return String
1167     */

1168    protected String JavaDoc getSRCLocation(String JavaDoc jarName) {
1169        return getJARLocation(getSRCName(jarName));
1170    }
1171
1172    /**
1173     * Return the location for a temporary file for the jar file with
1174     * the given name.
1175     *
1176     * @param jarName the name of the jar file
1177     * @return String
1178     */

1179    protected String JavaDoc getTempJARFolderLocation(String JavaDoc jarName) {
1180        IPath destination = new Path(Utils.getPropertyFormat(PROPERTY_TEMP_FOLDER));
1181        destination = destination.append(jarName + ".bin"); //$NON-NLS-1$
1182
return destination.toString();
1183    }
1184
1185    /**
1186     * Return the full location of the jar file.
1187     *
1188     * @param jarName the name of the jar file
1189     * @return String
1190     */

1191    protected String JavaDoc getJARLocation(String JavaDoc jarName) {
1192        return new Path(Utils.getPropertyFormat(PROPERTY_BUILD_RESULT_FOLDER)).append(jarName).toString();
1193    }
1194
1195    protected String JavaDoc[] getClasspathEntries(BundleDescription lookedUpModel) throws CoreException {
1196        return (String JavaDoc[]) getSite(false).getRegistry().getExtraData().get(new Long JavaDoc(lookedUpModel.getBundleId()));
1197    }
1198
1199    protected Properties getBuildProperties() throws CoreException {
1200        if (buildProperties == null)
1201            return buildProperties = readProperties(model.getLocation(), propertiesFileName, isIgnoreMissingPropertiesFile() ? IStatus.OK : IStatus.WARNING);
1202
1203        return buildProperties;
1204    }
1205
1206    /**
1207     * Return the name of the zip file for the source from the given jar name.
1208     *
1209     * @param jarName the name of the jar file
1210     * @return String
1211     */

1212    protected String JavaDoc getSRCName(String JavaDoc jarName) {
1213        if (jarName.endsWith(".jar")) { //$NON-NLS-1$
1214
return jarName.substring(0, jarName.length() - 4) + SRC_ZIP;
1215        }
1216        if (jarName.equals(EXPANDED_DOT))
1217            return SRC_ZIP;
1218        return jarName.replace('/', '.') + SRC_ZIP;
1219    }
1220
1221    /**
1222     * If the model defines its own custom script, we do not generate a new one
1223     * but we do try to update the version number.
1224     */

1225    private void updateExistingScript() throws CoreException {
1226        String JavaDoc root = getLocation(model);
1227        File buildFile = new File(root, buildScriptFileName);
1228        if (!buildFile.exists()) {
1229            String JavaDoc message = NLS.bind(Messages.error_missingCustomBuildFile, buildFile);
1230            throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_SCRIPT, message, null));
1231        }
1232        try {
1233            updateVersion(buildFile, PROPERTY_VERSION_SUFFIX, model.getVersion().toString());
1234        } catch (IOException e) {
1235            String JavaDoc message = NLS.bind(Messages.exception_writeScript, buildFile);
1236            throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_SCRIPT, message, e));
1237        }
1238        return;
1239    }
1240
1241    /**
1242     * Substitute the value of an element description variable (variables that
1243     * are found in files like plugin.xml, e.g. $ws$) by an Ant property.
1244     *
1245     * @param sourceString
1246     * @return String
1247     */

1248    protected String JavaDoc replaceVariables(String JavaDoc sourceString, boolean compiledElement) {
1249        if (sourceString == null)
1250            return null;
1251
1252        int i = -1;
1253        String JavaDoc result = sourceString;
1254        while ((i = result.indexOf(DESCRIPTION_VARIABLE_WS)) >= 0)
1255            result = result.substring(0, i) + "ws/" + Utils.getPropertyFormat(compiledElement ? PROPERTY_WS : PROPERTY_BASE_WS) + result.substring(i + DESCRIPTION_VARIABLE_WS.length()); //$NON-NLS-1$
1256
while ((i = result.indexOf(DESCRIPTION_VARIABLE_OS)) >= 0)
1257            result = result.substring(0, i) + "os/" + Utils.getPropertyFormat(compiledElement ? PROPERTY_OS : PROPERTY_BASE_OS) + result.substring(i + DESCRIPTION_VARIABLE_OS.length()); //$NON-NLS-1$
1258
while ((i = result.indexOf(DESCRIPTION_VARIABLE_ARCH)) >= 0)
1259            result = result.substring(0, i) + "arch/" + Utils.getPropertyFormat(compiledElement ? PROPERTY_ARCH : PROPERTY_BASE_ARCH) + result.substring(i + DESCRIPTION_VARIABLE_OS.length()); //$NON-NLS-1$
1260
while ((i = result.indexOf(DESCRIPTION_VARIABLE_NL)) >= 0)
1261            result = result.substring(0, i) + "nl/" + Utils.getPropertyFormat(compiledElement ? PROPERTY_NL : PROPERTY_BASE_NL) + result.substring(i + DESCRIPTION_VARIABLE_NL.length()); //$NON-NLS-1$
1262
return result;
1263    }
1264
1265    public BundleDescription getModel() {
1266        return model;
1267    }
1268
1269    public String JavaDoc getPropertiesFileName() {
1270        return propertiesFileName;
1271    }
1272
1273    public void setPropertiesFileName(String JavaDoc propertyFileName) {
1274        this.propertiesFileName = propertyFileName;
1275    }
1276
1277    public String JavaDoc getBuildScriptFileName() {
1278        return buildScriptFileName;
1279    }
1280
1281    public void setBuildScriptFileName(String JavaDoc buildScriptFileName) {
1282        this.buildScriptFileName = buildScriptFileName;
1283    }
1284
1285    /**
1286     * Sets whether or not to sign any constructed jars.
1287     *
1288     * @param value whether or not to sign any constructed JARs
1289     */

1290    public void setSignJars(boolean value) {
1291        signJars = value;
1292    }
1293
1294    /**
1295     * Returns the model object which is associated with the given identifier.
1296     * Returns <code>null</code> if the model object cannot be found.
1297     *
1298     * @param modelId the identifier of the model object to lookup
1299     * @return the model object or <code>null</code>
1300     */

1301    protected BundleDescription getModel(String JavaDoc modelId, String JavaDoc modelVersion) throws CoreException {
1302        if (modelVersion == null)
1303            return getSite(false).getRegistry().getResolvedBundle(modelId);
1304        return getSite(false).getRegistry().getResolvedBundle(modelId, modelVersion);
1305    }
1306
1307    public IPluginEntry getAssociatedEntry() {
1308        return associatedEntry;
1309    }
1310
1311    public void setAssociatedEntry(IPluginEntry associatedEntry) {
1312        this.associatedEntry = associatedEntry;
1313    }
1314}
1315
Popular Tags