1   
2   
3   
4   
5   
6   
7   
8   
9   
10  
11  package com.legstar.codegen;
12  
13  import java.io.BufferedWriter;
14  import java.io.File;
15  import java.io.FileOutputStream;
16  import java.io.IOException;
17  import java.io.OutputStreamWriter;
18  import java.io.StringWriter;
19  import java.io.Writer;
20  import java.net.InetAddress;
21  import java.net.URI;
22  import java.net.URISyntaxException;
23  import java.net.UnknownHostException;
24  import java.nio.charset.Charset;
25  import java.text.SimpleDateFormat;
26  import java.util.Calendar;
27  import java.util.Map;
28  import java.util.Random;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.velocity.VelocityContext;
33  import org.apache.velocity.app.Velocity;
34  import org.apache.velocity.exception.MethodInvocationException;
35  import org.apache.velocity.exception.ParseErrorException;
36  import org.apache.velocity.exception.ResourceNotFoundException;
37  
38  
39  
40  
41  
42  public final class CodeGenUtil {
43  
44      
45      public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
46  
47      
48      private static Random mRandom = new Random();
49  
50      
51      public static final String JAXB_TYPE_SUFFIX = "Type";
52  
53      
54      public static final String CRLF = System.getProperty("line.separator");
55  
56      
57      private static final Log LOG = LogFactory.getLog(CodeGenUtil.class);
58  
59      
60  
61  
62      private CodeGenUtil() {
63      }
64  
65      
66  
67  
68  
69  
70  
71  
72      public static void checkDirectory(final String dir, final boolean create,
73              final String errorDirName) {
74          try {
75              checkDirectory(dir, create);
76          } catch (IllegalArgumentException e) {
77              throw new IllegalArgumentException(errorDirName + ": "
78                      + e.getMessage());
79          }
80      }
81  
82      
83  
84  
85  
86  
87  
88  
89      public static void checkDirectory(final File fdir, final boolean create,
90              final String errorDirName) {
91          try {
92              checkDirectory(fdir, create);
93          } catch (IllegalArgumentException e) {
94              throw new IllegalArgumentException(errorDirName + ": "
95                      + e.getMessage());
96          }
97      }
98  
99      
100 
101 
102 
103 
104 
105     public static void checkDirectory(final String dir, final boolean create) {
106 
107         if (dir == null || dir.length() == 0) {
108             throw (new IllegalArgumentException(
109                     "No directory name was specified"));
110         }
111 
112         checkDirectory(new File(dir), create);
113     }
114 
115     
116 
117 
118 
119 
120 
121     public static void checkDirectory(final File fdir, final boolean create) {
122 
123         if (fdir == null) {
124             throw (new IllegalArgumentException(
125                     "No directory name was specified"));
126         }
127 
128         if (!fdir.exists()) {
129             if (!create) {
130                 throw (new IllegalArgumentException(fdir.getName()
131                         + " does not exist"));
132             } else {
133                 if (!fdir.mkdirs()) {
134                     throw (new IllegalArgumentException(
135                             "Could not create directory " + fdir.getName()));
136                 } else {
137                     return;
138                 }
139             }
140         }
141         if (!fdir.isDirectory()) {
142             throw (new IllegalArgumentException(fdir.getName()
143                     + " is not a directory"));
144         }
145         if (!fdir.canWrite()) {
146             throw (new IllegalArgumentException("Directory " + fdir.getName()
147                     + " is not writable"));
148         }
149     }
150 
151     
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165     public static File getFile(final String dir, final String filename) {
166         File file = new File(filename);
167         if (file.isAbsolute()) {
168             return file;
169         }
170         if (dir == null || dir.length() == 0) {
171             return new File(filename);
172         }
173         return new File(dir, filename);
174     }
175 
176     
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188     public static File getFile(final File fdir, final String filename) {
189         File file = new File(filename);
190         if (file.isAbsolute()) {
191             return file;
192         }
193         return new File(fdir, filename);
194     }
195 
196     
197 
198 
199 
200 
201 
202 
203     public static String classNormalize(final String noun) {
204         String className = null;
205         if (noun != null && noun.length() > 0) {
206             className = noun.substring(0, 1).toUpperCase();
207             if (noun.length() > 1) {
208                 className += noun.substring(1, noun.length());
209             }
210         }
211         return className;
212     }
213 
214     
215 
216 
217 
218 
219 
220 
221     public static String relativeLocation(final String packageName) {
222         if (packageName == null || packageName.length() == 0) {
223             return "";
224         }
225         String loc = packageName.replace('.', '/');
226         if (loc.charAt(0) != '/') {
227             loc = '/' + loc;
228         }
229         if (loc.charAt(loc.length() - 1) != '/') {
230             loc += '/';
231         }
232         return loc;
233     }
234 
235     
236 
237 
238 
239 
240 
241 
242 
243 
244     public static String classFilesLocation(final String rootDirName,
245             final String packageName, final boolean create) {
246         if (rootDirName == null || rootDirName.length() == 0) {
247             throw (new IllegalArgumentException(
248                     "No root directory name was specified"));
249         }
250         String dir;
251         if (packageName != null && packageName.length() > 0) {
252             dir = rootDirName + '/' + CodeGenUtil.relativeLocation(packageName);
253         } else {
254             dir = rootDirName;
255         }
256         if (create) {
257             CodeGenUtil.checkDirectory(dir, true);
258         }
259         return dir;
260     }
261 
262     
263 
264 
265 
266 
267 
268 
269 
270 
271 
272     public static File classFilesLocation(final File rootDir,
273             final String packageName, final boolean create) {
274         File dir = rootDir;
275         if (packageName != null && packageName.length() > 0) {
276             dir = new File(rootDir, CodeGenUtil.relativeLocation(packageName));
277         }
278         if (create) {
279             CodeGenUtil.checkDirectory(dir, true);
280         }
281         return dir;
282     }
283 
284     
285 
286 
287 
288 
289 
290 
291 
292 
293 
294     public static void initVelocity() throws CodeGenVelocityException {
295         ClassLoader loader = Thread.currentThread().getContextClassLoader();
296         try {
297             Velocity.addProperty("resource.loader", "classpath");
298             Velocity.addProperty("classpath.resource.loader.description",
299                     "Velocity Classpath Resource Loader");
300             Velocity.addProperty("classpath.resource.loader.class",
301                     "org.apache.velocity.runtime.resource.loader."
302                             + "ClasspathResourceLoader");
303             Velocity.addProperty("classpath.resource.loader.cache", true);
304             Thread.currentThread().setContextClassLoader(
305                     Velocity.class.getClassLoader());
306             Velocity.init();
307         } catch (Exception e) {
308             throw new CodeGenVelocityException(e);
309         } finally {
310             Thread.currentThread().setContextClassLoader(loader);
311         }
312     }
313 
314     
315 
316 
317 
318 
319 
320     public static VelocityContext getContext(final String generatorName) {
321         VelocityContext context = new VelocityContext();
322         context.put("formattedDate", now());
323         context.put("generatorName", generatorName);
324         return context;
325     }
326 
327     
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338     public static void processTemplate(final String generatorName,
339             final String templateName, final String modelName,
340             final Object model, final Map < String, Object > parameters,
341             final File targetFile) throws CodeGenMakeException {
342 
343         processTemplate(generatorName, templateName, modelName, model,
344                 parameters, targetFile, null);
345     }
346 
347     
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360     public static void processTemplate(final String generatorName,
361             final String templateName, final String modelName,
362             final Object model, final Map < String, Object > parameters,
363             final File targetFile, final String targetCharsetName)
364             throws CodeGenMakeException {
365 
366         if (LOG.isDebugEnabled()) {
367             LOG.debug("Processing template");
368             LOG.debug("Template name       = " + templateName);
369             LOG.debug("Target file         = " + targetFile);
370             LOG.debug("Target charset name = " + targetCharsetName);
371             if (parameters != null) {
372                 for (String key : parameters.keySet()) {
373                     Object value = parameters.get(key);
374                     LOG.debug("Parameter " + key + " = " + value);
375                 }
376             }
377         }
378         VelocityContext context = CodeGenUtil.getContext(generatorName);
379         context.put(modelName, model);
380         context.put("serialVersionID", Long.toString(mRandom.nextLong()) + 'L');
381         if (parameters != null) {
382             for (String key : parameters.keySet()) {
383                 context.put(key, parameters.get(key));
384             }
385         }
386         StringWriter w = new StringWriter();
387 
388         try {
389             Velocity.mergeTemplate(templateName, "UTF-8", context, w);
390             Writer out = null;
391             try {
392                 FileOutputStream fos = new FileOutputStream(targetFile);
393                 OutputStreamWriter osw;
394                 if (targetCharsetName == null) {
395                     osw = new OutputStreamWriter(fos);
396                 } else {
397                     osw = new OutputStreamWriter(fos, targetCharsetName);
398                 }
399                 out = new BufferedWriter(osw);
400                 out.write(w.toString());
401             } catch (IOException e) {
402                 throw new CodeGenMakeException(e);
403             } finally {
404                 if (out != null) {
405                     out.close();
406                 }
407             }
408         } catch (ResourceNotFoundException e) {
409             throw new CodeGenMakeException(e);
410         } catch (ParseErrorException e) {
411             throw new CodeGenMakeException(e);
412         } catch (MethodInvocationException e) {
413             throw new CodeGenMakeException(e);
414         } catch (Exception e) {
415             throw new CodeGenMakeException(e);
416         }
417     }
418 
419     
420 
421 
422 
423 
424     public static String now() {
425         Calendar cal = Calendar.getInstance();
426         SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
427         return sdf.format(cal.getTime());
428     }
429 
430     
431 
432 
433 
434 
435 
436     public static void checkHttpURI(final String httpUri)
437             throws CodeGenMakeException {
438         try {
439             if (httpUri == null || httpUri.length() == 0) {
440                 throw new CodeGenMakeException("You must specify a valid URI");
441             }
442             URI uri = new URI(httpUri);
443             if (uri.getScheme() == null
444                     || uri.getScheme().compareToIgnoreCase("http") != 0) {
445                 throw new CodeGenMakeException("URI " + uri
446                         + " must have http scheme");
447             }
448         } catch (URISyntaxException e) {
449             throw new CodeGenMakeException(e);
450         }
451 
452     }
453 
454     
455 
456 
457 
458 
459 
460 
461     public static void checkCharset(final String charset)
462             throws CodeGenMakeException {
463         if (charset == null || charset.length() == 0) {
464             throw new CodeGenMakeException(
465                     "You must specify a valid character set");
466         }
467         if (!Charset.isSupported(charset)) {
468             throw new CodeGenMakeException("Character set " + charset
469                     + " is not supported");
470         }
471     }
472 
473     
474 
475 
476 
477 
478 
479 
480     public static String fieldNameFromPropertyName(final String propertyName) {
481         String fieldName = null;
482         if (propertyName != null && propertyName.length() > 0) {
483             fieldName = propertyName.substring(0, 1).toLowerCase();
484             if (propertyName.length() > 1) {
485                 fieldName += propertyName.substring(1, propertyName.length());
486             }
487         }
488         return fieldName;
489     }
490 
491     
492 
493 
494 
495 
496 
497 
498     public static String propertyNameFromFieldName(final String fieldName) {
499         String propertyName = null;
500         if (fieldName != null && fieldName.length() > 0) {
501             propertyName = fieldName.substring(0, 1).toUpperCase();
502             if (fieldName.length() > 1) {
503                 propertyName += fieldName.substring(1, fieldName.length());
504             }
505         }
506         return propertyName;
507     }
508 
509     
510 
511 
512 
513 
514 
515 
516     public static String propertyNameFromJaxbType(final String jaxbType) {
517         String propertyName = null;
518         if (jaxbType != null && jaxbType.length() > 0) {
519             propertyName = jaxbType;
520             if (propertyName.endsWith(JAXB_TYPE_SUFFIX)) {
521                 propertyName = propertyName.substring(0, propertyName.length()
522                         - JAXB_TYPE_SUFFIX.length());
523             }
524         }
525         return propertyName;
526     }
527 
528     
529 
530 
531 
532 
533     public static String getLocalIPAddress() {
534         try {
535             InetAddress addr = InetAddress.getLocalHost();
536             byte[] ipAddr = addr.getAddress();
537             String ipAddrStr = "";
538             for (int i = 0; i < ipAddr.length; i++) {
539                 if (i > 0) {
540                     ipAddrStr += ".";
541                 }
542                 ipAddrStr += ipAddr[i] & 0xFF;
543             }
544             return ipAddrStr;
545         } catch (UnknownHostException e) {
546             return "";
547         }
548 
549     }
550 }