KickJava   Java API By Example, From Geeks To Geeks.

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


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.net.MalformedURLException JavaDoc;
15 import java.net.URL JavaDoc;
16 import java.util.*;
17 import org.eclipse.core.runtime.*;
18 import org.eclipse.osgi.service.resolver.BundleDescription;
19 import org.eclipse.osgi.util.NLS;
20 import org.eclipse.pde.internal.build.ant.AntScript;
21 import org.eclipse.update.core.IFeature;
22 import org.eclipse.update.core.IPluginEntry;
23 import org.osgi.framework.Version;
24
25 /**
26  * General utility class.
27  */

28 public final class Utils implements IPDEBuildConstants, IBuildPropertiesConstants, IXMLConstants {
29     /**
30      * Convert a list of tokens into an array. The list separator has to be
31      * specified.
32      */

33     public static String JavaDoc[] getArrayFromString(String JavaDoc list, String JavaDoc separator) {
34         if (list == null || list.trim().equals("")) //$NON-NLS-1$
35
return new String JavaDoc[0];
36         List result = new ArrayList();
37         for (StringTokenizer tokens = new StringTokenizer(list, separator); tokens.hasMoreTokens();) {
38             String JavaDoc token = tokens.nextToken().trim();
39             if (!token.equals("")) //$NON-NLS-1$
40
result.add(token);
41         }
42         return (String JavaDoc[]) result.toArray(new String JavaDoc[result.size()]);
43     }
44
45     /**
46      * Convert a list of tokens into an array. The list separator has to be
47      * specified. The spcecificity of this method is that it returns an empty
48      * element when to same separators are following each others. For example
49      * the string a,,b returns the following array [a, ,b]
50      *
51      */

52     public static String JavaDoc[] getArrayFromStringWithBlank(String JavaDoc list, String JavaDoc separator) {
53         if (list == null || list.trim().length() == 0)
54             return new String JavaDoc[0];
55         List result = new ArrayList();
56         boolean previousWasSeparator = true;
57         for (StringTokenizer tokens = new StringTokenizer(list, separator, true); tokens.hasMoreTokens();) {
58             String JavaDoc token = tokens.nextToken().trim();
59             if (token.equals(separator)) {
60                 if (previousWasSeparator)
61                     result.add(""); //$NON-NLS-1$
62
previousWasSeparator = true;
63             } else {
64                 result.add(token);
65                 previousWasSeparator = false;
66             }
67         }
68         return (String JavaDoc[]) result.toArray(new String JavaDoc[result.size()]);
69     }
70
71     /**
72      * Return a string array constructed from the given list of comma-separated
73      * tokens.
74      *
75      * @param list
76      * the list to convert
77      * @return the array of strings
78      */

79     public static String JavaDoc[] getArrayFromString(String JavaDoc list) {
80         return getArrayFromString(list, ","); //$NON-NLS-1$
81
}
82
83     /**
84      * Converts an array of strings into an array of URLs.
85      *
86      * @param target
87      * @return URL[]
88      * @throws CoreException
89      */

90     public static URL JavaDoc[] asURL(String JavaDoc[] target) throws CoreException {
91         if (target == null)
92             return null;
93         try {
94             URL JavaDoc[] result = new URL JavaDoc[target.length];
95             for (int i = 0; i < target.length; i++)
96                 result[i] = new URL JavaDoc(target[i]);
97             return result;
98         } catch (MalformedURLException JavaDoc e) {
99             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_MALFORMED_URL, e.getMessage(), e));
100         }
101     }
102
103     public static URL JavaDoc[] asURL(Collection target) throws CoreException {
104         if (target == null)
105             return null;
106         try {
107             URL JavaDoc[] result = new URL JavaDoc[target.size()];
108             int i = 0;
109             for (Iterator iter = target.iterator(); iter.hasNext();) {
110                 result[i++] = ((File) iter.next()).toURL();
111             }
112             return result;
113         } catch (MalformedURLException JavaDoc e) {
114             throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_MALFORMED_URL, e.getMessage(), e));
115         }
116     }
117
118     public static File[] asFile(String JavaDoc[] target) {
119         if (target == null)
120             return new File[0];
121         File[] result = new File[target.length];
122         for (int i = 0; i < result.length; i++) {
123             result[i] = new File(target[i]);
124         }
125         return result;
126     }
127     
128     public static File[] asFile(URL JavaDoc[] target) {
129         if (target == null)
130             return new File[0];
131         File[] result = new File[target.length];
132         for (int i = 0; i < result.length; i++) {
133             result[i] = new File(target[i].getFile());
134         }
135         return result;
136     }
137     
138     /**
139      * Return a string which is a concatination of each member of the given
140      * collection, separated by the given separator.
141      *
142      * @param collection
143      * the collection to concatinate
144      * @param separator
145      * the separator to use
146      * @return String
147      */

148     public static String JavaDoc getStringFromCollection(Collection collection, String JavaDoc separator) {
149         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
150         boolean first = true;
151         for (Iterator i = collection.iterator(); i.hasNext();) {
152             if (first)
153                 first = false;
154             else
155                 result.append(separator);
156             result.append(i.next());
157         }
158         return result.toString();
159     }
160
161     /**
162      * Return a string which is a concatination of each member of the given
163      * array, separated by the given separator.
164      *
165      * @param values
166      * the array to concatinate
167      * @param separator
168      * the separator to use
169      * @return String
170      */

171     public static String JavaDoc getStringFromArray(String JavaDoc[] values, String JavaDoc separator) {
172         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
173         for (int i = 0; i < values.length; i++) {
174             if (values[i] != null) {
175                 if (i > 0)
176                     result.append(separator);
177                 result.append(values[i]);
178             }
179         }
180         return result.toString();
181     }
182
183     /**
184      * Return a path which is equivalent to the given location relative to the
185      * specified base path.
186      *
187      * @param location
188      * the location to convert
189      * @param base
190      * the base path
191      * @return IPath
192      */

193     public static IPath makeRelative(IPath location, IPath base) {
194         //can't make relative if the devices don't match
195
if (location.getDevice() == null) {
196             if (base.getDevice() != null)
197                 return location;
198         } else {
199             if (!location.getDevice().equalsIgnoreCase(base.getDevice()))
200                 return location;
201         }
202         int baseCount = base.segmentCount();
203         int count = base.matchingFirstSegments(location);
204         String JavaDoc temp = ""; //$NON-NLS-1$
205
for (int j = 0; j < baseCount - count; j++)
206             temp += "../"; //$NON-NLS-1$
207
return new Path(temp).append(location.removeFirstSegments(count));
208     }
209
210     /**
211      * Transfers all available bytes from the given input stream to the given
212      * output stream. Regardless of failure, this method closes both streams.
213      *
214      * @param source
215      * @param destination
216      * @throws IOException
217      */

218     public static void transferStreams(InputStream source, OutputStream destination) throws IOException {
219         source = new BufferedInputStream(source);
220         destination = new BufferedOutputStream(destination);
221         try {
222             byte[] buffer = new byte[8192];
223             while (true) {
224                 int bytesRead = -1;
225                 if ((bytesRead = source.read(buffer)) == -1)
226                     break;
227                 destination.write(buffer, 0, bytesRead);
228             }
229         } finally {
230             try {
231                 source.close();
232             } catch (IOException e) {
233                 // ignore
234
}
235             try {
236                 destination.close();
237             } catch (IOException e) {
238                 // ignore
239
}
240         }
241     }
242
243     public static IPluginEntry[] getPluginEntry(IFeature feature, String JavaDoc pluginId, boolean raw) {
244         IPluginEntry[] plugins;
245         if (raw)
246             plugins = feature.getRawPluginEntries();
247         else
248             plugins = feature.getPluginEntries();
249         List foundEntries = new ArrayList(5);
250
251         for (int i = 0; i < plugins.length; i++) {
252             if (plugins[i].getVersionedIdentifier().getIdentifier().equals(pluginId))
253                 foundEntries.add(plugins[i]);
254         }
255         return (IPluginEntry[]) foundEntries.toArray(new IPluginEntry[foundEntries.size()]);
256
257     }
258
259     // Return a collection of File, the result can be null
260
public static Collection findFiles(File from, String JavaDoc foldername, final String JavaDoc filename) {
261         // if from is a file which name match filename, then simply return the
262
// file
263
File root = from;
264         if (root.isFile() && root.getName().equals(filename)) {
265             Collection coll = new ArrayList(1);
266             coll.add(root);
267             return coll;
268         }
269
270         Collection collectedElements = new ArrayList(10);
271
272         File[] featureDirectoryContent = new File(from, foldername).listFiles();
273         if (featureDirectoryContent == null)
274             return null;
275
276         for (int i = 0; i < featureDirectoryContent.length; i++) {
277             if (featureDirectoryContent[i].isDirectory()) {
278                 File[] featureFiles = featureDirectoryContent[i].listFiles(new FilenameFilter() {
279                     public boolean accept(File dir, String JavaDoc name) {
280                         return name.equals(filename);
281                     }
282                 });
283                 if (featureFiles.length != 0)
284                     collectedElements.add(featureFiles[0]);
285             }
286         }
287         return collectedElements;
288     }
289
290     public static boolean isIn(IPluginEntry[] array, IPluginEntry element) {
291         for (int i = 0; i < array.length; i++) {
292             if (array[i].getVersionedIdentifier().equals(element.getVersionedIdentifier()))
293                 return true;
294         }
295         return false;
296     }
297
298     public static Collection copyFiles(String JavaDoc fromDir, String JavaDoc toDir) throws CoreException {
299         File templateLocation = new File(fromDir);
300         Collection copiedFiles = new ArrayList();
301         if (templateLocation.exists()) {
302             File[] files = templateLocation.listFiles();
303             if (files != null) {
304                 for (int i = 0; i < files.length; i++) {
305                     if (files[i].isDirectory()) {
306                         File subDir = new File(toDir, files[i].getName());
307                         if(!subDir.exists())
308                             subDir.mkdirs();
309                         Collection subFiles = copyFiles(fromDir + '/' + files[i].getName(), toDir+ '/' + files[i].getName());
310                         for (Iterator iter = subFiles.iterator(); iter.hasNext();) {
311                             String JavaDoc sub = (String JavaDoc) iter.next();
312                             copiedFiles.add(files[i].getName() + '/' + sub);
313                         }
314                         continue;
315                     }
316
317                     FileInputStream inputStream = null;
318                     FileOutputStream outputStream = null;
319
320                     try {
321                         inputStream = new FileInputStream(files[i]);
322                     } catch (FileNotFoundException e) {
323                         String JavaDoc message = NLS.bind(Messages.exception_missingFile, files[i].getAbsolutePath());
324                         throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_READING_FILE, message, e));
325                     }
326
327                     String JavaDoc fileToCopy = toDir + '/' + files[i].getName();
328                     try {
329                         outputStream = new FileOutputStream(fileToCopy);
330                     } catch (FileNotFoundException e) {
331                         String JavaDoc message = NLS.bind(Messages.exception_missingFile, fileToCopy);
332                         throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_READING_FILE, message, e));
333                     }
334
335                     try {
336                         Utils.transferStreams(inputStream, outputStream);
337                         copiedFiles.add(files[i].getName());
338                     } catch (IOException e) {
339                         String JavaDoc message = NLS.bind(Messages.exception_writingFile, fileToCopy);
340                         throw new CoreException(new Status(IStatus.ERROR, PI_PDEBUILD, EXCEPTION_WRITING_FILE, message, e));
341                     }
342                 }
343             }
344         }
345         return copiedFiles;
346     }
347
348     public static List extractPlugins(List initialList, List toExtract) {
349         //TODO This algorithm needs to be improved
350
if (initialList.size() == toExtract.size())
351             return initialList;
352         List result = new ArrayList(toExtract.size());
353         for (Iterator iter = initialList.iterator(); iter.hasNext();) {
354             Object JavaDoc element = iter.next();
355             if (toExtract.contains(element)) {
356                 result.add(element);
357                 if (result.size() == toExtract.size())
358                     break;
359             }
360         }
361         return result;
362     }
363
364     public static int isStringIn(String JavaDoc[] searched, String JavaDoc toSearch) {
365         if (searched == null || toSearch == null)
366             return -1;
367         for (int i = 0; i < searched.length; i++) {
368             if (toSearch.startsWith(searched[i]))
369                 return i;
370         }
371         return -1;
372     }
373
374     public static void generatePermissions(Properties featureProperties, Config aConfig, String JavaDoc targetRootProperty, AntScript script) {
375         String JavaDoc configInfix = aConfig.toString("."); //$NON-NLS-1$
376
String JavaDoc configPath = aConfig.toStringReplacingAny(".", ANY_STRING);
377         String JavaDoc prefixPermissions = ROOT_PREFIX + configInfix + '.' + PERMISSIONS + '.';
378         String JavaDoc prefixLinks = ROOT_PREFIX + configInfix + '.' + LINK;
379         String JavaDoc commonPermissions = ROOT_PREFIX + PERMISSIONS + '.';
380         String JavaDoc commonLinks = ROOT_PREFIX + LINK;
381         for (Iterator iter = featureProperties.entrySet().iterator(); iter.hasNext();) {
382             Map.Entry permission = (Map.Entry) iter.next();
383             String JavaDoc instruction = (String JavaDoc) permission.getKey();
384             String JavaDoc parameters = removeEndingSlashes((String JavaDoc) permission.getValue());
385             if (instruction.startsWith(prefixPermissions)) {
386                 generateChmodInstruction(script, getPropertyFormat(targetRootProperty) + '/' + configPath + '/' + getPropertyFormat(PROPERTY_COLLECTING_FOLDER), instruction.substring(prefixPermissions.length()), parameters);
387                 continue;
388             }
389             if (instruction.startsWith(prefixLinks)) {
390                 generateLinkInstruction(script, getPropertyFormat(targetRootProperty) + '/' + configPath + '/' + getPropertyFormat(PROPERTY_COLLECTING_FOLDER), parameters);
391                 continue;
392             }
393             if (instruction.startsWith(commonPermissions)) {
394                 generateChmodInstruction(script, getPropertyFormat(targetRootProperty) + '/' + configPath + '/' + getPropertyFormat(PROPERTY_COLLECTING_FOLDER), instruction.substring(commonPermissions.length()), parameters);
395                 continue;
396             }
397             if (instruction.startsWith(commonLinks)) {
398                 generateLinkInstruction(script, getPropertyFormat(targetRootProperty) + '/' + configPath + '/' + getPropertyFormat(PROPERTY_COLLECTING_FOLDER), parameters);
399                 continue;
400             }
401         }
402     }
403     
404     public static String JavaDoc removeEndingSlashes(String JavaDoc value) {
405         String JavaDoc[] params = Utils.getArrayFromString(value, ","); //$NON-NLS-1$
406
for (int i = 0; i < params.length; i++) {
407             if (params[i].endsWith("/")) //$NON-NLS-1$
408
params[i] = params[i].substring(0, params[i].length() - 1);
409         }
410         return Utils.getStringFromArray(params, ","); //$NON-NLS-1$
411
}
412     
413     private static void generateChmodInstruction(AntScript script, String JavaDoc dir, String JavaDoc rights, String JavaDoc files) {
414         if (rights.equals(EXECUTABLE)) {
415             rights = "755"; //$NON-NLS-1$
416
}
417         script.printChmod(dir, rights, files);
418     }
419
420     private static void generateLinkInstruction(AntScript script, String JavaDoc dir, String JavaDoc files) {
421         String JavaDoc[] links = Utils.getArrayFromString(files, ","); //$NON-NLS-1$
422
List arguments = new ArrayList(2);
423         for (int i = 0; i < links.length; i += 2) {
424             arguments.add("-sf"); //$NON-NLS-1$
425
arguments.add(links[i]);
426             arguments.add(links[i + 1]);
427             script.printExecTask("ln", dir, arguments, "Linux"); //$NON-NLS-1$ //$NON-NLS-2$
428
arguments.clear();
429         }
430     }
431
432     /**
433      * Return a string with the given property name in the format:
434      * <pre>${propertyName}</pre>.
435      *
436      * @param propertyName the name of the property
437      * @return String
438      */

439     public static String JavaDoc getPropertyFormat(String JavaDoc propertyName) {
440         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
441         sb.append(PROPERTY_ASSIGNMENT_PREFIX);
442         sb.append(propertyName);
443         sb.append(PROPERTY_ASSIGNMENT_SUFFIX);
444         return sb.toString();
445     }
446     
447     public static boolean isBinary(BundleDescription bundle) {
448         Properties bundleProperties = ((Properties) bundle.getUserObject());
449         if (bundleProperties == null || bundleProperties.get(IS_COMPILED) == null){
450             File props = new File(bundle.getLocation(), PROPERTIES_FILE);
451             return !(props.exists() && props.isFile());
452         }
453         return (Boolean.FALSE == bundleProperties.get(IS_COMPILED));
454     }
455     
456     public static Object JavaDoc[] parseExtraBundlesString(String JavaDoc input, boolean onlyId) {
457         StringTokenizer tokenizer = null;
458         if (onlyId)
459             tokenizer = new StringTokenizer(input.startsWith("plugin@") ? input.substring(7) : input.substring(8), ";"); //$NON-NLS-1$//$NON-NLS-2$
460
else
461             tokenizer = new StringTokenizer(input, ";"); //$NON-NLS-1$
462
String JavaDoc bundleId = tokenizer.nextToken();
463         Version version = Version.emptyVersion;
464         Boolean JavaDoc unpack = Boolean.FALSE;
465         while (tokenizer.hasMoreTokens()) {
466             String JavaDoc token = tokenizer.nextToken();
467             if (token.startsWith("version")) { //$NON-NLS-1$
468
version = new Version(token.substring(8));
469                 continue;
470             }
471             if (token.startsWith("unpack")) { //$NON-NLS-1$
472
unpack = (token.toLowerCase().indexOf(TRUE) > -1) ? Boolean.TRUE : Boolean.FALSE;
473                 continue;
474             }
475         }
476         return new Object JavaDoc[] { bundleId, version, unpack };
477     }
478
479 }
480
Popular Tags