KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > pde > ui > templates > AbstractTemplateSection


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 Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.pde.ui.templates;
12 import java.io.ByteArrayInputStream JavaDoc;
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.InputStream JavaDoc;
17 import java.io.InputStreamReader JavaDoc;
18 import java.net.MalformedURLException JavaDoc;
19 import java.net.URL JavaDoc;
20 import java.util.Enumeration JavaDoc;
21 import java.util.HashMap JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Map JavaDoc;
24 import java.util.MissingResourceException JavaDoc;
25 import java.util.ResourceBundle JavaDoc;
26 import java.util.zip.ZipEntry JavaDoc;
27 import java.util.zip.ZipException JavaDoc;
28 import java.util.zip.ZipFile JavaDoc;
29
30 import org.eclipse.core.resources.IContainer;
31 import org.eclipse.core.resources.IFile;
32 import org.eclipse.core.resources.IFolder;
33 import org.eclipse.core.resources.IProject;
34 import org.eclipse.core.runtime.CoreException;
35 import org.eclipse.core.runtime.FileLocator;
36 import org.eclipse.core.runtime.IPath;
37 import org.eclipse.core.runtime.IProgressMonitor;
38 import org.eclipse.core.runtime.Path;
39 import org.eclipse.jdt.core.IClasspathEntry;
40 import org.eclipse.jdt.core.IJavaProject;
41 import org.eclipse.jdt.core.JavaCore;
42 import org.eclipse.jdt.core.JavaModelException;
43 import org.eclipse.jface.wizard.Wizard;
44 import org.eclipse.pde.core.plugin.IPlugin;
45 import org.eclipse.pde.core.plugin.IPluginBase;
46 import org.eclipse.pde.core.plugin.IPluginExtension;
47 import org.eclipse.pde.core.plugin.IPluginModel;
48 import org.eclipse.pde.core.plugin.IPluginModelBase;
49 import org.eclipse.pde.core.plugin.IPluginReference;
50 import org.eclipse.pde.internal.core.TargetPlatformHelper;
51 import org.eclipse.pde.internal.core.ibundle.IBundlePluginBase;
52 import org.eclipse.pde.internal.ui.PDEUIMessages;
53 import org.eclipse.pde.internal.ui.wizards.templates.ControlStack;
54 import org.eclipse.pde.internal.ui.wizards.templates.PluginReference;
55
56 /**
57  * Common function for template sections. It is recommended to subclass this
58  * class rather than implementing ITemplateSection directly when providing
59  * extension templates.
60  *
61  * @since 2.0
62  */

63
64 public abstract class AbstractTemplateSection
65         implements
66             ITemplateSection,
67             IVariableProvider {
68
69     /**
70      * The project handle.
71      */

72     protected IProject project;
73     /**
74      * The plug-in model.
75      */

76     protected IPluginModelBase model;
77     /**
78      * The key for the main plug-in class of the plug-in that the template is
79      * used for (value="pluginClass"). The return value is a fully-qualified class name.
80      */

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

83     /**
84      * The key for the simple class name of a bundle activator (value="activator")
85      *
86      * @since 3.3
87      */

88     public static final String JavaDoc KEY_ACTIVATOR_SIMPLE = "activator"; //$NON-NLS-1$
89
/**
90      * The key for the plug-in id of the plug-in that the template is used for
91      * (value="pluginId").
92      */

93     public static final String JavaDoc KEY_PLUGIN_ID = "pluginId"; //$NON-NLS-1$
94
/**
95      * The key for the plug-in name of the plug-in that the template is used for
96      * (value="pluginName").
97      */

98     public static final String JavaDoc KEY_PLUGIN_NAME = "pluginName"; //$NON-NLS-1$
99
/**
100      * The key for the package name that will be created by this teamplate
101      * (value="packageName").
102      */

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

105     private boolean pagesAdded = false;
106     /**
107      * The default implementation of this method provides values of the
108      * following keys: <samp>pluginClass </samp>, <samp>pluginId </samp> and
109      * <samp>pluginName </samp>.
110      *
111      * @see ITemplateSection#getReplacementString(String,String)
112      */

113     public String JavaDoc getReplacementString(String JavaDoc fileName, String JavaDoc key) {
114         String JavaDoc result = getKeyValue(key);
115         return result != null ? result : key;
116     }
117
118     /**
119      * @see IVariableProvider#getValue(String)
120      */

121
122     public Object JavaDoc getValue(String JavaDoc key) {
123         return getKeyValue(key);
124     }
125     
126     private String JavaDoc getKeyValue(String JavaDoc key) {
127         if (model == null)
128             return null;
129         
130         if (key.equals(KEY_PLUGIN_CLASS) && model instanceof IPluginModel) {
131             IPlugin plugin = (IPlugin) model.getPluginBase();
132             return plugin.getClassName();
133         }
134         
135         if (key.equals(KEY_ACTIVATOR_SIMPLE) && model instanceof IPluginModel) {
136             IPlugin plugin = (IPlugin) model.getPluginBase();
137             String JavaDoc qualified = plugin.getClassName();
138             if (qualified != null) {
139                 int lastDot = qualified.lastIndexOf('.');
140                 return (lastDot != -1 && lastDot < qualified.length() - 1) ? qualified.substring(lastDot + 1) : qualified;
141             }
142         }
143         if (key.equals(KEY_PLUGIN_ID)) {
144             IPluginBase plugin = model.getPluginBase();
145             return plugin.getId();
146         }
147         if (key.equals(KEY_PLUGIN_NAME)) {
148             IPluginBase plugin = model.getPluginBase();
149             return plugin.getTranslatedName();
150         }
151         
152         if (key.equals(KEY_PACKAGE_NAME) && model instanceof IPluginModel) {
153             IPlugin plugin = (IPlugin) model.getPluginBase();
154             String JavaDoc qualified = plugin.getClassName();
155             if (qualified != null) {
156                 int lastDot = qualified.lastIndexOf('.');
157                 return (lastDot != -1) ? qualified.substring(0, lastDot) : qualified;
158             }
159         }
160         return null;
161     }
162     /**
163      * @see ITemplateSection#getTemplateLocation()
164      */

165     public URL JavaDoc getTemplateLocation() {
166         return null;
167     }
168     /**
169      * @see ITemplateSection#getDescription()
170      */

171     public String JavaDoc getDescription() {
172         return ""; //$NON-NLS-1$
173
}
174     /**
175      * Returns the translated version of the resource string represented by the
176      * provided key.
177      *
178      * @param key
179      * the key of the required resource string
180      * @return the translated version of the required resource string
181      * @see #getPluginResourceBundle()
182      */

183     public String JavaDoc getPluginResourceString(String JavaDoc key) {
184         ResourceBundle JavaDoc bundle = getPluginResourceBundle();
185         if (bundle == null)
186             return key;
187         try {
188             return bundle.getString(key);
189         } catch (MissingResourceException JavaDoc e) {
190             return key;
191         }
192     }
193     /**
194      * An abstract method that returns the resource bundle that corresponds to
195      * the best match of <samp>plugin.properties </samp> file for the current
196      * locale (in case of fragments, the file is <samp>fragment.properties
197      * </samp>).
198      *
199      * @return resource bundle for plug-in properties file or <samp>null </samp>
200      * if not found.
201      */

202     protected abstract ResourceBundle JavaDoc getPluginResourceBundle();
203
204     /* (non-Javadoc)
205      * @see org.eclipse.pde.ui.templates.ITemplateSection#addPages(org.eclipse.jface.wizard.Wizard)
206      */

207     public void addPages(Wizard wizard) {
208     }
209     
210     /**
211      * Tests if wizard pages for this template section have been added.
212      *
213      * @return <code>true</code> if wizard pages for this section have been
214      * added, <code>false</code> otherwise.
215      */

216     public boolean getPagesAdded() {
217         return pagesAdded;
218     }
219
220     /**
221      * Marks that pages have been added to the wizard by this template. Call
222      * this method in 'addPages'.
223      *
224      * @see #addPages(Wizard)
225      */

226     protected void markPagesAdded() {
227         pagesAdded = true;
228     }
229
230     /**
231      * The default implementation of the interface method. The returned value is
232      * 1.
233      *
234      * @see ITemplateSection#getNumberOfWorkUnits()
235      */

236     public int getNumberOfWorkUnits() {
237         return 1;
238     }
239
240     /* (non-Javadoc)
241      * @see org.eclipse.pde.ui.templates.ITemplateSection#getDependencies(java.lang.String)
242      */

243     public IPluginReference[] getDependencies(String JavaDoc schemaVersion) {
244         return new IPluginReference[]{new PluginReference("org.eclipse.ui", //$NON-NLS-1$
245
null, 0)};
246     }
247     
248     /**
249      * Returns the folder with Java files in the target project. The default
250      * implementation looks for source folders in the classpath of the target
251      * folders and picks the first one encountered. Subclasses may override this
252      * behaviour.
253      *
254      * @param monitor
255      * progress monitor to use
256      * @return source folder that will be used to generate Java files or
257      * <samp>null </samp> if none found.
258      */

259
260     protected IFolder getSourceFolder(IProgressMonitor monitor)
261             throws CoreException {
262         IFolder sourceFolder = null;
263
264         try {
265             IJavaProject javaProject = JavaCore.create(project);
266             IClasspathEntry[] classpath = javaProject.getRawClasspath();
267             for (int i = 0; i < classpath.length; i++) {
268                 IClasspathEntry entry = classpath[i];
269                 if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
270                     IPath path = entry.getPath().removeFirstSegments(1);
271                     if (path.segmentCount() > 0)
272                         sourceFolder = project.getFolder(path);
273                     break;
274                 }
275             }
276         } catch (JavaModelException e) {
277         }
278         return sourceFolder;
279     }
280
281     /**
282      * Generates files as part of the template execution. The default
283      * implementation uses template location as a root of the file templates.
284      * {@link #generateFiles(IProgressMonitor monitor, URL locationUrl)} on how
285      * the location gets processed.
286      *
287      * @param monitor
288      * progress monitor to use to indicate generation progress
289      */

290     protected void generateFiles(IProgressMonitor monitor) throws CoreException {
291         generateFiles(monitor, getTemplateLocation());
292     }
293     
294     /**
295      * Generates files as part of the template execution.
296      * The files found in the location are processed in the following way:
297      * <ul>
298      * <li>Files and folders found in the directory <samp>bin </samp> are
299      * copied into the target project without modification.</li>
300      * <li>Files found in the directory <samp>java </samp> are copied into the
301      * Java source folder by creating the folder structure that corresponds to
302      * the package name (variable <samp>packageName </samp>). Java files are
303      * subject to conditional generation and variable replacement.</li>
304      * <li>All other files and folders are copied directly into the target
305      * folder with the conditional generation and variable replacement for
306      * files. Variable replacement also includes file names.</li>
307      * </ul>
308      *
309      * @since 3.3
310      * @param monitor
311      * progress monitor to use to indicate generation progress
312      * @param locationUrl a url pointing to a file/directory that will be copied into the template
313      */

314     protected void generateFiles(IProgressMonitor monitor, URL JavaDoc locationUrl) throws CoreException {
315         monitor.setTaskName(PDEUIMessages.AbstractTemplateSection_generating);
316
317         if (locationUrl == null) {
318             return;
319         }
320         try {
321             locationUrl = FileLocator.resolve(locationUrl);
322             locationUrl = FileLocator.toFileURL(locationUrl);
323         } catch (IOException JavaDoc e) {
324             return;
325         }
326         if ("file".equals(locationUrl.getProtocol())) { //$NON-NLS-1$
327
File JavaDoc templateDirectory = new File JavaDoc(locationUrl.getFile());
328             if (!templateDirectory.exists())
329                 return;
330             generateFiles(templateDirectory, project, true, false, monitor);
331         } else if ("jar".equals(locationUrl.getProtocol())) { //$NON-NLS-1$
332
String JavaDoc file = locationUrl.getFile();
333             int exclamation = file.indexOf('!');
334             if (exclamation < 0)
335                 return;
336             URL JavaDoc fileUrl = null;
337             try {
338                 fileUrl = new URL JavaDoc(file.substring(0, exclamation));
339             } catch (MalformedURLException JavaDoc mue) {
340                 return;
341             }
342             File JavaDoc pluginJar = new File JavaDoc(fileUrl.getFile());
343             if (!pluginJar.exists())
344                 return;
345             String JavaDoc templateDirectory = file.substring(exclamation + 1); // "/some/path/"
346
IPath path = new Path(templateDirectory);
347             ZipFile JavaDoc zipFile = null;
348             try {
349                 zipFile = new ZipFile JavaDoc(pluginJar);
350                 generateFiles(zipFile, path, project, true, false, monitor);
351             } catch (ZipException JavaDoc ze) {
352             } catch (IOException JavaDoc ioe) {
353             } finally {
354                 if (zipFile != null) {
355                     try {
356                         zipFile.close();
357                     } catch (IOException JavaDoc e) {
358                     }
359                 }
360             }
361
362         }
363         monitor.subTask(""); //$NON-NLS-1$
364
monitor.worked(1);
365     }
366     
367     /**
368      * Tests if the folder found in the template location should be created in
369      * the target project. Subclasses may use this method to conditionally block
370      * the creation of entire directories (subject to user choices).
371      *
372      * @param sourceFolder
373      * the folder that is tested
374      * @return <code>true</code> if the provided folder should be created in
375      * the workspace, <code>false</code> if the values of the
376      * substitution variables indicate otherwise.
377      */

378     protected boolean isOkToCreateFolder(File JavaDoc sourceFolder) {
379         return true;
380     }
381
382     /**
383      * Tests if the file found in the template location should be created in the
384      * target project. Subclasses may use this method to conditionally block
385      * creation of the file (subject to user choices).
386      *
387      * @param sourceFile
388      * the file found in the template location that needs to be
389      * created.
390      * @return <samp>true </samp> if the specified file should be created in the
391      * project or <samp>false </samp> to skip it. The default
392      * implementation is <samp>true </samp>.
393      */

394     protected boolean isOkToCreateFile(File JavaDoc sourceFile) {
395         return true;
396     }
397
398     /**
399      * Subclass must implement this method to add the required entries in the
400      * plug-in model.
401      *
402      * @param monitor
403      * the progress monitor to be used
404      */

405     protected abstract void updateModel(IProgressMonitor monitor)
406             throws CoreException;
407
408     /**
409      * The default implementation of the interface method. It will generate
410      * required files found in the template location and then call
411      * <samp>updateModel </samp> to add the required manifest entires.
412      *
413      * @see ITemplateSection#execute(IProject, IPluginModelBase,
414      * IProgressMonitor)
415      */

416     public void execute(IProject project, IPluginModelBase model,
417             IProgressMonitor monitor) throws CoreException {
418         this.project = project;
419         this.model = model;
420         generateFiles(monitor);
421         updateModel(monitor);
422     }
423     /**
424      * A utility method to create an extension object for the plug-in model from
425      * the provided extension point id.
426      *
427      * @param pointId
428      * the identifier of the target extension point
429      * @param reuse
430      * if true, new extension object will be created only if an
431      * extension with the same Id does not exist.
432      * @return an existing extension (if exists and <samp>reuse </samp> is
433      * <samp>true </samp>), or a new extension object otherwise.
434      */

435     protected IPluginExtension createExtension(String JavaDoc pointId, boolean reuse)
436             throws CoreException {
437         if (reuse) {
438             IPluginExtension[] extensions = model.getPluginBase()
439                     .getExtensions();
440             for (int i = 0; i < extensions.length; i++) {
441                 IPluginExtension extension = extensions[i];
442                 if (extension.getPoint().equalsIgnoreCase(pointId)) {
443                     return extension;
444                 }
445             }
446         }
447         IPluginExtension extension = model.getFactory().createExtension();
448         extension.setPoint(pointId);
449         return extension;
450     }
451
452     private void generateFiles(File JavaDoc src, IContainer dst, boolean firstLevel,
453             boolean binary, IProgressMonitor monitor) throws CoreException {
454         File JavaDoc[] members = src.listFiles();
455
456         for (int i = 0; i < members.length; i++) {
457             File JavaDoc member = members[i];
458             if (member.isDirectory()) {
459                 IContainer dstContainer = null;
460
461                 if (firstLevel) {
462                     binary = false;
463                     if (!isOkToCreateFolder(member))
464                         continue;
465                     
466                     if (member.getName().equals("java")) { //$NON-NLS-1$
467
IFolder sourceFolder = getSourceFolder(monitor);
468                         dstContainer = generateJavaSourceFolder(sourceFolder, monitor);
469                     } else if (member.getName().equals("bin")) { //$NON-NLS-1$
470
binary = true;
471                         dstContainer = dst;
472                     }
473                 }
474                 if (dstContainer == null) {
475                     if (isOkToCreateFolder(member) == false)
476                         continue;
477                     String JavaDoc folderName = getProcessedString(member.getName(),
478                             member.getName());
479                     dstContainer = dst.getFolder(new Path(folderName));
480                 }
481                 if (dstContainer instanceof IFolder && !dstContainer.exists())
482                     ((IFolder) dstContainer).create(true, true, monitor);
483                 generateFiles(member, dstContainer, false, binary, monitor);
484             } else {
485                 if (isOkToCreateFile(member)) {
486                     if (firstLevel)
487                         binary = false;
488                     InputStream JavaDoc in = null;
489                     try {
490                         in = new FileInputStream JavaDoc(member);
491                         copyFile(member.getName(), in, dst, binary, monitor);
492                     } catch (IOException JavaDoc ioe) {
493                     } finally {
494                         if (in != null)
495                             try {
496                                 in.close();
497                             } catch (IOException JavaDoc ioe2) {
498                             }
499                     }
500                 }
501             }
502         }
503     }
504
505     private void generateFiles(ZipFile JavaDoc zipFile, IPath path, IContainer dst,
506             boolean firstLevel, boolean binary, IProgressMonitor monitor)
507             throws CoreException {
508         int pathLength = path.segmentCount();
509         // Immidiate children
510
Map JavaDoc childZipEntries = new HashMap JavaDoc(); // "dir/" or "dir/file.java"
511

512         for (Enumeration JavaDoc zipEntries = zipFile.entries(); zipEntries
513                 .hasMoreElements();) {
514             ZipEntry JavaDoc zipEntry = (ZipEntry JavaDoc) zipEntries.nextElement();
515             IPath entryPath = new Path(zipEntry.getName());
516             if (entryPath.segmentCount() <= pathLength) {
517                 // ancestor or current directory
518
continue;
519             }
520             if (!path.isPrefixOf(entryPath)) {
521                 // not a descendant
522
continue;
523             }
524             if (entryPath.segmentCount() == pathLength + 1) {
525                 childZipEntries.put(zipEntry.getName(), zipEntry);
526             } else {
527                 String JavaDoc name = entryPath.uptoSegment(
528                         pathLength + 1).addTrailingSeparator().toString();
529                 if(!childZipEntries.containsKey(name)){
530                     ZipEntry JavaDoc dirEntry = new ZipEntry JavaDoc(name);
531                     childZipEntries.put(name, dirEntry);
532                 }
533             }
534         }
535
536         for (Iterator JavaDoc it = childZipEntries.values().iterator(); it.hasNext();) {
537             ZipEntry JavaDoc zipEnry = (ZipEntry JavaDoc) it.next();
538             String JavaDoc name = new Path(zipEnry.getName()).lastSegment().toString();
539             if (zipEnry.isDirectory()) {
540                 IContainer dstContainer = null;
541
542                 if (firstLevel) {
543                     binary = false;
544                     if (name.equals("java")) { //$NON-NLS-1$
545
IFolder sourceFolder = getSourceFolder(monitor);
546                         dstContainer = generateJavaSourceFolder(sourceFolder,
547                                 monitor);
548                     } else if (name.equals("bin")) { //$NON-NLS-1$
549
binary = true;
550                         dstContainer = dst;
551                     }
552                 }
553                 if (dstContainer == null) {
554                     if (isOkToCreateFolder(new File JavaDoc(path.toFile(), name)) == false)
555                         continue;
556                     String JavaDoc folderName = getProcessedString(name, name);
557                     dstContainer = dst.getFolder(new Path(folderName));
558                 }
559                 if (dstContainer instanceof IFolder && !dstContainer.exists())
560                     ((IFolder) dstContainer).create(true, true, monitor);
561                 generateFiles(zipFile, path.append(name), dstContainer, false,
562                         binary, monitor);
563             } else {
564                 if (isOkToCreateFile(new File JavaDoc(path.toFile(), name))) {
565                     if (firstLevel)
566                         binary = false;
567                     InputStream JavaDoc in = null;
568                     try {
569                         in = zipFile.getInputStream(zipEnry);
570                         copyFile(name, in, dst, binary, monitor);
571                     } catch (IOException JavaDoc ioe) {
572                     } finally {
573                         if (in != null)
574                             try {
575                                 in.close();
576                             } catch (IOException JavaDoc ioe2) {
577                             }
578                     }
579                 }
580             }
581         }
582     }
583
584     private IFolder generateJavaSourceFolder(IFolder sourceFolder,
585             IProgressMonitor monitor) throws CoreException {
586         Object JavaDoc packageValue = getValue(KEY_PACKAGE_NAME);
587         String JavaDoc packageName = packageValue != null
588                 ? packageValue.toString()
589                 : null;
590         if (packageName == null)
591             packageName = model.getPluginBase().getId();
592         IPath path = new Path(packageName.replace('.', File.separatorChar));
593         if (sourceFolder != null)
594             path = sourceFolder.getProjectRelativePath().append(path);
595
596         for (int i = 1; i <= path.segmentCount(); i++) {
597             IPath subpath = path.uptoSegment(i);
598             IFolder subfolder = project.getFolder(subpath);
599             if (subfolder.exists() == false)
600                 subfolder.create(true, true, monitor);
601         }
602         return project.getFolder(path);
603     }
604
605     private void copyFile(String JavaDoc fileName, InputStream JavaDoc input, IContainer dst, boolean binary,
606             IProgressMonitor monitor) throws CoreException {
607         String JavaDoc targetFileName = getProcessedString(fileName, fileName);
608
609         monitor.subTask(targetFileName);
610         IFile dstFile = dst.getFile(new Path(targetFileName));
611
612         try {
613             InputStream JavaDoc stream = getProcessedStream(fileName, input, binary);
614             if (dstFile.exists()) {
615                 dstFile.setContents(stream, true, true, monitor);
616             } else {
617                 dstFile.create(stream, true, monitor);
618             }
619             stream.close();
620
621         } catch (IOException JavaDoc e) {
622         }
623     }
624
625     private String JavaDoc getProcessedString(String JavaDoc fileName, String JavaDoc source) {
626         if (source.indexOf('$') == -1)
627             return source;
628         int loc = -1;
629         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
630         boolean replacementMode = false;
631         for (int i = 0; i < source.length(); i++) {
632             char c = source.charAt(i);
633             if (c == '$') {
634                 if (replacementMode) {
635                     String JavaDoc key = source.substring(loc, i);
636                     String JavaDoc value = key.length() == 0 ? "$" //$NON-NLS-1$
637
: getReplacementString(fileName, key);
638                     buffer.append(value);
639                     replacementMode = false;
640                 } else {
641                     replacementMode = true;
642                     loc = i + 1;
643                     continue;
644                 }
645             } else if (!replacementMode)
646                 buffer.append(c);
647         }
648         return buffer.toString();
649     }
650
651     private InputStream JavaDoc getProcessedStream(String JavaDoc fileName, InputStream JavaDoc stream, boolean binary)
652             throws IOException JavaDoc, CoreException {
653         if (binary)
654             return stream;
655
656         InputStreamReader JavaDoc reader = new InputStreamReader JavaDoc(stream);
657         int bufsize = 1024;
658         char[] cbuffer = new char[bufsize];
659         int read = 0;
660         StringBuffer JavaDoc keyBuffer = new StringBuffer JavaDoc();
661         StringBuffer JavaDoc outBuffer = new StringBuffer JavaDoc();
662         StringBuffer JavaDoc preBuffer = new StringBuffer JavaDoc();
663         boolean newLine = true;
664         ControlStack preStack = new ControlStack();
665         preStack.setValueProvider(this);
666
667         boolean replacementMode = false;
668         boolean preprocessorMode = false;
669         boolean escape = false;
670         while (read != -1) {
671             read = reader.read(cbuffer);
672             for (int i = 0; i < read; i++) {
673                 char c = cbuffer[i];
674
675                 if (escape) {
676                     StringBuffer JavaDoc buf = preprocessorMode ? preBuffer : outBuffer;
677                     buf.append(c);
678                     escape = false;
679                     continue;
680                 }
681
682                 if (newLine && c == '%') {
683                     // preprocessor line
684
preprocessorMode = true;
685                     preBuffer.delete(0, preBuffer.length());
686                     continue;
687                 }
688                 if (preprocessorMode) {
689                     if (c == '\\') {
690                         escape = true;
691                         continue;
692                     }
693                     if (c == '\n') {
694                         // handle line
695
preprocessorMode = false;
696                         newLine = true;
697                         String JavaDoc line = preBuffer.toString().trim();
698                         preStack.processLine(line);
699                         continue;
700                     }
701                     preBuffer.append(c);
702                     
703                     continue;
704                 }
705
706                 if (preStack.getCurrentState() == false) {
707                     continue;
708                 }
709
710                 if (c == '$') {
711                     if (replacementMode) {
712                         replacementMode = false;
713                         String JavaDoc key = keyBuffer.toString();
714                         String JavaDoc value = key.length() == 0 ? "$" //$NON-NLS-1$
715
: getReplacementString(fileName, key);
716                         outBuffer.append(value);
717                         keyBuffer.delete(0, keyBuffer.length());
718                     } else {
719                         replacementMode = true;
720                     }
721                 } else {
722                     if (replacementMode)
723                         keyBuffer.append(c);
724                     else {
725                         outBuffer.append(c);
726                         if (c == '\n') {
727                             newLine = true;
728                         } else
729                             newLine = false;
730                     }
731                 }
732             }
733         }
734         return new ByteArrayInputStream JavaDoc(outBuffer.toString().getBytes(project.getDefaultCharset()));
735     }
736     
737     protected double getTargetVersion() {
738         try {
739             IPluginBase plugin = model.getPluginBase();
740             if (plugin instanceof IBundlePluginBase)
741                 return Double.parseDouble(((IBundlePluginBase)plugin).getTargetVersion());
742         } catch (NumberFormatException JavaDoc e) {
743         }
744        return TargetPlatformHelper.getTargetVersion();
745     }
746
747 }
748
Popular Tags