KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > tigris > scarab > util > build > PropertyFileGenerator


1 package org.tigris.scarab.util.build;
2
3 /* ================================================================
4  * Copyright (c) 2000-2002 CollabNet. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are
8  * met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  *
17  * 3. The end-user documentation included with the redistribution, if
18  * any, must include the following acknowlegement: "This product includes
19  * software developed by Collab.Net <http://www.Collab.Net/>."
20  * Alternately, this acknowlegement may appear in the software itself, if
21  * and wherever such third-party acknowlegements normally appear.
22  *
23  * 4. The hosted project names must not be used to endorse or promote
24  * products derived from this software without prior written
25  * permission. For written permission, please contact info@collab.net.
26  *
27  * 5. Products derived from this software may not use the "Tigris" or
28  * "Scarab" names nor may "Tigris" or "Scarab" appear in their names without
29  * prior written permission of Collab.Net.
30  *
31  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
32  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
33  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
34  * IN NO EVENT SHALL COLLAB.NET OR ITS CONTRIBUTORS BE LIABLE FOR ANY
35  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
37  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
39  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
40  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42  *
43  * ====================================================================
44  *
45  * This software consists of voluntary contributions made by many
46  * individuals on behalf of Collab.Net.
47  */

48
49 import java.io.BufferedReader JavaDoc;
50 import java.io.File JavaDoc;
51 import java.io.FileReader JavaDoc;
52 import java.io.FileWriter JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.io.PrintWriter JavaDoc;
55 import java.io.Reader JavaDoc;
56 import java.io.Writer JavaDoc;
57 import java.util.Hashtable JavaDoc;
58 import java.util.List JavaDoc;
59 import java.util.Map JavaDoc;
60 import java.util.StringTokenizer JavaDoc;
61 import java.util.Vector JavaDoc;
62
63 /**
64  * This class is used as ant task backend for the generation
65  * of a property file by use of a template file.
66  *
67  * @author <a HREF="mailto:dabbous@saxess.com">Hussayn Dabbous</a>
68  * @version $Id: PropertyFileGenerator.java 9429 2005-02-25 21:24:30Z dabbous $
69  */

70
71 public class PropertyFileGenerator
72 {
73     /**
74      * This file will be read in and all property values
75      * in it will be replaced by the actual values as they
76      * are in the online environment.
77      */

78     private File JavaDoc templateFile;
79
80     /**
81      * This is the file, which shall contain the
82      * final property name/value pairs. It's overall
83      * layout is similar to the templateFile, but the
84      * property values are generated from the current
85      * online property settings.
86      */

87     private File JavaDoc customFile;
88
89     /**
90      * This Map contains the user specified properties
91      * defined in the list of property files given
92      * when the method setProperties() is called.
93      **/

94     
95     private Map JavaDoc userProperties;
96     
97     /**
98      * Setter: set the path to the template file.
99      * Throws an exception, if the template file does not exist.
100      * @param theTemplatePath
101      * @return
102      */

103     public boolean setTemplate(String JavaDoc theTemplatePath)
104     {
105         boolean status = true;
106         templateFile = new File JavaDoc(theTemplatePath);
107         if(!templateFile.exists())
108         {
109             status = false;
110         }
111         return status;
112     }
113     
114     /**
115      * Return the absolute path to the templateFile, or null, if
116      * no template file has been set.
117      * @return
118      */

119     public String JavaDoc getTemplate()
120     {
121         return (templateFile==null)? null:templateFile.getAbsolutePath();
122     }
123
124     /**
125      * Setter: set the path to the final property file.
126      * Throws an exception, if the customFile exist,
127      * but can't be overwritten (due to permission settings).
128      * @param theCustomPath
129      */

130     public boolean setCustom(String JavaDoc theCustomPath)
131     {
132         boolean status = true;
133         customFile = new File JavaDoc(theCustomPath);
134         if(!customFile.getParentFile().exists())
135         {
136             customFile.getParentFile().mkdir();
137         }
138         
139         if(customFile.exists() &&
140            !customFile.canWrite())
141         {
142             status = false;
143         }
144         
145         return status;
146     }
147
148     /**
149      * Return the absoute path to the customFile, or null, if no path
150      * has been set.
151      * @return
152      */

153     public String JavaDoc getCustom()
154     {
155         String JavaDoc result = null;
156         if ( customFile != null )
157         {
158             result = customFile.getAbsolutePath();
159         }
160         return result;
161     }
162
163     /**
164      * Setter: Create a Map of unresolved properties from
165      * the files defined in theUserpathes.
166      * Throws an exception, if a customFile exist,
167      * but can't be read (due to permission settings).
168      * First definition of a property wins.
169      * @param theUserPath
170      */

171     public boolean setProperties(String JavaDoc theUserPathes)
172     {
173         List JavaDoc filePathes = createPathList(theUserPathes);
174
175         if(filePathes != null)
176         {
177             userProperties = new Hashtable JavaDoc();
178             for(int index=0; index<filePathes.size(); index++)
179             {
180                 File JavaDoc file = new File JavaDoc((String JavaDoc)filePathes.get(index));
181                 if(file.exists())
182                 {
183                     if(!file.canRead())
184                     {
185                         throw new RuntimeException JavaDoc("No Read permission for file ["+filePathes.get(index)+"]");
186                     }
187                     try
188                     {
189                         addUnresolvedProperties(file,userProperties);
190                     }
191                     catch (IOException JavaDoc e)
192                     {
193                         throw new RuntimeException JavaDoc("Could not read file ["+filePathes.get(index)+"]");
194                     }
195                 }
196             }
197         }
198         return true;
199     }
200
201     /**
202      * @param file
203      * @param properties
204      */

205     private void addUnresolvedProperties(File JavaDoc file, Map JavaDoc properties) throws IOException JavaDoc
206     {
207         Reader JavaDoc reader = new FileReader JavaDoc(file);
208         BufferedReader JavaDoc br = new BufferedReader JavaDoc(reader);
209
210         String JavaDoc line;
211
212         while((line=br.readLine()) != null)
213         {
214             String JavaDoc trimmedLine = line.trim();
215             if ( trimmedLine.equals("")
216                 ||trimmedLine.startsWith("#") )
217             {
218                 continue; // forget comment lines and empty lines.
219
}
220             else
221             {
222                 String JavaDoc name = null;
223                 String JavaDoc value = null;
224                 int index = line.indexOf("=");
225                 if(index >=0)
226                 {
227                     name = line.substring(0,index).trim();
228                     value = line.substring(index+1).trim();
229                 }
230                 else
231                 {
232                     name = line.trim();
233                     value = "";
234                 }
235                 
236                 if(properties.get(name) == null)
237                 {
238                     properties.put(name,value);
239                 }
240             }
241         }
242         br.close();
243     }
244
245     /**
246      * Convert a unix style pathlist to a List of pathes.
247      * E.g. the String "path1:path2:path3" is converted into
248      * a three component vector containing "path1", "path2" and
249      * "path3"
250      * If theUserpathes contains no path, this method returns null
251      * @param theUserPathes
252      * @return
253      */

254     private List JavaDoc createPathList(String JavaDoc theUserPathes)
255     {
256         List JavaDoc result = null;
257         StringTokenizer JavaDoc stok = new StringTokenizer JavaDoc(theUserPathes,":");
258         while(stok.hasMoreTokens())
259         {
260             String JavaDoc path = stok.nextToken();
261             if(path.length()==1 && stok.hasMoreTokens())
262             {
263              // deal with windows drive letters, e.g. "c:scarab/build.properties"
264
path+=":"+stok.nextToken();
265             }
266
267             if(result == null)
268             {
269                 result = new Vector JavaDoc();
270             }
271             
272             result.add(path);
273         }
274         return result;
275     }
276     
277     
278     /**
279      * Read the templateFile and behave according to
280      * following rule set:
281      * <ul>
282      * <li> rule 1: Copy every line, which does NOT contain
283      * a property verbatim to the customFile.</li>
284      *
285      * <li> rule 2: Retrieve the current online value of each
286      * property found in the templateFile and generate an
287      * appropriate name/value pair in the customFile.</li>
288      *
289      * <li> rule 3: If a property value starts with a "${" in
290      * the templateFile, keep the value as is. By this we
291      * can propagate ${variables} to the customFile, which
292      * will be resolved during startup of Scarab.</li>
293      * </ul>
294      *
295      */

296     public void execute(PropertyGetter props) throws IOException JavaDoc {
297         
298  
299             Reader JavaDoc reader = new FileReader JavaDoc(templateFile);
300             Writer JavaDoc writer = new FileWriter JavaDoc(customFile);
301             BufferedReader JavaDoc br = new BufferedReader JavaDoc(reader);
302             PrintWriter JavaDoc pw = new PrintWriter JavaDoc(writer);
303
304             String JavaDoc line;
305
306             while((line=br.readLine()) != null)
307             {
308                 String JavaDoc trimmedLine = line.trim();
309                 if ( trimmedLine.equals("")
310                     ||trimmedLine.startsWith("#") )
311                 {
312                     pw.println(line);
313                 }
314                 else
315                 {
316                     String JavaDoc resultLine = createResultLine(line, props);
317                     pw.println(resultLine);
318                 }
319             }
320             pw.close();
321             br.close();
322         
323     }
324
325     /**
326      * Read the current line and behave according to
327      * following rule set:
328      * <ul>
329      * <li> rule 1: If the line does not contain a property, copy
330      * it verbatim.</li>
331      *
332      * <li> rule 2: Retrieve the current online value of the
333      * property found in the line parameter and generate an
334      * appropriate name/value pair in the resultLine.</li>
335      *
336      * <li> rule 3: If a property value starts with a "${" in
337      * the line, keep the value as is. By this we
338      * can propagate ${variables} to the customFile, which
339      * will be "resolved late" (during startup of Scarab).</li>
340      * </ul>
341      * @param line
342      * @param props
343      * @return
344      */

345     private String JavaDoc createResultLine(String JavaDoc line, PropertyGetter props)
346     {
347         String JavaDoc propertyName = null;
348         String JavaDoc templateValue = null;
349         String JavaDoc resultLine;
350         int index = line.indexOf("=");
351         if(index >=0)
352         {
353             propertyName = line.substring(0,index).trim();
354             templateValue = line.substring(index+1).trim();
355             int beginOfValue = line.indexOf(templateValue,index+1);
356             resultLine = (beginOfValue == -1) ?
357                          line : line.substring(0,beginOfValue);
358         }
359         else
360         {
361             propertyName = line.trim();
362             templateValue = "";
363             int endOfLine = line.indexOf(propertyName)+propertyName.length();
364             resultLine = ((endOfLine == -1) ? line : line.substring(0,endOfLine)) + " = ";
365         }
366         
367         String JavaDoc newValue = (String JavaDoc) userProperties.get(propertyName);
368
369         if(newValue == null)
370         {
371             newValue = (String JavaDoc) props.getProperty(propertyName,templateValue);
372             if(newValue == null)
373             {
374                 newValue = "";
375             }
376         }
377         else if(newValue.equalsIgnoreCase("**generated**"))
378         {
379             String JavaDoc dbtype = (String JavaDoc)props.getProperty("scarab.database.type","hypersonic");
380             if(dbtype.equals(""))
381             {
382                 dbtype="hypersonic";
383             }
384             newValue = "${"+propertyName+"."+dbtype+"}";
385         }
386
387         if ( newValue.equals(templateValue))
388         {
389             resultLine = line;
390         }
391         else
392         {
393             resultLine += newValue;
394         }
395         return resultLine;
396     }
397 }
398
Popular Tags