Customizing Liferay service builder templates

Liferay service builder code generation is based on Freemarker templates. The default templates come packaged inside the portal jar files. You can take a look at them for example in Github (note that those are from master branch – if you want to make modifications you should probably locate template files that correspond to the version of your Liferay setup). Another option to see the templates is to locate the portal-impl.jar and extract template files from there. The templates are in com/liferay/portal/tools/servicebuilder/dependencies package/folder.

In order to make service builder use your modified template you need to make the template available and then change the ant build scripts to make use of it.

1. Create sb_templates directory underneath liferay-plugins-sdk -root folder and place your modified template there. I suggest using the original template file name to keep things simple.

2. Modify the ant build script to override the default templates with your own. The related build file is build-common-plugin.xml (located in liferay-plugins-sdk folder). Look for the “build-service” target. There you need to make two changes

2.1 Locate the path with id=”service.classpath”. The service builder will use this path to locate the templates. Add following highlighted line as the first item

<path id="service.classpath">
    <pathelement location="${project.dir}/sb_templates" />
    <path refid="lib.classpath" />
	<path refid="portal.classpath" />
	<fileset dir="${app.server.lib.portal.dir}" 
          includes="commons-digester.jar,commons-lang.jar,easyconf.jar" />
	<fileset dir="docroot/WEB-INF/lib" includes="*.jar" />			
	<pathelement location="docroot/WEB-INF/classes" />
</path>

2.2 Modify the java task, adding arguments like the following line for each template you want to override

<java
	classname="com.liferay.portal.tools.servicebuilder.ServiceBuilder"
	classpathref="service.classpath"
	outputproperty="service.test.output">
	<arg value="-Dexternal-properties=com/liferay/portal/tools/dependencies/portal-tools.properties" />
	<arg value="-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger" />
	<arg value="-Dservice.tpl.service_clp_serializer=vt_service_clp_serializer.ftl" />					
	<arg value="service.input.file=${service.input.file}" />
	<arg value="service.hbm.file=${basedir}/docroot/WEB-INF/src/META-INF/portlet-hbm.xml" />

3. Execute service builder. Remember to check the output to see if there are some errors in your templates. If your modified template is not found, service builder may just skip generating the file. This can be confusing if you generating on top of existing files. If you suspect the files is not being regenerated compare the last modified timestamp to other generated files.