KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > wizards > exports > FeatureExportJob


1 /*******************************************************************************
2  * Copyright (c) 2000, 2004 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Common Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/cpl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.internal.ui.wizards.exports;
12 import java.io.*;
13 import java.lang.reflect.*;
14 import java.util.*;
15 import org.eclipse.ant.core.*;
16 import org.eclipse.core.resources.*;
17 import org.eclipse.core.runtime.*;
18 import org.eclipse.core.runtime.jobs.*;
19 import org.eclipse.jdt.core.*;
20 import org.eclipse.jface.dialogs.*;
21 import org.eclipse.jface.preference.*;
22 import org.eclipse.pde.core.*;
23 import org.eclipse.pde.core.build.*;
24 import org.eclipse.pde.core.plugin.*;
25 import org.eclipse.pde.internal.build.*;
26 import org.eclipse.pde.internal.core.*;
27 import org.eclipse.pde.internal.core.build.*;
28 import org.eclipse.pde.internal.core.feature.FeatureChild;
29 import org.eclipse.pde.internal.core.ifeature.*;
30 import org.eclipse.pde.internal.ui.*;
31 import org.eclipse.pde.internal.ui.build.*;
32 import org.eclipse.swt.widgets.*;
33
34 public class FeatureExportJob extends Job implements IPreferenceConstants {
35     
36     // The three supported export types
37
public static final int EXPORT_AS_ZIP = 0;
38     public static final int EXPORT_AS_DIRECTORY = 1;
39     public static final int EXPORT_AS_UPDATE_JARS = 2;
40     
41     // write to the ant build listener log
42
protected static PrintWriter writer;
43     protected static File logFile;
44     
45     // Export options specified in the wizard
46
protected int fExportType;
47     protected boolean fExportSource;
48     protected String JavaDoc fDestinationDirectory;
49     protected String JavaDoc fZipFilename;
50     protected Object JavaDoc[] fItems;
51     
52     // Location where the build takes place
53
protected String JavaDoc fBuildTempLocation;
54     private String JavaDoc fDevProperties;
55     
56     protected HashMap fBuildProperties;
57     
58     class SchedulingRule implements ISchedulingRule {
59
60         /* (non-Javadoc)
61          * @see org.eclipse.core.runtime.jobs.ISchedulingRule#contains(org.eclipse.core.runtime.jobs.ISchedulingRule)
62          */

63         public boolean contains(ISchedulingRule rule) {
64             return rule instanceof SchedulingRule;
65         }
66
67         /* (non-Javadoc)
68          * @see org.eclipse.core.runtime.jobs.ISchedulingRule#isConflicting(org.eclipse.core.runtime.jobs.ISchedulingRule)
69          */

70         public boolean isConflicting(ISchedulingRule rule) {
71             return rule instanceof SchedulingRule;
72         }
73         
74     }
75     
76     public FeatureExportJob(int exportType, boolean exportSource, String JavaDoc destination, String JavaDoc zipFileName, Object JavaDoc[] items) {
77         super(PDEPlugin.getResourceString("FeatureExportJob.name")); //$NON-NLS-1$
78
fExportType = exportType;
79         fExportSource = exportSource;
80         fDestinationDirectory = destination;
81         fZipFilename = zipFileName;
82         fItems = items;
83         fBuildTempLocation = PDEPlugin.getDefault().getStateLocation().append("temp").toString(); //$NON-NLS-1$
84
setRule(new SchedulingRule());
85     }
86     
87     /*
88      * (non-Javadoc)
89      *
90      * @see org.eclipse.core.internal.jobs.InternalJob#run(org.eclipse.core.runtime.IProgressMonitor)
91      */

92     protected IStatus run(IProgressMonitor monitor) {
93         String JavaDoc errorMessage = null;
94         try {
95             createLogWriter();
96             doExports(monitor);
97         } catch (final CoreException e) {
98             final Display display = getStandardDisplay();
99             display.asyncExec(new Runnable JavaDoc() {
100                 public void run() {
101                     ErrorDialog.openError(display.getActiveShell(), PDEPlugin.getResourceString("FeatureExportJob.error"), PDEPlugin.getResourceString("FeatureExportJob.problems"), e.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
102
done(new Status(IStatus.OK, PDEPlugin.getPluginId(), IStatus.OK, "", null)); //$NON-NLS-1$
103
}
104             });
105             return Job.ASYNC_FINISH;
106         } catch (InvocationTargetException e) {
107             String JavaDoc message = e.getTargetException().getMessage();
108             if (message != null && message.length() > 0) {
109                 errorMessage = e.getTargetException().getMessage();
110             }
111         } finally {
112             if (writer != null)
113                 writer.close();
114         }
115         if (errorMessage == null && logFile != null && logFile.exists() && logFile.length() > 0) {
116             errorMessage = getLogFoundMessage();
117         }
118         
119         if (errorMessage != null) {
120             final String JavaDoc em = errorMessage;
121             getStandardDisplay().asyncExec(new Runnable JavaDoc() {
122                 public void run() {
123                     asyncNotifyExportException(em);
124                 }
125             });
126             return Job.ASYNC_FINISH;
127         }
128         return new Status(IStatus.OK, PDEPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
129
}
130     
131     
132     protected void doExports(IProgressMonitor monitor) throws InvocationTargetException, CoreException {
133         createDestination();
134         monitor.beginTask("", fItems.length + 1); //$NON-NLS-1$
135
try {
136             for (int i = 0; i < fItems.length; i++) {
137                 IFeatureModel model = (IFeatureModel)fItems[i];
138                 try {
139                     IFeature feature = model.getFeature();
140                     String JavaDoc id = feature.getId();
141                     String JavaDoc os = getOS(feature);
142                     String JavaDoc ws = getWS(feature);
143                     String JavaDoc arch = getOSArch(feature);
144                     doExport(id, model.getFeature().getVersion(), model.getInstallLocation(), os, ws, arch, new SubProgressMonitor(monitor, 1));
145                 } finally {
146                     deleteBuildFiles(model);
147                 }
148             }
149         } finally {
150             cleanup(new SubProgressMonitor(monitor, 1));
151             monitor.done();
152         }
153     }
154     
155     private String JavaDoc getOS(IFeature feature) {
156         String JavaDoc os = feature.getOS();
157         if (os == null || os.trim().length() == 0 || os.indexOf(',') != -1 || os.equals("*")) //$NON-NLS-1$
158
return TargetPlatform.getOS();
159         return os;
160     }
161     
162     private String JavaDoc getWS(IFeature feature) {
163         String JavaDoc ws = feature.getWS();
164         if (ws == null || ws.trim().length() == 0 || ws.indexOf(',') != -1 || ws.equals("*")) //$NON-NLS-1$
165
return TargetPlatform.getWS();
166         return ws;
167     }
168     
169     private String JavaDoc getOSArch(IFeature feature) {
170         String JavaDoc arch = feature.getArch();
171         if (arch == null || arch.trim().length() == 0 || arch.indexOf(',') != -1 || arch.equals("*")) //$NON-NLS-1$
172
return TargetPlatform.getOSArch();
173         return arch;
174     }
175     
176     private void createDestination() throws InvocationTargetException {
177         File file = new File(fDestinationDirectory);
178         if (!file.exists() || !file.isDirectory()) {
179             if (!file.mkdirs())
180                 throw new InvocationTargetException(new Exception JavaDoc(PDEPlugin.getResourceString("ExportWizard.badDirectory"))); //$NON-NLS-1$
181
}
182     }
183     
184     protected void doExport(String JavaDoc featureID, String JavaDoc version, String JavaDoc featureLocation, String JavaDoc os, String JavaDoc ws, String JavaDoc arch, IProgressMonitor monitor)
185         throws CoreException, InvocationTargetException {
186         monitor.beginTask("", 5); //$NON-NLS-1$
187
monitor.setTaskName(PDEPlugin.getResourceString("FeatureExportJob.taskName")); //$NON-NLS-1$
188
try {
189             HashMap properties = createBuildProperties(os, ws, arch);
190             makeScript(featureID, version, os, ws, arch, featureLocation);
191             monitor.worked(1);
192             runScript(getBuildScriptName(featureLocation), getBuildExecutionTargets(),
193                     properties, new SubProgressMonitor(monitor, 2));
194             runScript(getAssemblyScriptName(featureID, os, ws, arch, featureLocation), new String JavaDoc[]{"main"}, //$NON-NLS-1$
195
properties, new SubProgressMonitor(monitor, 2));
196         } finally {
197             monitor.done();
198         }
199     }
200
201     protected HashMap createBuildProperties(String JavaDoc os, String JavaDoc ws, String JavaDoc arch) {
202         if (fBuildProperties == null) {
203             fBuildProperties = new HashMap(15);
204             fBuildProperties.put(IXMLConstants.PROPERTY_BUILD_TEMP, fBuildTempLocation + "/destination"); //$NON-NLS-1$
205
fBuildProperties.put(IXMLConstants.PROPERTY_TEMP_FOLDER, fBuildTempLocation + "/temp.folder"); //$NON-NLS-1$
206
fBuildProperties.put(IXMLConstants.PROPERTY_FEATURE_TEMP_FOLDER, fBuildTempLocation + "/destination"); //$NON-NLS-1$
207
fBuildProperties.put(IXMLConstants.PROPERTY_INCLUDE_CHILDREN, "true"); //$NON-NLS-1$
208
fBuildProperties.put("eclipse.running", "true"); //$NON-NLS-1$ //$NON-NLS-2$
209
fBuildProperties.put(IXMLConstants.PROPERTY_BASE_OS, os);
210             fBuildProperties.put(IXMLConstants.PROPERTY_BASE_WS, ws);
211             fBuildProperties.put(IXMLConstants.PROPERTY_BASE_ARCH, arch);
212             fBuildProperties.put(IXMLConstants.PROPERTY_BASE_NL, TargetPlatform.getNL());
213             fBuildProperties.put(IXMLConstants.PROPERTY_BOOTCLASSPATH, BaseBuildAction.getBootClasspath());
214             IPreferenceStore store = PDEPlugin.getDefault().getPreferenceStore();
215             fBuildProperties.put(IXMLConstants.PROPERTY_JAVAC_FAIL_ON_ERROR, "false"); //$NON-NLS-1$
216
fBuildProperties.put(IXMLConstants.PROPERTY_JAVAC_DEBUG_INFO, store.getBoolean(PROP_JAVAC_DEBUG_INFO) ? "on" : "off"); //$NON-NLS-1$ //$NON-NLS-2$
217
fBuildProperties.put(IXMLConstants.PROPERTY_JAVAC_VERBOSE, store.getString(PROP_JAVAC_VERBOSE));
218
219             Preferences pref = JavaCore.getPlugin().getPluginPreferences();
220             fBuildProperties.put(IXMLConstants.PROPERTY_JAVAC_SOURCE, pref.getString(JavaCore.COMPILER_SOURCE));
221             fBuildProperties.put(IXMLConstants.PROPERTY_JAVAC_TARGET, pref.getString(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM));
222             
223             // for the assembler...
224
fBuildProperties.put(IXMLConstants.PROPERTY_BUILD_DIRECTORY, fBuildTempLocation + "/assemblyLocation"); //$NON-NLS-1$
225
fBuildProperties.put(IXMLConstants.PROPERTY_BUILD_LABEL, "."); //$NON-NLS-1$
226
fBuildProperties.put(IXMLConstants.PROPERTY_COLLECTING_FOLDER, "."); //$NON-NLS-1$
227
String JavaDoc prefix = Platform.getOS().equals("macosx") ? "." : ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
228
fBuildProperties.put(IXMLConstants.PROPERTY_ARCHIVE_PREFIX, prefix);
229             if (fExportType == EXPORT_AS_ZIP)
230                 fBuildProperties.put(IXMLConstants.PROPERTY_ARCHIVE_FULLPATH, fDestinationDirectory + File.separator + fZipFilename);
231             else
232                 fBuildProperties.put(IXMLConstants.PROPERTY_ASSEMBLY_TMP, fDestinationDirectory);
233         }
234         return fBuildProperties;
235     }
236     
237     private void makeScript(String JavaDoc featureID, String JavaDoc versionId, String JavaDoc os, String JavaDoc ws, String JavaDoc arch, String JavaDoc featureLocation) throws CoreException {
238         BuildScriptGenerator generator = new BuildScriptGenerator();
239         generator.setBuildingOSGi(PDECore.getDefault().getModelManager().isOSGiRuntime());
240         generator.setChildren(true);
241         generator.setWorkingDirectory(featureLocation);
242         generator.setDevEntries(getDevProperties());
243         generator.setElements(new String JavaDoc[] {"feature@" + featureID + (versionId == null ? "" : ":" + versionId)}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
244
generator.setPluginPath(getPaths());
245         String JavaDoc format;
246         if (fExportType == EXPORT_AS_ZIP)
247             format = Platform.getOS().equals("macosx") ? "tarGz" : "antZip"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
248
else
249             format = "folder"; //$NON-NLS-1$
250
BuildScriptGenerator.setOutputFormat(format);
251         BuildScriptGenerator.setForceUpdateJar(fExportType == EXPORT_AS_UPDATE_JARS);
252         BuildScriptGenerator.setEmbeddedSource(fExportSource && fExportType != EXPORT_AS_UPDATE_JARS);
253         BuildScriptGenerator.setConfigInfo(os + "," + ws + "," + arch); //$NON-NLS-1$ //$NON-NLS-2$
254
generator.generate();
255     }
256     
257     private String JavaDoc getDevProperties() {
258         if (fDevProperties == null) {
259             fDevProperties = ClasspathHelper.getDevEntriesProperties(fBuildTempLocation + "/dev.properties", false); //$NON-NLS-1$
260
}
261         return fDevProperties;
262     }
263
264     protected void runScript(String JavaDoc location, String JavaDoc[] targets, Map properties,
265             IProgressMonitor monitor) throws InvocationTargetException, CoreException {
266         AntRunner runner = new AntRunner();
267         runner.addUserProperties(properties);
268         runner.setAntHome(location);
269         runner.setBuildFileLocation(location);
270         runner.addBuildListener("org.eclipse.pde.internal.ui.ant.ExportBuildListener"); //$NON-NLS-1$
271
runner.setExecutionTargets(targets);
272         runner.run(monitor);
273     }
274
275     private String JavaDoc getBuildScriptName(String JavaDoc featureLocation) {
276         return featureLocation + Path.SEPARATOR + "build.xml"; //$NON-NLS-1$
277
}
278     
279     protected String JavaDoc getAssemblyScriptName(String JavaDoc featureID, String JavaDoc os, String JavaDoc ws, String JavaDoc arch, String JavaDoc featureLocation) {
280         return featureLocation + Path.SEPARATOR + "assemble." //$NON-NLS-1$
281
+ featureID + "." + os + "." //$NON-NLS-1$ //$NON-NLS-2$
282
+ ws + "." + arch //$NON-NLS-1$
283
+ ".xml"; //$NON-NLS-1$
284
}
285     
286     private String JavaDoc[] getBuildExecutionTargets() {
287         if (fExportSource && fExportType != EXPORT_AS_UPDATE_JARS)
288             return new String JavaDoc[] {"build.jars", "build.sources", "gather.logs"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
289
return new String JavaDoc[] {"build.jars", "gather.logs"}; //$NON-NLS-1$ //$NON-NLS-2$
290
}
291
292     public void deleteBuildFiles(IModel model) throws CoreException {
293         if (model == null)
294             return;
295         
296         String JavaDoc directory =
297             (model instanceof IFeatureModel)
298                 ? ((IFeatureModel) model).getInstallLocation()
299                 : ((IPluginModelBase) model).getInstallLocation();
300                 
301         if (model.getUnderlyingResource() != null && !isCustomBuild(model)) {
302             File dir = new File(directory);
303             File[] children = dir.listFiles();
304             if (children != null) {
305                 for (int i = 0; i < children.length; i++) {
306                     if (!children[i].isDirectory()) {
307                         String JavaDoc filename = children[i].getName();
308                         if (filename.equals("build.xml") || //$NON-NLS-1$
309
(filename.startsWith("assemble.") && filename.endsWith(".xml"))) { //$NON-NLS-1$ //$NON-NLS-2$
310
children[i].delete();
311                         }
312                     }
313                 }
314             }
315         }
316         
317         if (model instanceof IFeatureModel) {
318             IFeature feature = ((IFeatureModel)model).getFeature();
319             IFeatureChild[] children = feature.getIncludedFeatures();
320             for (int i = 0; i < children.length; i++) {
321                 IFeature ref = ((FeatureChild)children[i]).getReferencedFeature();
322                 if (ref != null) {
323                     deleteBuildFiles(ref.getModel());
324                 }
325             }
326             
327             IFeaturePlugin[] plugins = feature.getPlugins();
328             PluginModelManager manager = PDECore.getDefault().getModelManager();
329             for (int i = 0; i < plugins.length; i++) {
330                 ModelEntry entry = manager.findEntry(plugins[i].getId());
331                 if (entry != null) {
332                     deleteBuildFiles(entry.getActiveModel());
333                 }
334             }
335         }
336     }
337
338     protected boolean isCustomBuild(IModel model) throws CoreException {
339         IBuildModel buildModel = null;
340         IFile buildFile = model.getUnderlyingResource().getProject().getFile("build.properties"); //$NON-NLS-1$
341
if (buildFile.exists()) {
342             buildModel = new WorkspaceBuildModel(buildFile);
343             buildModel.load();
344         }
345         if (buildModel != null) {
346             IBuild build = buildModel.getBuild();
347             IBuildEntry entry = build.getEntry("custom"); //$NON-NLS-1$
348
if (entry != null) {
349                 String JavaDoc[] tokens = entry.getTokens();
350                 for (int i = 0; i < tokens.length; i++) {
351                     if (tokens[i].equals("true")) //$NON-NLS-1$
352
return true;
353                 }
354             }
355         }
356         return false;
357     }
358
359     protected String JavaDoc[] getPaths() throws CoreException {
360         ArrayList paths = new ArrayList();
361         IFeatureModel[] models = PDECore.getDefault().getWorkspaceModelManager().getFeatureModels();
362         for (int i = 0; i < models.length; i++) {
363             paths.add(models[i].getInstallLocation() + Path.SEPARATOR + "feature.xml"); //$NON-NLS-1$
364
}
365         
366         String JavaDoc[] plugins = TargetPlatform.createPluginPath();
367         String JavaDoc[] features = (String JavaDoc[]) paths.toArray(new String JavaDoc[paths.size()]);
368         String JavaDoc[] all = new String JavaDoc[plugins.length + paths.size()];
369         System.arraycopy(plugins, 0, all, 0, plugins.length);
370         System.arraycopy(features, 0, all, plugins.length, features.length);
371         return all;
372     }
373
374     private static void createLogWriter() {
375         try {
376             String JavaDoc path = PDEPlugin.getDefault().getStateLocation().toOSString();
377             logFile = new File(path, "exportLog.txt"); //$NON-NLS-1$
378
if (logFile.exists()) {
379                 logFile.delete();
380                 logFile.createNewFile();
381             }
382             writer = new PrintWriter(new FileWriter(logFile), true);
383         } catch (IOException e) {
384         }
385     }
386     
387     public static PrintWriter getWriter() {
388         if (writer == null)
389             createLogWriter();
390         return writer;
391     }
392     
393     protected void cleanup(IProgressMonitor monitor) {
394         File scriptFile = null;
395         try {
396             scriptFile = createScriptFile();
397             writer = new PrintWriter(new FileWriter(scriptFile), true);
398             generateHeader(writer);
399             generateDeleteZipTarget(writer);
400             generateCleanTarget(writer);
401             boolean errors = generateZipLogsTarget(writer);
402             generateClosingTag(writer);
403             writer.close();
404             
405             ArrayList targets = new ArrayList();
406             targets.add("deleteZip"); //$NON-NLS-1$
407
if (errors)
408                 targets.add("zip.logs"); //$NON-NLS-1$
409
targets.add("clean"); //$NON-NLS-1$
410
AntRunner runner = new AntRunner();
411             runner.setBuildFileLocation(scriptFile.getAbsolutePath());
412             runner.setExecutionTargets((String JavaDoc[]) targets.toArray(new String JavaDoc[targets.size()]));
413             runner.run(monitor);
414         } catch (IOException e) {
415         } catch (CoreException e) {
416         } finally {
417             if (scriptFile != null && scriptFile.exists())
418                 scriptFile.delete();
419         }
420     }
421     private File createScriptFile() throws IOException {
422         String JavaDoc path = PDEPlugin.getDefault().getStateLocation().toOSString();
423         File zip = new File(path, "zip.xml"); //$NON-NLS-1$
424
if (zip.exists()) {
425             zip.delete();
426             zip.createNewFile();
427         }
428         return zip;
429     }
430     private void generateHeader(PrintWriter writer) {
431         writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); //$NON-NLS-1$
432
writer.println("<project name=\"temp\" default=\"clean\" basedir=\".\">"); //$NON-NLS-1$
433
}
434     private void generateCleanTarget(PrintWriter writer) {
435         writer.println("<target name=\"clean\">"); //$NON-NLS-1$
436
writer.println("<delete dir=\"" + fBuildTempLocation + "\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
437
writer.println("</target>"); //$NON-NLS-1$
438
}
439     private void generateDeleteZipTarget(PrintWriter writer) {
440         writer.println("<target name=\"deleteZip\">"); //$NON-NLS-1$
441
writer.println("<delete file=\"" + fDestinationDirectory + "/logs.zip\"/>"); //$NON-NLS-1$ //$NON-NLS-2$
442
writer.println("</target>"); //$NON-NLS-1$
443
}
444     
445     private boolean generateZipLogsTarget(PrintWriter writer) {
446         if (logFile != null && logFile.exists() && logFile.length() > 0) {
447             writer.println("<target name=\"zip.logs\">"); //$NON-NLS-1$
448
writer.println("<zip zipfile=\"" + fDestinationDirectory + "/logs.zip\" basedir=\"" + fBuildTempLocation + "/temp.folder\"/>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
449
writer.println("</target>"); //$NON-NLS-1$
450
return true;
451         }
452         return false;
453     }
454     private void generateClosingTag(PrintWriter writer) {
455         writer.println("</project>"); //$NON-NLS-1$
456
}
457     /**
458      * Returns the standard display to be used. The method first checks, if the
459      * thread calling this method has an associated disaply. If so, this display
460      * is returned. Otherwise the method returns the default display.
461      */

462     public static Display getStandardDisplay() {
463         Display display;
464         display = Display.getCurrent();
465         if (display == null)
466             display = Display.getDefault();
467         return display;
468     }
469     
470     private void asyncNotifyExportException(String JavaDoc errorMessage) {
471         getStandardDisplay().beep();
472         MessageDialog.openError(PDEPlugin.getActiveWorkbenchShell(), PDEPlugin.getResourceString("FeatureExportJob.error"), errorMessage); //$NON-NLS-1$
473
done(new Status(IStatus.OK, PDEPlugin.getPluginId(), IStatus.OK, "", null)); //$NON-NLS-1$
474
}
475     
476     protected String JavaDoc getLogFoundMessage() {
477         return PDEPlugin.getFormattedMessage("ExportJob.error.message", fDestinationDirectory + File.separator + "logs.zip"); //$NON-NLS-1$ //$NON-NLS-2$
478
}
479 }
480
Popular Tags