Download Report

Transcript
6.6. VELOCITY TEMPLATES USED FOR CODE GENERATION
69
by providing space characters in the code to be generated and making no formatting of the Velocity functions themselves. To view the generated output see for instance CustomerBean.java in
Appendix B.
6.6.3 Velocity macros
In Velocity it is possible to define macros. A macro can be defined within a template, and must be
specified before it is used. A macro defined in a template is not accesible from other templates.
The file VM_global_library.vm defines global Velocity macros used in various templates.
An example of such a macro is the separateParameters macro Figure 6.12 which is used to
make commaseparated lists. Commaseparated lists are necessary when generating parameter lists
in method declarations.
#macro( separateParameters $list $sep )
#foreach( $element in $list )#if( $velocityCount > 1 )$sep#end \
$element.getType() $element.getName()#end
#end
Figure 6.12: The separateParameters macro. A line break is added in the macro due to layout of
this report.
The code snippet shows the definition of the separateParameters macro which given a collection and a some separator (e.g. ’,’ ), will take every element in the collection and separate them
by the specified separator. The separator sign will not be used before the first element, and not
behind the last, since the value of $velocityCount is increased by one for each element in the list.
6.6.4 The Utility class
The Utility class found in Appendix F contains helper methods needed by the Velocity templates.
E.g. the Utility class specifies a firstCharAsCapital(String s) method which return
a String with the first letter capitalized. This method is used when generating the names of get
and set methods to capitalize the name of the fields, e.g. setName. Another method specified in
the Utility class is the runTemplate(String templateName, String fileName,
String directory) which is used whenever it is necessary to run a template from within
another template. This method is thus used in the template generate.vm that controls which
templates to run.
The Utility class is implemented as a singleton since only one instance is needed as Velocity
templates cannot call static methods, as explained in Section 4.7.4 on page 39. During instantiation the static Utility instance will bind itself in the VelocityContext under the key ’util’ to make
itself reachable from the Velocity templates. Thus all methods defined in the Utility class are
available when using the $util variable in the Velocity templates.
6.6.5 How automatic generation of primary keys is implemented
The Velocity template GUIDProviderTemplate.vm will generate a class called GUIDProvider
implementing the algorithm described in Section 4.8.1 to automatically generate primary keys
for EJB applications. An implementation of the GUIDProvider class can be found in Appendix
B.