Thursday, October 29, 2009

HowTo: Build NetBeans projects for multiple environments

Sometimes you'll need to build a project out of NetBeans for different environments (e.g. your local Windows box or that Linux test server) but certain project files will need different values (e.g. file paths, DB credentials) for each environment.

Here's how to do that without much fuss or inconvenience:

  • create a conf directory in the project root (nb: conf can be whatever value you like better)

    • create a directory, for each environment you intend to build for, under the conf directory

      • e.g. dev, test, demo, prod


    • into each of these leaf directories create a file called build.properties

      • populate each build.properties file with environment-specific values


        • e.g. jdbc_url=jdbc:derby:myTestDB


  • modify the existing build.xml file located in the root of your NetBeans project, adding 2 XML-stanzas/ant-targets:

    • this one (i.e. -pre-compile) causes NetBeans to prompt you every time you build with a dialog that offers you the environment to build for, the default is settable and the dialog is easily dismissed by a click or an Enter keystroke:



      • <target name="-pre-compile">
        <input message="Choose a build type:"
        validargs="dev,demo,test,prod"
        addproperty="build.type"
        defaultvalue="dev"
        />
        <property file="conf/${build.type}/build.properties"/>
        </target>

    • this one (i.e. -post-compile) causes NetBeans to do whatever you want e.g. string replacement in a file e.g. web.xml:




      • <target name="-post-compile">
        <replace file="${build.web.dir}/WEB-INF/web.xml" token="@log_dir@" value="${log_dir}" />
        </target>


      • e.g. above, the value of log_dir will be taken from e.g. conf\prod\build.properties and will globally replace the token @log_dir@ in the file web\WEB-INF\web.xml, relative to the NetBeans project's root, when you select a prod build.


  • Lastly, complete any setup e.g. modify the targets of any string replacements

Buld your project and you should be prompted for a target environment.

NB: file paths in the build.properties are subject to the usual Java gotchas wrt/Window path separators i.e.

  • this: log_dir=C:\tmp\myProject\logs

    • will become this: C:tmpmyProjectlogs

    • after string replacement


  • the usual workarounds are available e.g.

    • use this instead: log_dir=C:\\tmp\\myProject\\logs

    • or this works too: log_dir=C:/tmp/myProject/logs


Build on it!

No comments: