KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > internal > ui > util > TemplateFileGenerator


1 /*******************************************************************************
2  * Copyright (c) 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 Corporation - initial API and implementation
10  *******************************************************************************/

11
12 package org.eclipse.pde.internal.ui.util;
13
14 import java.io.ByteArrayInputStream JavaDoc;
15 import java.io.File JavaDoc;
16 import java.io.FileInputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.InputStreamReader JavaDoc;
20 import java.net.MalformedURLException JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.Enumeration JavaDoc;
24 import java.util.HashMap JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.Map JavaDoc;
27 import java.util.zip.ZipEntry JavaDoc;
28 import java.util.zip.ZipException JavaDoc;
29 import java.util.zip.ZipFile JavaDoc;
30
31 import org.eclipse.core.resources.IContainer;
32 import org.eclipse.core.resources.IFile;
33 import org.eclipse.core.resources.IFolder;
34 import org.eclipse.core.resources.IProject;
35 import org.eclipse.core.runtime.CoreException;
36 import org.eclipse.core.runtime.FileLocator;
37 import org.eclipse.core.runtime.IPath;
38 import org.eclipse.core.runtime.IProgressMonitor;
39 import org.eclipse.core.runtime.Path;
40 import org.eclipse.core.runtime.Platform;
41 import org.eclipse.jdt.core.IClasspathEntry;
42 import org.eclipse.jdt.core.IJavaProject;
43 import org.eclipse.jdt.core.JavaCore;
44 import org.eclipse.jdt.core.JavaModelException;
45 import org.eclipse.pde.core.plugin.IPlugin;
46 import org.eclipse.pde.core.plugin.IPluginBase;
47 import org.eclipse.pde.core.plugin.IPluginModel;
48 import org.eclipse.pde.core.plugin.IPluginModelBase;
49 import org.eclipse.pde.internal.core.TargetPlatformHelper;
50 import org.eclipse.pde.internal.core.ibundle.IBundlePluginBase;
51 import org.eclipse.pde.internal.ui.PDEUIMessages;
52 import org.eclipse.pde.internal.ui.wizards.product.ISplashHandlerConstants;
53 import org.eclipse.pde.internal.ui.wizards.product.UpdateSplashHandlerAction;
54 import org.eclipse.pde.internal.ui.wizards.templates.ControlStack;
55 import org.eclipse.pde.ui.templates.IVariableProvider;
56 import org.osgi.framework.Bundle;
57
58 /**
59  * TemplateFileGenerator
60  *
61  */

62 public class TemplateFileGenerator implements IVariableProvider {
63
64     // TODO: MP: SPLASH: Merge this utility back with template (maybe as an abstract base class?) - Extracted from org.eclipse.pde.ui.templates.AbstractTemplateSection
65
// TODO: MP: SPLASH: Major code-clean-up required
66

67     /**
68      * The key for the main plug-in class of the plug-in that the template is
69      * used for (value="pluginClass"). The return value is a fully-qualified class name.
70      */

71     public static final String JavaDoc KEY_PLUGIN_CLASS = "pluginClass"; //$NON-NLS-1$
72

73     /**
74      * The key for the simple class name of a bundle activator (value="activator")
75      *
76      * @since 3.3
77      */

78     public static final String JavaDoc KEY_ACTIVATOR_SIMPLE = "activator"; //$NON-NLS-1$
79
/**
80      * The key for the plug-in id of the plug-in that the template is used for
81      * (value="pluginId").
82      */

83     public static final String JavaDoc KEY_PLUGIN_ID = "pluginId"; //$NON-NLS-1$
84
/**
85      * The key for the plug-in name of the plug-in that the template is used for
86      * (value="pluginName").
87      */

88     public static final String JavaDoc KEY_PLUGIN_NAME = "pluginName"; //$NON-NLS-1$
89
/**
90      * The key for the package name that will be created by this teamplate
91      * (value="packageName").
92      */

93     public static final String JavaDoc KEY_PACKAGE_NAME = "packageName"; //$NON-NLS-1$
94

95     private IProject fProject;
96     
97     private IPluginModelBase fModel;
98     
99     private String JavaDoc fPluginID;
100
101     private String JavaDoc fPackage;
102     
103     private String JavaDoc fClass;
104
105     private String JavaDoc fTemplate;
106     
107     /**
108      * @param project
109      * @param model
110      */

111     public TemplateFileGenerator(IProject project, IPluginModelBase model,
112             String JavaDoc pluginID, String JavaDoc targetPackage, String JavaDoc targetClass,
113             String JavaDoc template) {
114         fProject = project;
115         fModel = model;
116         fPluginID = pluginID;
117         fPackage = targetPackage;
118         fClass = targetClass;
119         fTemplate = template;
120     }
121
122     /**
123      * Generates files as part of the template execution. The default
124      * implementation uses template location as a root of the file templates.
125      * {@link #generateFiles(IProgressMonitor monitor, URL locationUrl)} on how
126      * the location gets processed.
127      *
128      * @param monitor
129      * progress monitor to use to indicate generation progress
130      */

131     public void generateFiles(IProgressMonitor monitor) throws CoreException {
132         // Generate files using the default template location
133
generateFiles(monitor, getTemplateLocation());
134         // Generate files using the shared branding location (for splash screen)
135
Bundle templateBundle = Platform.getBundle("org.eclipse.pde.ui.templates"); //$NON-NLS-1$
136
if (templateBundle == null) {
137             return;
138         }
139         generateFiles(monitor, templateBundle.getEntry("branding/")); //$NON-NLS-1$
140
}
141     
142     public URL JavaDoc getTemplateLocation() {
143         Bundle bundle = Platform.getBundle("org.eclipse.pde.ui.templates"); //$NON-NLS-1$
144
if (bundle == null) {
145             return null;
146         }
147         
148         try {
149             String JavaDoc[] candidates = getDirectoryCandidates();
150             for (int i = 0; i < candidates.length; i++) {
151                 if (bundle.getEntry(candidates[i]) != null) {
152                     URL JavaDoc candidate = new URL JavaDoc(bundle.getEntry("/"), candidates[i]); //$NON-NLS-1$
153
return candidate;
154                 }
155             }
156         } catch (MalformedURLException JavaDoc e) {
157         }
158         return null;
159     }
160     
161     /**
162      * Generates files as part of the template execution.
163      * The files found in the location are processed in the following way:
164      * <ul>
165      * <li>Files and folders found in the directory <samp>bin </samp> are
166      * copied into the target project without modification.</li>
167      * <li>Files found in the directory <samp>java </samp> are copied into the
168      * Java source folder by creating the folder structure that corresponds to
169      * the package name (variable <samp>packageName </samp>). Java files are
170      * subject to conditional generation and variable replacement.</li>
171      * <li>All other files and folders are copied directly into the target
172      * folder with the conditional generation and variable replacement for
173      * files. Variable replacement also includes file names.</li>
174      * </ul>
175      *
176      * @since 3.3
177      * @param monitor
178      * progress monitor to use to indicate generation progress
179      * @param locationUrl a url pointing to a file/directory that will be copied into the template
180      */

181     protected void generateFiles(IProgressMonitor monitor, URL JavaDoc locationUrl) throws CoreException {
182         monitor.setTaskName(PDEUIMessages.AbstractTemplateSection_generating);
183
184         if (locationUrl == null) {
185             return;
186         }
187         try {
188             locationUrl = FileLocator.resolve(locationUrl);
189             locationUrl = FileLocator.toFileURL(locationUrl);
190         } catch (IOException JavaDoc e) {
191             return;
192         }
193         if ("file".equals(locationUrl.getProtocol())) { //$NON-NLS-1$
194
File JavaDoc templateDirectory = new File JavaDoc(locationUrl.getFile());
195             if (!templateDirectory.exists())
196                 return;
197             generateFiles(templateDirectory, fProject, true, false, monitor);
198         } else if ("jar".equals(locationUrl.getProtocol())) { //$NON-NLS-1$
199
String JavaDoc file = locationUrl.getFile();
200             int exclamation = file.indexOf('!');
201             if (exclamation < 0)
202                 return;
203             URL JavaDoc fileUrl = null;
204             try {
205                 fileUrl = new URL JavaDoc(file.substring(0, exclamation));
206             } catch (MalformedURLException JavaDoc mue) {
207                 return;
208             }
209             File JavaDoc pluginJar = new File JavaDoc(fileUrl.getFile());
210             if (!pluginJar.exists())
211                 return;
212             String JavaDoc templateDirectory = file.substring(exclamation + 1); // "/some/path/"
213
IPath path = new Path(templateDirectory);
214             ZipFile JavaDoc zipFile = null;
215             try {
216                 zipFile = new ZipFile JavaDoc(pluginJar);
217                 generateFiles(zipFile, path, fProject, true, false, monitor);
218             } catch (ZipException JavaDoc ze) {
219             } catch (IOException JavaDoc ioe) {
220             } finally {
221                 if (zipFile != null) {
222                     try {
223                         zipFile.close();
224                     } catch (IOException JavaDoc e) {
225                     }
226                 }
227             }
228
229         }
230         monitor.subTask(""); //$NON-NLS-1$
231
monitor.worked(1);
232     }
233     
234     private void generateFiles(File JavaDoc src, IContainer dst, boolean firstLevel,
235             boolean binary, IProgressMonitor monitor) throws CoreException {
236         File JavaDoc[] members = src.listFiles();
237
238         for (int i = 0; i < members.length; i++) {
239             File JavaDoc member = members[i];
240             if (member.isDirectory()) {
241                 IContainer dstContainer = null;
242
243                 if (firstLevel) {
244                     binary = false;
245                     if (!isOkToCreateFolder(member))
246                         continue;
247                     
248                     if (member.getName().equals("java")) { //$NON-NLS-1$
249
IFolder sourceFolder = getSourceFolder(monitor);
250                         dstContainer = generateJavaSourceFolder(sourceFolder, monitor);
251                     } else if (member.getName().equals("bin")) { //$NON-NLS-1$
252
binary = true;
253                         dstContainer = dst;
254                     }
255                 }
256                 if (dstContainer == null) {
257                     if (isOkToCreateFolder(member) == false)
258                         continue;
259                     String JavaDoc folderName = getProcessedString(member.getName(),
260                             member.getName());
261                     dstContainer = dst.getFolder(new Path(folderName));
262                 }
263                 if (dstContainer instanceof IFolder && !dstContainer.exists())
264                     ((IFolder) dstContainer).create(true, true, monitor);
265                 generateFiles(member, dstContainer, false, binary, monitor);
266             } else {
267                 if (isOkToCreateFile(member)) {
268                     if (firstLevel)
269                         binary = false;
270                     InputStream JavaDoc in = null;
271                     try {
272                         in = new FileInputStream JavaDoc(member);
273                         copyFile(member.getName(), in, dst, binary, monitor);
274                     } catch (IOException JavaDoc ioe) {
275                     } finally {
276                         if (in != null)
277                             try {
278                                 in.close();
279                             } catch (IOException JavaDoc ioe2) {
280                             }
281                     }
282                 }
283             }
284         }
285     }
286     
287     private void copyFile(String JavaDoc fileName, InputStream JavaDoc input, IContainer dst, boolean binary,
288             IProgressMonitor monitor) throws CoreException {
289         String JavaDoc targetFileName = getProcessedString(fileName, fileName);
290
291         monitor.subTask(targetFileName);
292         IFile dstFile = dst.getFile(new Path(targetFileName));
293
294         try {
295             InputStream JavaDoc stream = getProcessedStream(fileName, input, binary);
296             if (dstFile.exists()) {
297                 dstFile.setContents(stream, true, true, monitor);
298             } else {
299                 dstFile.create(stream, true, monitor);
300             }
301             stream.close();
302
303         } catch (IOException JavaDoc e) {
304         }
305     }
306     
307     private void generateFiles(ZipFile JavaDoc zipFile, IPath path, IContainer dst,
308             boolean firstLevel, boolean binary, IProgressMonitor monitor)
309             throws CoreException {
310         int pathLength = path.segmentCount();
311         // Immidiate children
312
Map JavaDoc childZipEntries = new HashMap JavaDoc(); // "dir/" or "dir/file.java"
313

314         for (Enumeration JavaDoc zipEntries = zipFile.entries(); zipEntries
315                 .hasMoreElements();) {
316             ZipEntry JavaDoc zipEntry = (ZipEntry JavaDoc) zipEntries.nextElement();
317             IPath entryPath = new Path(zipEntry.getName());
318             if (entryPath.segmentCount() <= pathLength) {
319                 // ancestor or current directory
320
continue;
321             }
322             if (!path.isPrefixOf(entryPath)) {
323                 // not a descendant
324
continue;
325             }
326             if (entryPath.segmentCount() == pathLength + 1) {
327                 childZipEntries.put(zipEntry.getName(), zipEntry);
328             } else {
329                 String JavaDoc name = entryPath.uptoSegment(
330                         pathLength + 1).addTrailingSeparator().toString();
331                 if(!childZipEntries.containsKey(name)){
332                     ZipEntry JavaDoc dirEntry = new ZipEntry JavaDoc(name);
333                     childZipEntries.put(name, dirEntry);
334                 }
335             }
336         }
337
338         for (Iterator JavaDoc it = childZipEntries.values().iterator(); it.hasNext();) {
339             ZipEntry JavaDoc zipEnry = (ZipEntry JavaDoc) it.next();
340             String JavaDoc name = new Path(zipEnry.getName()).lastSegment().toString();
341             if (zipEnry.isDirectory()) {
342                 IContainer dstContainer = null;
343
344                 if (firstLevel) {
345                     binary = false;
346                     if (name.equals("java")) { //$NON-NLS-1$
347
IFolder sourceFolder = getSourceFolder(monitor);
348                         dstContainer = generateJavaSourceFolder(sourceFolder,
349                                 monitor);
350                     } else if (name.equals("bin")) { //$NON-NLS-1$
351
binary = true;
352                         dstContainer = dst;
353                     }
354                 }
355                 if (dstContainer == null) {
356                     if (isOkToCreateFolder(new File JavaDoc(path.toFile(), name)) == false)
357                         continue;
358                     String JavaDoc folderName = getProcessedString(name, name);
359                     dstContainer = dst.getFolder(new Path(folderName));
360                 }
361                 if (dstContainer instanceof IFolder && !dstContainer.exists())
362                     ((IFolder) dstContainer).create(true, true, monitor);
363                 generateFiles(zipFile, path.append(name), dstContainer, false,
364                         binary, monitor);
365             } else {
366                 if (isOkToCreateFile(new File JavaDoc(path.toFile(), name))) {
367                     if (firstLevel)
368                         binary = false;
369                     InputStream JavaDoc in = null;
370                     try {
371                         in = zipFile.getInputStream(zipEnry);
372                         copyFile(name, in, dst, binary, monitor);
373                     } catch (IOException JavaDoc ioe) {
374                     } finally {
375                         if (in != null)
376                             try {
377                                 in.close();
378                             } catch (IOException JavaDoc ioe2) {
379                             }
380                     }
381                 }
382             }
383         }
384     }
385     
386     /**
387      * Tests if the folder found in the template location should be created in
388      * the target project. Subclasses may use this method to conditionally block
389      * the creation of entire directories (subject to user choices).
390      *
391      * @param sourceFolder
392      * the folder that is tested
393      * @return <code>true</code> if the provided folder should be created in
394      * the workspace, <code>false</code> if the values of the
395      * substitution variables indicate otherwise.
396      */

397     protected boolean isOkToCreateFolder(File JavaDoc sourceFolder) {
398         boolean extensibleTemplateSelected =
399             UpdateSplashHandlerAction.isExtensibleTemplateSelected(fTemplate);
400         String JavaDoc sourceFolderString = sourceFolder.toString();
401         
402         if ((extensibleTemplateSelected == false) &&
403                 sourceFolderString.endsWith("icons")) { //$NON-NLS-1$
404
return false;
405         } else if ((extensibleTemplateSelected == false) &&
406                 sourceFolderString.endsWith("schema")) { //$NON-NLS-1$
407
return false;
408         }
409             
410         return true;
411     }
412
413     /**
414      * Tests if the file found in the template location should be created in the
415      * target project. Subclasses may use this method to conditionally block
416      * creation of the file (subject to user choices).
417      *
418      * @param sourceFile
419      * the file found in the template location that needs to be
420      * created.
421      * @return <samp>true </samp> if the specified file should be created in the
422      * project or <samp>false </samp> to skip it. The default
423      * implementation is <samp>true </samp>.
424      */

425     protected boolean isOkToCreateFile(File JavaDoc sourceFile) {
426         String JavaDoc javaSuffix = ".java"; //$NON-NLS-1$
427
String JavaDoc targetFile = fClass + javaSuffix;
428         String JavaDoc copyFile = sourceFile.toString();
429         // Prevent needless copying
430
// TODO: MP: SPLASH: Propagate / share copy prevention code with org.eclipse.pde.internal.ui.templates.ide.SplashHandlersTemplate
431
if (copyFile.endsWith(javaSuffix)) {
432             if ((copyFile.endsWith(targetFile) == false) ||
433                 fProject.exists(new Path("src" + '/' + fPackage.replace('.', '/') + '/' + targetFile))) { //$NON-NLS-1$
434
return false;
435             }
436         } else if (copyFile.endsWith("splash.bmp") && //$NON-NLS-1$
437
(fProject.exists(new Path("splash.bmp")))) { //$NON-NLS-1$
438
return false;
439         } else if (copyFile.endsWith(".png")) { //$NON-NLS-1$
440
if (copyFile.endsWith("af.png") && //$NON-NLS-1$
441
fProject.exists(new Path("icons/af.png"))) { //$NON-NLS-1$
442
return false;
443             } else if (copyFile.endsWith("embedded.png") && //$NON-NLS-1$
444
fProject.exists(new Path("icons/embedded.png"))) { //$NON-NLS-1$
445
return false;
446             } else if (copyFile.endsWith("enterprise.png") && //$NON-NLS-1$
447
fProject.exists(new Path("icons/enterprise.png"))) { //$NON-NLS-1$
448
return false;
449             } else if (copyFile.endsWith("rcp.png") && //$NON-NLS-1$
450
fProject.exists(new Path("icons/rcp.png"))) { //$NON-NLS-1$
451
return false;
452             } else if (copyFile.endsWith("languages.png") && //$NON-NLS-1$
453
fProject.exists(new Path("icons/languages.png"))) { //$NON-NLS-1$
454
return false;
455             }
456         } else if (copyFile.endsWith("splashExtension.exsd") && //$NON-NLS-1$
457
(fProject.exists(new Path("schema/splashExtension.exsd")))) { //$NON-NLS-1$
458
return false;
459         }
460         
461         return true;
462     }
463     
464     /**
465      * Returns the folder with Java files in the target project. The default
466      * implementation looks for source folders in the classpath of the target
467      * folders and picks the first one encountered. Subclasses may override this
468      * behaviour.
469      *
470      * @param monitor
471      * progress monitor to use
472      * @return source folder that will be used to generate Java files or
473      * <samp>null </samp> if none found.
474      */

475
476     protected IFolder getSourceFolder(IProgressMonitor monitor)
477             throws CoreException {
478         IFolder sourceFolder = null;
479
480         try {
481             IJavaProject javaProject = JavaCore.create(fProject);
482             IClasspathEntry[] classpath = javaProject.getRawClasspath();
483             for (int i = 0; i < classpath.length; i++) {
484                 IClasspathEntry entry = classpath[i];
485                 if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
486                     IPath path = entry.getPath().removeFirstSegments(1);
487                     if (path.segmentCount() > 0)
488                         sourceFolder = fProject.getFolder(path);
489                     break;
490                 }
491             }
492         } catch (JavaModelException e) {
493         }
494         return sourceFolder;
495     }
496     
497     /**
498      * @see IVariableProvider#getValue(String)
499      */

500
501     public Object JavaDoc getValue(String JavaDoc key) {
502         return getKeyValue(key);
503     }
504     
505     private IFolder generateJavaSourceFolder(IFolder sourceFolder,
506             IProgressMonitor monitor) throws CoreException {
507         Object JavaDoc packageValue = getValue(KEY_PACKAGE_NAME);
508         //
509
String JavaDoc packageName = packageValue != null
510                 ? packageValue.toString()
511                 : null;
512         if (packageName == null)
513             packageName = fModel.getPluginBase().getId();
514         IPath path = new Path(packageName.replace('.', File.separatorChar));
515         if (sourceFolder != null)
516             path = sourceFolder.getProjectRelativePath().append(path);
517
518         for (int i = 1; i <= path.segmentCount(); i++) {
519             IPath subpath = path.uptoSegment(i);
520             IFolder subfolder = fProject.getFolder(subpath);
521             if (subfolder.exists() == false)
522                 subfolder.create(true, true, monitor);
523         }
524         return fProject.getFolder(path);
525     }
526     
527     private String JavaDoc getProcessedString(String JavaDoc fileName, String JavaDoc source) {
528         if (source.indexOf('$') == -1)
529             return source;
530         int loc = -1;
531         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
532         boolean replacementMode = false;
533         for (int i = 0; i < source.length(); i++) {
534             char c = source.charAt(i);
535             if (c == '$') {
536                 if (replacementMode) {
537                     String JavaDoc key = source.substring(loc, i);
538                     String JavaDoc value = key.length() == 0 ? "$" //$NON-NLS-1$
539
: getReplacementString(fileName, key);
540                     buffer.append(value);
541                     replacementMode = false;
542                 } else {
543                     replacementMode = true;
544                     loc = i + 1;
545                     continue;
546                 }
547             } else if (!replacementMode)
548                 buffer.append(c);
549         }
550         return buffer.toString();
551     }
552     
553     /**
554      * The default implementation of this method provides values of the
555      * following keys: <samp>pluginClass </samp>, <samp>pluginId </samp> and
556      * <samp>pluginName </samp>.
557      *
558      * @see ITemplateSection#getReplacementString(String,String)
559      */

560     public String JavaDoc getReplacementString(String JavaDoc fileName, String JavaDoc key) {
561         String JavaDoc result = getKeyValue(key);
562         return result != null ? result : key;
563     }
564     
565     private String JavaDoc getKeyValue(String JavaDoc key) {
566         if (fModel == null)
567             return null;
568         
569         // TODO: MP: SPLASH: Broken and not needed, underlying model does not have class, id, translated name parameters defined
570
if (key.equals(KEY_PLUGIN_CLASS) && fModel instanceof IPluginModel) {
571             IPlugin plugin = (IPlugin) fModel.getPluginBase();
572             return plugin.getClassName();
573         }
574         
575         // TODO: MP: SPLASH: Broken and not needed, underlying model does not have class, id, translated name parameters defined
576
if (key.equals(KEY_ACTIVATOR_SIMPLE) && fModel instanceof IPluginModel) {
577             IPlugin plugin = (IPlugin) fModel.getPluginBase();
578             String JavaDoc qualified = plugin.getClassName();
579             if (qualified != null) {
580                 int lastDot = qualified.lastIndexOf('.');
581                 return (lastDot != -1 && lastDot < qualified.length() - 1) ? qualified.substring(lastDot + 1) : qualified;
582             }
583         }
584
585         if (key.equals(KEY_PLUGIN_ID)) {
586             return fPluginID;
587             // Old implementation, does not work
588
//IPluginBase plugin = fModel.getPluginBase();
589
//return plugin.getId();
590
}
591         // TODO: MP: SPLASH: Broken and not needed, underlying model does not have class, id, translated name parameters defined
592
if (key.equals(KEY_PLUGIN_NAME)) {
593             IPluginBase plugin = fModel.getPluginBase();
594             return plugin.getTranslatedName();
595         }
596         
597         if (key.equals(KEY_PACKAGE_NAME) && fModel instanceof IPluginModel) {
598             return fPackage;
599             // Old implementation, does not work
600
// IPlugin plugin = (IPlugin) fModel.getPluginBase();
601
// String qualified = plugin.getClassName();
602
// if (qualified != null) {
603
// int lastDot = qualified.lastIndexOf('.');
604
// return (lastDot != -1) ? qualified.substring(0, lastDot) : qualified;
605
// }
606
}
607         return null;
608     }
609
610     private InputStream JavaDoc getProcessedStream(String JavaDoc fileName, InputStream JavaDoc stream,
611             boolean binary) throws IOException JavaDoc, CoreException {
612         if (binary)
613             return stream;
614
615         InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(stream);
616         int bufsize = 1024;
617         char[] cbuffer = new char[bufsize];
618         int read = 0;
619         StringBuffer JavaDoc keyBuffer = new StringBuffer JavaDoc();
620         StringBuffer JavaDoc outBuffer = new StringBuffer JavaDoc();
621         StringBuffer JavaDoc preBuffer = new StringBuffer JavaDoc();
622         boolean newLine = true;
623         ControlStack preStack = new ControlStack();
624         preStack.setValueProvider(this);
625
626         boolean replacementMode = false;
627         boolean preprocessorMode = false;
628         boolean escape = false;
629         while (read != -1) {
630             read = reader.read(cbuffer);
631             for (int i = 0; i < read; i++) {
632                 char c = cbuffer[i];
633
634                 if (escape) {
635                     StringBuffer JavaDoc buf = preprocessorMode ? preBuffer : outBuffer;
636                     buf.append(c);
637                     escape = false;
638                     continue;
639                 }
640
641                 if (newLine && c == '%') {
642                     // preprocessor line
643
preprocessorMode = true;
644                     preBuffer.delete(0, preBuffer.length());
645                     continue;
646                 }
647                 if (preprocessorMode) {
648                     if (c == '\\') {
649                         escape = true;
650                         continue;
651                     }
652                     if (c == '\n') {
653                         // handle line
654
preprocessorMode = false;
655                         newLine = true;
656                         String JavaDoc line = preBuffer.toString().trim();
657                         preStack.processLine(line);
658                         continue;
659                     }
660                     preBuffer.append(c);
661
662                     continue;
663                 }
664
665                 if (preStack.getCurrentState() == false) {
666                     continue;
667                 }
668
669                 if (c == '$') {
670                     if (replacementMode) {
671                         replacementMode = false;
672                         String JavaDoc key = keyBuffer.toString();
673                         String JavaDoc value = key.length() == 0 ? "$" //$NON-NLS-1$
674
: getReplacementString(fileName, key);
675                         outBuffer.append(value);
676                         keyBuffer.delete(0, keyBuffer.length());
677                     } else {
678                         replacementMode = true;
679                     }
680                 } else {
681                     if (replacementMode)
682                         keyBuffer.append(c);
683                     else {
684                         outBuffer.append(c);
685                         if (c == '\n') {
686                             newLine = true;
687                         } else
688                             newLine = false;
689                     }
690                 }
691             }
692         }
693         return new ByteArrayInputStream JavaDoc(outBuffer.toString().getBytes(
694                 fProject.getDefaultCharset()));
695     }
696     
697     private String JavaDoc[] getDirectoryCandidates() {
698         double version = getTargetVersion();
699         ArrayList JavaDoc result = new ArrayList JavaDoc();
700         if (version >= 3.3)
701             result.add("templates_3.3" + "/" + getSectionId() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
702
if (version >= 3.2)
703             result.add("templates_3.2" + "/" + getSectionId() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
704
if (version >= 3.1)
705             result.add("templates_3.1" + "/" + getSectionId() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
706
if (version >= 3.0)
707             result.add("templates_3.0" + "/" + getSectionId() + "/"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
708
return (String JavaDoc[])result.toArray(new String JavaDoc[result.size()]);
709     }
710     
711     public String JavaDoc getSectionId() {
712         return ISplashHandlerConstants.F_UNQUALIFIED_EXTENSION_ID;
713     }
714     
715     protected double getTargetVersion() {
716         try {
717             IPluginBase plugin = fModel.getPluginBase();
718             if (plugin instanceof IBundlePluginBase)
719                 return Double.parseDouble(((IBundlePluginBase)plugin).getTargetVersion());
720         } catch (NumberFormatException JavaDoc e) {
721         }
722        return TargetPlatformHelper.getTargetVersion();
723     }
724     
725 }
726
Popular Tags