KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > build > AbstractScriptGenerator


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  *******************************************************************************/

11 package org.eclipse.pde.internal.build;
12
13 import java.io.*;
14 import java.util.*;
15 import org.eclipse.core.runtime.*;
16 import org.eclipse.osgi.service.resolver.BundleDescription;
17 import org.eclipse.osgi.service.resolver.State;
18 import org.eclipse.osgi.util.NLS;
19 import org.eclipse.pde.internal.build.ant.AntScript;
20 import org.eclipse.pde.internal.build.site.*;
21 import org.eclipse.update.core.*;
22
23 /**
24  * Generic super-class for all script generator classes.
25  * It contains basic informations like the script, the configurations, and a location
26  */

27 public abstract class AbstractScriptGenerator implements IXMLConstants, IPDEBuildConstants, IBuildPropertiesConstants {
28     private static Properties immutableAntProperties = null;
29     protected static boolean embeddedSource = false;
30     protected static boolean forceUpdateJarFormat = false;
31     private static List configInfos;
32     protected static String JavaDoc workingDirectory;
33     protected static boolean buildingOSGi = true;
34     protected AntScript script;
35     protected Properties platformProperties;
36
37     private static PDEUIStateWrapper pdeUIState;
38
39     /** Location of the plug-ins and fragments. */
40     protected String JavaDoc[] sitePaths;
41     protected String JavaDoc[] pluginPath;
42     protected BuildTimeSiteFactory siteFactory;
43
44     /**
45      * Indicate whether the content of the pdestate should only contain the plugins that are in the transitive closure of the features being built
46      */

47     protected boolean filterState = false;
48     protected List featuresForFilterRoots = new ArrayList();
49     protected List pluginsForFilterRoots = new ArrayList();
50
51     protected boolean reportResolutionErrors;
52     
53     static {
54         // By default, a generic configuration is set
55
configInfos = new ArrayList(1);
56         configInfos.add(Config.genericConfig());
57     }
58
59     public static List getConfigInfos() {
60         return configInfos;
61     }
62
63     /**
64      * Starting point for script generation. See subclass implementations for
65      * individual comments.
66      *
67      * @throws CoreException
68      */

69     public abstract void generate() throws CoreException;
70
71     protected static void setStaticAntProperties(Properties properties) {
72         if (properties == null)
73             immutableAntProperties = new Properties();
74         else
75             immutableAntProperties = properties;
76         if (getImmutableAntProperty(IBuildPropertiesConstants.PROPERTY_PACKAGER_MODE) == null) {
77             immutableAntProperties.setProperty(IBuildPropertiesConstants.PROPERTY_PACKAGER_MODE, "false"); //$NON-NLS-1$
78
}
79         //When we are generating build scripts, the normalization needs to be set, and when doing packaging the default is to set normalization to true for backward compatibility
80
if (!getPropertyAsBoolean(IBuildPropertiesConstants.PROPERTY_PACKAGER_MODE) || getImmutableAntProperty(IBuildPropertiesConstants.PROPERTY_PACKAGER_AS_NORMALIZER) == null) {
81             immutableAntProperties.setProperty(IBuildPropertiesConstants.PROPERTY_PACKAGER_AS_NORMALIZER, "true"); //$NON-NLS-1$
82
}
83     }
84
85     public static String JavaDoc getImmutableAntProperty(String JavaDoc key) {
86         return getImmutableAntProperty(key, null);
87     }
88
89     public static boolean getPropertyAsBoolean(String JavaDoc key) {
90         String JavaDoc booleanValue = getImmutableAntProperty(key, null);
91         if ("true".equalsIgnoreCase(booleanValue))
92             return true;
93         else
94             return false;
95     }
96     
97     public static String JavaDoc getImmutableAntProperty(String JavaDoc key, String JavaDoc defaultValue) {
98         if (immutableAntProperties == null || !immutableAntProperties.containsKey(key))
99             return defaultValue;
100         Object JavaDoc obj = immutableAntProperties.get(key);
101         return (obj instanceof String JavaDoc) ? (String JavaDoc) obj : null;
102     }
103
104     public static void setConfigInfo(String JavaDoc spec) throws CoreException {
105         configInfos.clear();
106         String JavaDoc[] configs = Utils.getArrayFromStringWithBlank(spec, "&"); //$NON-NLS-1$
107
configInfos = new ArrayList(configs.length);
108         String JavaDoc[] os = new String JavaDoc[configs.length];
109         String JavaDoc[] ws = new String JavaDoc[configs.length];
110         String JavaDoc[] archs = new String JavaDoc[configs.length];
111         for (int i = 0; i < configs.length; i++) {
112             String JavaDoc[] configElements = Utils.getArrayFromStringWithBlank(configs[i], ","); //$NON-NLS-1$
113
if (configElements.length != 3) {
114                 IStatus error = new Status(IStatus.ERROR, IPDEBuildConstants.PI_PDEBUILD, IPDEBuildConstants.EXCEPTION_CONFIG_FORMAT, NLS.bind(Messages.error_configWrongFormat, configs[i]), null);
115                 throw new CoreException(error);
116             }
117             Config aConfig = new Config(configs[i]);
118             if (aConfig.equals(Config.genericConfig()))
119                 configInfos.add(Config.genericConfig());
120             else
121                 configInfos.add(aConfig);
122
123             // create a list of all ws, os and arch to feed the SiteManager
124
os[i] = aConfig.getOs();
125             ws[i] = aConfig.getWs();
126             archs[i] = aConfig.getArch();
127         }
128         SiteManager.setOS(Utils.getStringFromArray(os, ",")); //$NON-NLS-1$
129
SiteManager.setWS(Utils.getStringFromArray(ws, ",")); //$NON-NLS-1$
130
SiteManager.setOSArch(Utils.getStringFromArray(archs, ",")); //$NON-NLS-1$
131
}
132
133     public void setWorkingDirectory(String JavaDoc location) {
134         workingDirectory = location;
135     }
136
137     /**
138      * Return the file system location for the given plug-in model object.
139      *
140      * @param model the plug-in
141      * @return String
142      */

143     public String JavaDoc getLocation(BundleDescription model) {
144         return model.getLocation();
145     }
146
147     static public class MissingProperties extends Properties {
148         private static final long serialVersionUID = 3546924667060303927L;
149         private static MissingProperties singleton;
150
151         private MissingProperties() {
152             //nothing to do;
153
}
154
155         public synchronized Object JavaDoc setProperty(String JavaDoc key, String JavaDoc value) {
156             throw new UnsupportedOperationException JavaDoc();
157         }
158
159         public synchronized Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
160             throw new UnsupportedOperationException JavaDoc();
161         }
162
163         public static MissingProperties getInstance() {
164             if (singleton == null)
165                 singleton = new MissingProperties();
166             return singleton;
167         }
168     }
169
170     public static Properties readProperties(String JavaDoc location, String JavaDoc fileName, int errorLevel) throws CoreException {
171         Properties result = new Properties();
172         File file = new File(location, fileName);
173         try {
174             InputStream input = new BufferedInputStream(new FileInputStream(file));
175             try {
176                 result.load(input);
177             } finally {
178                 input.close();
179             }
180         } catch (FileNotFoundException e) {
181             if (errorLevel != IStatus.INFO && errorLevel != IStatus.OK) {
182                 String JavaDoc message = NLS.bind(Messages.exception_missingFile, file);
183                 BundleHelper.getDefault().getLog().log(new Status(errorLevel, PI_PDEBUILD, EXCEPTION_READING_FILE, message, null));
184             }
185             result = MissingProperties.getInstance();
186         } catch (IOException e) {
187             String JavaDoc message = NLS.bind(Messages.exception_readingFile, file);
188             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_READING_FILE, message, e));
189         }
190         return result;
191     }
192
193     public void openScript(String JavaDoc scriptLocation, String JavaDoc scriptName) throws CoreException {
194         if (script != null)
195             return;
196
197         try {
198             OutputStream scriptStream = new BufferedOutputStream(new FileOutputStream(scriptLocation + '/' + scriptName));
199             try {
200                 script = new AntScript(scriptStream);
201             } catch (IOException e) {
202                 try {
203                     scriptStream.close();
204                     String JavaDoc message = NLS.bind(Messages.exception_writingFile, scriptLocation + '/' + scriptName);
205                     throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_FILE, message, e));
206                 } catch (IOException e1) {
207                     // Ignored
208
}
209             }
210         } catch (FileNotFoundException e) {
211             String JavaDoc message = NLS.bind(Messages.exception_writingFile, scriptLocation + '/' + scriptName);
212             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_FILE, message, e));
213         }
214     }
215
216     public void closeScript() {
217         script.close();
218     }
219
220     public void setBuildingOSGi(boolean b) {
221         buildingOSGi = b;
222     }
223
224     public static boolean isBuildingOSGi() {
225         return buildingOSGi;
226     }
227
228     public static String JavaDoc getWorkingDirectory() {
229         return workingDirectory;
230     }
231
232     public static String JavaDoc getDefaultOutputFormat() {
233         return "zip"; //$NON-NLS-1$
234
}
235
236     public static boolean getDefaultEmbeddedSource() {
237         return false;
238     }
239
240     public static void setEmbeddedSource(boolean embed) {
241         embeddedSource = embed;
242     }
243
244     public static boolean getForceUpdateJarFormat() {
245         return false;
246     }
247
248     public static void setForceUpdateJar(boolean force) {
249         forceUpdateJarFormat = force;
250     }
251
252     public static String JavaDoc getDefaultConfigInfos() {
253         return "*, *, *"; //$NON-NLS-1$
254
}
255
256     public static boolean getDefaultBuildingOSGi() {
257         return true;
258     }
259
260     /**
261      * Return a build time site referencing things to be built.
262      * @param refresh : indicate if a refresh must be performed. Although this flag is set to true, a new site is not rebuild if the urls of the site did not changed
263      * @return BuildTimeSite
264      * @throws CoreException
265      */

266     public BuildTimeSite getSite(boolean refresh) throws CoreException {
267         if (siteFactory != null && refresh == false)
268             return (BuildTimeSite) siteFactory.createSite();
269
270         if (siteFactory == null || refresh == true) {
271             siteFactory = new BuildTimeSiteFactory();
272             siteFactory.setFilterState(filterState);
273             siteFactory.setFilterRoots(featuresForFilterRoots, pluginsForFilterRoots);
274             siteFactory.setReportResolutionErrors(reportResolutionErrors);
275         }
276
277         siteFactory.setSitePaths(getPaths());
278         siteFactory.setInitialState(pdeUIState);
279         BuildTimeSite result = (BuildTimeSite) siteFactory.createSite();
280         if (platformProperties != null)
281             result.setPlatformPropeties(platformProperties);
282         return result;
283     }
284
285     /**
286      * Method getPaths. These are the paths used for the BuildTimeSite
287      * @return URL[]
288      */

289     private String JavaDoc[] getPaths() {
290         if (sitePaths == null) {
291             if (pluginPath != null) {
292                 sitePaths = new String JavaDoc[pluginPath.length + 1];
293                 System.arraycopy(pluginPath, 0, sitePaths, 0, pluginPath.length);
294                 sitePaths[sitePaths.length - 1] = workingDirectory;
295             } else {
296                 sitePaths = new String JavaDoc[] {workingDirectory};
297             }
298         }
299
300         return sitePaths;
301     }
302
303     public void setBuildSiteFactory(BuildTimeSiteFactory siteFactory) {
304         this.siteFactory = siteFactory;
305     }
306
307     /**
308      * Return the path of the plugins //TODO Do we need to add support for features, or do we simply consider one list of URL? It is just a matter of style/
309      * @return URL[]
310      */

311     public String JavaDoc[] getPluginPath() {
312         return pluginPath;
313     }
314
315     /**
316      * Sets the pluginPath.
317      *
318      * @param path
319      */

320     public void setPluginPath(String JavaDoc[] path) {
321         pluginPath = path;
322     }
323
324     public void setPDEState(State state) {
325         ensurePDEUIStateNotNull();
326         pdeUIState.setState(state);
327     }
328
329     public void setStateExtraData(HashMap classpath, Map patchData) {
330         ensurePDEUIStateNotNull();
331         pdeUIState.setExtraData(classpath, patchData);
332     }
333
334     public void setNextId(long nextId) {
335         ensurePDEUIStateNotNull();
336         pdeUIState.setNextId(nextId);
337     }
338
339     protected void flushState() {
340         pdeUIState = null;
341     }
342
343     private void ensurePDEUIStateNotNull() {
344         if (pdeUIState == null)
345             pdeUIState = new PDEUIStateWrapper();
346     }
347
348     protected boolean havePDEUIState() {
349         return pdeUIState != null;
350     }
351
352     //Find a file in a bundle or a feature.
353
//location is assumed to be structured like : /<featureId | pluginId>/path.to.the.file
354
protected String JavaDoc findFile(String JavaDoc location, boolean makeRelative) {
355         if (location == null || location.length() == 0)
356             return null;
357         PDEState state;
358         try {
359             state = getSite(false).getRegistry();
360         } catch (CoreException e) {
361             return null;
362         }
363         Path path = new Path(location);
364         String JavaDoc id = path.segment(0);
365         BundleDescription[] matches = state.getState().getBundles(id);
366         if (matches != null && matches.length != 0) {
367             BundleDescription bundle = matches[0];
368             if (bundle != null) {
369                 String JavaDoc result = checkFile(new Path(bundle.getLocation()), path, makeRelative);
370                 if (result != null)
371                     return result;
372             }
373         }
374         // Couldn't find the file in any of the plugins, try in a feature.
375
IFeature feature = null;
376         try {
377             feature = getSite(false).findFeature(id, null, false);
378         } catch (CoreException e) {
379             //Ignore
380
}
381         if (feature == null)
382             return null;
383         ISiteFeatureReference ref = feature.getSite().getFeatureReference(feature);
384         IPath featureBase = new Path(ref.getURL().getFile()).removeLastSegments(1);
385         return checkFile(featureBase, path, makeRelative);
386     }
387
388     private String JavaDoc checkFile(IPath base, Path target, boolean makeRelative) {
389         IPath path = base.append(target.removeFirstSegments(1));
390         String JavaDoc result = path.toOSString();
391         if (!new File(result).exists())
392             return null;
393         if (makeRelative)
394             return Utils.makeRelative(path, new Path(workingDirectory)).toOSString();
395         return result;
396     }
397
398     public void setFilterState(boolean filter) {
399         filterState = filter;
400     }
401
402     /*
403      * If the user has specified a platform properties then load it.
404      */

405     public void setPlatformProperties(String JavaDoc filename) {
406         if (filename == null || filename.trim().length() == 0)
407             return;
408         File file = new File(filename);
409         if (!file.exists())
410             return;
411         platformProperties = new Properties();
412         InputStream input = null;
413         try {
414             input = new BufferedInputStream(new FileInputStream(file));
415             platformProperties.load(input);
416         } catch (IOException e) {
417             platformProperties = null;
418             String JavaDoc message = NLS.bind(Messages.error_loading_platform_properties, filename);
419             IStatus status = new Status(IStatus.WARNING, IPDEBuildConstants.PI_PDEBUILD, message, e);
420             BundleHelper.getDefault().getLog().log(status);
421         } finally {
422             if (input != null)
423                 try {
424                     input.close();
425                 } catch (IOException e) {
426                     // ignore
427
}
428         }
429     }
430     
431 }
432
Popular Tags