<?xml version="1.0" encoding="UTF-8"?>
<project name="appfuse" basedir="." default="package-web">

    <!-- import properties (app settings, classpath, jar file locations) -->
    <import file="properties.xml"/>

    <target name="init" description="defines custom tasks">
        <!-- Taskdefs -->
        <taskdef resource="net/sf/antcontrib/antcontrib.properties" classpath="${ant-contrib.jar}"/>
        
        <!-- Ensure that Ant 1.6.2+ is being used -->
        <available classname="org.apache.tools.ant.DynamicAttribute" property="ant-1.6.2"/>
        <fail unless="ant-1.6.2" message="AppFuse requires Ant 1.6.2 for faster unit testing"/>

        <!-- Check that junit.jar is in $ANT_HOME/lib or junit task fails -->
        <available classname="junit.framework.TestCase" property="junit.present"/>
        <fail unless="junit.present" message="Please copy junit.jar into ${env.ANT_HOME}/lib"/>

        <taskdef name="dbunit" classname="org.dbunit.ant.DbUnitTask" classpathref="dao.test.classpath"/>

        <!-- Test for Tomcat 5.0.x -->
        <available classname="org.apache.catalina.ant.SessionsTask" property="tomcat5">
            <classpath>
                <pathelement path="${tomcat.home}/server/lib/catalina-ant.jar"/>
            </classpath>
        </available>

        <!-- Test for Tomcat 5.5.x -->
        <available file="${tomcat.home}/common/lib/jasper-compiler-jdt.jar" property="tomcat5.5"/>

        <!-- Conditionally set property for converting to JSP 2.0 -->
        <condition property="convert.to.jsp2">
            <equals arg1="${jsp.2}" arg2="true"/>
        </condition>

        <!-- Conditionally set property for pre-compiling JSPs -->
        <condition property="precompile.jsp">
            <equals arg1="${jsp.precompile}" arg2="true"/>
        </condition>
    </target>
    
    <!-- Check timestamp on files -->
    <target name="prepare" depends="init" description="create target directories">
        <tstamp/>
        <tstamp><format property="copyright.year" pattern="yyyy"/></tstamp>
        <echo message="Preparing target directory '${webapp.target}'"/>
        <mkdir dir="${webapp.target}"/>
        <mkdir dir="${webapp.target}/WEB-INF"/>
        <mkdir dir="${webapp.dist}"/>
        <delete dir="${out.instr.dir}"/>

        <!-- Make sure hibernatedoclet is necessary -->
        <uptodate property="hibernatedoclet.unnecessary">
            <srcfiles dir="src/dao" includes="**/*.java"/>
            <srcfiles dir="${build.dir}/dao/gen" includes="**/*.java"/>
            <mapper type="glob" from="*.java" to="${build.dir}/dao/classes/*.class"/>
        </uptodate>

        <!-- Make sure webdoclet is necessary -->
        <uptodate property="webdoclet.uptodate">
            <srcfiles dir="src/web" includes="**/*.java"/>
            <srcfiles dir="${build.dir}/web/gen" includes="**/*.java"/>
            <mapper type="glob" from="*.java" to="${build.dir}/web/classes/*.class"/>
        </uptodate>

        <condition property="webdoclet.unnecessary">
            <and>
                <equals arg1="${webdoclet.uptodate}" arg2="true"/>
                <available file="${webapp.target}/WEB-INF/web.xml"/>
            </and>
        </condition>

    </target>

    <!-- List of variables in .properties files that will be replaced at
         build time -->
    <filterset id="variables.to.replace">
        <filter token="APPNAME" value="${webapp.name}"/>
        <filter token="ENCRYPT-ALGORITHM" value="${encrypt.algorithm}"/>
        <filter token="ERROR-MAILTO" value="${error.mailTo}"/>
        <filter token="ERROR-MAILFROM" value="${mail.default.from}"/>
        <filter token="ERROR-MAILHOST" value="${mail.host}"/>
        <filter token="ERROR-SERVER" value="${error.server}"/>
        <filter token="SECURE-LOGIN" value="${secure.login}"/>
        <filter token="HIBERNATE-DIALECT" value="${hibernate.dialect}"/>
    </filterset>

    <!-- List of variables to replace when configuring Tomcat -->
    <filterset id="db.variables">
        <filter token="DB-DRIVERNAME" value="${database.driver_class}"/>
        <filter token="DB-URL" value="${database.url}"/>
        <filter token="DB-USERNAME" value="${database.username}"/>
        <filter token="DB-PASSWORD" value="${database.password}"/>
    </filterset>

    <!-- Copy any resource or configuration files -->
    <target name="copy-resources" depends="prepare"
        description="Copy .properties and .xml files from source directory">
        <copy todir="${build.dir}/web/classes" includeEmptyDirs="no">
            <fileset dir="web/WEB-INF/classes">
                <exclude name="ApplicationResources_zh*.properties"/>
                <include name="*.properties"/>
                <include name="*.xml"/>
                <include name="*.vm"/>
            </fileset>
            <filterset refid="variables.to.replace"/>
        </copy>
        <native2ascii src="web/WEB-INF/classes" dest="${build.dir}/web/classes" 
            includes="ApplicationResources_zh*.properties" encoding="UTF-8"/>
        <generate-database-properties/>
        <copy todir="${build.dir}/web/classes" file="database.properties"/>
    </target>

    <!-- =================================================================== -->
    <!-- The "copy-web-files" target copies the static web resources portion -->
    <!-- of your web application source into the build target area           -->
    <!-- =================================================================== -->
    <target name="copy-web-files" depends="prepare" description="Copy static files">
        <echo message="Copying static files"/>
        <!-- Remove the copy block below if you're not displaying version/copyright in the footer -->
        <tstamp>
            <format property="build.timestamp" pattern="EEEE MMM dd, yyyy 'at' hh:mm a zz"/>
        </tstamp>
        <copy todir="${webapp.target}">
            <fileset dir="web" includes="common/footer.jsp"/>
            <filterset>
                <filter token="APPVERSION" value="${webapp.version}"/>
                <filter token="COPYRIGHT-YEAR" value="${copyright.year}"/>
                <filter token="BUILD-TIME" value="${build.timestamp} by ${user.name}"/>
            </filterset>
        </copy>
        <copy todir="${webapp.target}" includeEmptyDirs="no">
            <fileset dir="${basedir}/web">
                <include name="**"/>
                <exclude name="pages/**"/>
                <exclude name="**/classes/**"/>
                <exclude name="**/*-resources.xml"/>
            </fileset>
        </copy>
        <!-- Copy JSP Pages under WEB-INF/pages -->
        <copy todir="${webapp.target}/WEB-INF">
            <fileset dir="${basedir}/web">
                <include name="pages/**/*.jsp"/>
            </fileset>
            <fileset dir="${struts.dir}" includes="*.xml"/>
            <fileset dir="${basedir}/web/WEB-INF" includes="**/*-resources.xml"/>
            <filterset refid="db.variables"/>
        </copy>
        <!-- Copy *.txt files so they can be included in release notes -->
        <copy todir="${webapp.target}">
            <fileset dir="${basedir}">
                <include name="*.txt"/>
            </fileset>
        </copy>
    </target>

    <!-- =================================================================== -->
    <!-- The "jsp-2" replaces JSTL's <c:out> tags with what's in "value" and -->
    <!-- removes JSTL's 1.0 JARS                                             -->
    <!-- =================================================================== -->
    <target name="jsp-2" depends="webdoclet" if="convert.to.jsp2"
        description="Convert JSP 1.2 tags (i.e. JSTL) to JSP 2.0">
        <echo level="info">Change JSTL Tags to Run-Time</echo>
        <replaceregexp flags="g">
            <regexp pattern='uri="http://java.sun.com/jstl/core"'/>
            <substitution expression='uri="http://java.sun.com/jsp/jstl/core"'/>
            <fileset dir="${webapp.target}" includes="**/*.jsp"/>
        </replaceregexp>
        <replaceregexp flags="g">
            <regexp pattern='uri="http://java.sun.com/jstl/fmt"'/>
            <substitution expression='uri="http://java.sun.com/jsp/jstl/fmt"'/>
            <fileset dir="${webapp.target}" includes="**/*.jsp"/>
        </replaceregexp>
        <replaceregexp flags="g">
            <regexp pattern='uri="http://java.sun.com/jstl/sql"'/>
            <substitution expression='uri="http://java.sun.com/jsp/jstl/sql"'/>
            <fileset dir="${webapp.target}" includes="**/*.jsp"/>
        </replaceregexp>

        <echo level="info">Removing JSTL's c:out tags</echo>
        <replaceregexp flags="g">
            <regexp pattern='&lt;c:out value="([^"]*)"/&gt;'/>
            <substitution expression="\1"/>
            <fileset dir="${webapp.target}" includes="**/*.jsp"/>
        </replaceregexp>

        <echo level="info">Replacing 2.3 DTD with 2.4 XSD in web.xml</echo>
        <replace file="${webapp.target}/WEB-INF/web.xml">
            <replacetoken><![CDATA[<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>]]></replacetoken>
            <replacevalue><![CDATA[<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
]]></replacevalue>
        </replace>
    </target>
    
    <!-- =================================================================== -->
    <!-- The "stage-web" is used to gather all static web recourses in the   -->
    <!-- build directory.                                                    -->
    <!-- =================================================================== -->
    <target name="stage-web" depends="copy-resources,copy-web-files"
        description="Calls other targets to gather static resources"/>
        
    <!-- =================================================================== -->
    <!-- The "hibernatedoclet" target generates Hibernate mapping files      -->
    <!-- based on XDoclet marked-up Plain Old Java Object (POJO)             -->
    <!-- =================================================================== -->
    <target name="hibernatedoclet" depends="prepare" unless="hibernatedoclet.unnecessary"
        description="Generate Hibernate mapping files">

        <taskdef name="hibernatedoclet"
            classname="xdoclet.modules.hibernate.HibernateDocletTask"
            classpathref="xdoclet.classpath"/>
        
        <!-- generate hibernate files -->
        <hibernatedoclet destdir="${build.dir}/dao/gen" mergedir="metadata/dao"
            excludedtags="@version,@author" addedtags="@xdoclet-generated at ${TODAY}"
            force="${xdoclet.force}">
            <fileset dir="src/dao"/>
            <hibernate validatexml="true" version="3.0"/>
        </hibernatedoclet>
    </target>

    <target name="compile-dao" depends="hibernatedoclet" description="Compile dao module">
        <compile module="dao"/>
    </target>

    <target name="package-dao" depends="prepare,compile-dao" description="Package DAO JAR">
        <!-- Copy XML files from source -->
        <copy todir="${build.dir}/dao/gen">
            <fileset dir="src/dao" includes="**/*.xml" excludes="**/*-${dao.type}.xml"/>
            <filterset refid="variables.to.replace"/>
        </copy>
        <!-- Copy Spring configuration files -->
        <mkdir dir="${build.dir}/dao/gen/META-INF"/>
        <copy overwrite="true" tofile="${build.dir}/dao/gen/META-INF/applicationContext-${dao.type}.xml">
            <fileset dir="src/dao" includes="**/*-${dao.type}.xml"/>
            <filterset refid="variables.to.replace"/>
        </copy>
        <jar destfile="${dist.dir}/${webapp.name}-dao.jar">
            <manifest>
                <attribute name="Class-Path" value="${webapp.name}-dao.jar"/>
            </manifest>
            <fileset dir="${build.dir}/dao/classes"/>
            <fileset dir="${build.dir}/dao/gen" includes="**/*.xml" 
                excludes="**/applicationContext-*.xml"/>
            <metainf dir="${build.dir}/dao/gen/META-INF"/>
        </jar>
    </target>
   
    <target name="test-dao" depends="copy-resources,package-dao,db-load,check-debug" description="Test dao module">
        <test-module module="dao" additional.src.dirs="${build.dir}/dao/gen"/>
    </target>
  
    <!-- Service -->
    <target name="compile-service" depends="package-dao" description="Compile service module">
        <compile module="service"/>
    </target>

    <target name="package-service" depends="compile-service">
        <mkdir dir="${build.dir}/service/classes/META-INF"/>
        <copy tofile="${build.dir}/service/classes/META-INF/applicationContext-service.xml">
            <fileset dir="src/service" includes="**/*-service.xml"/>
        </copy>
        <jar destfile="${dist.dir}/${webapp.name}-service.jar">
            <manifest>
                <attribute name="Class-Path"
                    value="${webapp.name}-dao.jar ${webapp.name}-service.jar"/>
            </manifest>
            <fileset dir="${build.dir}/service/classes" includes="**/*.class"/>
            <metainf dir="${build.dir}/service/classes/META-INF"/>
        </jar>
    </target>

    <target name="test-service" depends="copy-resources,compile-service,check-debug" description="Test service module">
        <test-module module="service"/>
    </target>

    <!-- Generate ActionForms from POJOs -->
    <target name="gen-forms" depends="prepare" unless="webdoclet.uptodate"
        description="Generates ActionForms from POJOs">
        <taskdef name="xdoclet" classname="xdoclet.DocletTask"
            classpathref="xdoclet.classpath"/>

        <!-- generate struts forms -->
        <xdoclet destdir="${build.dir}/web/gen" excludedtags="@version,@author"
            addedtags="@xdoclet-generated at ${TODAY}" force="${xdoclet.force}" 
            mergedir="metadata/web">
            <fileset dir="src/dao"/>

            <configParam name="basePackageName" value="org.appfuse"/>

            <!-- generate struts forms -->
            <actionform templateFile="metadata/templates/struts_form.xdt">
                <packageSubstitution packages="model" substituteWith="webapp.form"/>
            </actionform>
        </xdoclet>
    </target>

    <target name="compile-web" depends="package-service,stage-web,gen-forms" description="Compile web module">
        <compile module="web" additional.src.dirs="${build.dir}/web/gen"/>
    </target>

    <!-- Simple alias to compile-web -->
    <target name="compile" depends="compile-web" 
        description="alias for compile-web"/>

    <target name="webdoclet" depends="compile-web" unless="webdoclet.unnecessary"
        description="Generate JSP TLD and other web artifacts">
        <taskdef name="webdoclet" classname="xdoclet.modules.web.WebDocletTask">
            <classpath>
                <path refid="xdoclet.classpath"/>
                <path refid="web.compile.classpath"/>
            </classpath>
        </taskdef>
        <webdoclet destdir="${webapp.target}/WEB-INF" force="${xdoclet.force}"
            mergedir="metadata/web" excludedtags="@version,@author" verbose="true">
            <fileset dir="src/web"/>
            <fileset dir="${build.dir}/web/gen"/>
            <jsptaglib validateXML="true"
                description="Custom tag library for this application"
                shortName="${webapp.name}" filename="${webapp.name}.tld"/>
            <strutsconfigxml validateXML="true" version="1.2"/>
            <strutsvalidationxml version="1.1.3"/>
        </webdoclet>
    </target>

    <!-- Simple alias to package-web -->
    <target name="war" depends="package-web" description="alias for package-web"/>

    <target name="package-web" depends="compile-web,compile-jsp" description="Package WAR">
        <!-- If Servlet 2.4, uncomment the <dispatcher> elements in filter-mappings -->
        <if>
            <or>
                <isset property="convert.to.jsp2"/>
            </or>
            <then>
                <replaceregexp flags="g"
                    file="${webapp.target}/WEB-INF/web.xml"
                    match='&lt;!--dispatcher&gt;'
                    replace='&lt;dispatcher&gt;'/>
                <replaceregexp flags="g"
                    file="${webapp.target}/WEB-INF/web.xml"
                    match='&lt;/dispatcher--&gt;'
                    replace='&lt;/dispatcher&gt;'/>
                <property name="jstl.final.dir" value="${jsp2.jstl.dir}"/> 
            </then>
            <else>
                <property name="jstl.final.dir" value="${jstl.dir}"/>
            </else> 
        </if>
        <echo>Preparing tomcat-context.xml for inclusion in war</echo>
        <!-- Copy tomcat-context.xml file to context.xml -->
        <if>
            <and>
                <isset property="tomcat5"/>
                <not><isset property="tomcat5.5"/></not>
            </and>
            <then>
                <copy tofile="${webapp.dist}/context.xml"
                    file="metadata/conf/tomcat-context.xml" overwrite="true">
                    <filterset refid="db.variables"/>
                </copy>
            </then>
            <elseif>
                <isset property="tomcat5.5"/>
                <then>
                    <copy tofile="${webapp.dist}/context.xml"
                        file="metadata/conf/tomcat-context-5.5.xml" overwrite="true">
                        <filterset refid="db.variables"/>
                    </copy>
                </then>
            </elseif>
        </if>
        <!-- Copy .properties files in src tree to build/web/classes -->
        <copy todir="${build.dir}/web/classes">
            <fileset dir="src/web">
                <include name="**/*.properties"/>
                <include name="**/*.xml"/>
            </fileset>
        </copy>
        <war destfile="${webapp.dist}/${webapp.war}"
            webxml="${webapp.target}/WEB-INF/web.xml" compress="true">
            <fileset dir="${webapp.target}" excludes="**/web.xml"/>
            <metainf dir="${webapp.dist}" includes="context.xml"/>

            <classes dir="${build.dir}/web/classes">
                <exclude name="**/database.properties"/>
            </classes>

            <webinf dir="${build.dir}/dao/gen/META-INF" includes="*.xml"/>
            <webinf dir="${build.dir}/service/classes/META-INF" includes="*.xml"/>

            <lib file="${dist.dir}/${webapp.name}-dao.jar"/>
            <lib file="${dist.dir}/${webapp.name}-service.jar"/>
            
            <webinf dir="${struts.dir}" includes="*.xml"/>

            <lib file="${clickstream.jar}"/>
            <lib file="${dwr.jar}"/>
            <lib dir="${commons.dir}" includes="*.jar"/>
            <lib dir="${struts.dir}" includes="*.jar"/>
            <lib dir="${jstl.final.dir}/lib" includes="*.jar"/>
            <lib dir="${javamail.dir}" includes="*.jar"/>   
            <lib file="${log4j.jar}"/>
            <lib file="${strutsmenu.jar}"/>
            <lib file="${database.jar}"/>
            <lib dir="${displaytag.dir}" includes="*.jar"/>
            <lib file="${hibernate.jar}"/>
            <lib dir="${hibernate.dir}/lib" includes="*.jar"/>
            <lib dir="${spring.dir}" includes="*.jar" excludes="*mock.jar"/>
            <lib file="${sitemesh.jar}"/>
            <lib dir="${velocity.dir}" includes="*.jar"/>  
            <lib file="${urlrewrite.jar}"/>
        </war>
    </target>

    <target name="test-web" depends="webdoclet,db-load,check-debug" description="Test web module">
        <copy todir="${webapp.target}/WEB-INF" file="${struts.dir}/validator-rules.xml"/>
        <test-module module="web"/>
    </target>

    <macrodef name="compile">
        <attribute name="module"/>
        <attribute name="additional.src.dirs" default=""/>
        <element name="options" optional="yes"/>

        <sequential>
            <echo>Compiling @{module}...</echo>
            <mkdir dir="${build.dir}/@{module}/classes"/>
            <mkdir dir="${test.dir}/@{module}/classes"/>
            <javac srcdir="${src}/@{module};@{additional.src.dirs}"
                destdir="${build.dir}/@{module}/classes" debug="${compile.debug}"
                deprecation="${compile.deprecation}" optimize="${compile.optimize}"
                classpathref="@{module}.compile.classpath">
                <options/>
            </javac>
            <javac srcdir="test/@{module}" debug="true"
                destdir="${test.dir}/@{module}/classes">
                <classpath>
                    <path refid="@{module}.test.classpath"/>
                    <path location="${build.dir}/@{module}/classes"/>
                </classpath>
                <options/>
            </javac>
            <emma enabled="${emma.enabled}" >
                <instr instrpath="${build.dir}/@{module}/classes"
                       destdir="${out.instr.dir}/@{module}/classes"
                       metadatafile="${coverage.dir}/metadata-@{module}.emma"
                       merge="true"/>
            </emma>
        </sequential>
    </macrodef>

    <macrodef name="test-module">
        <attribute name="module"/>
        <attribute name="additional.src.dirs" default=""/>
        <element name="options" optional="yes"/>

        <sequential>
            <echo level="info">Testing @{module}...</echo>
            <mkdir dir="${test.dir}/data"/>
            <propertycopy name="testcase" from="@{module}-testcase" silent="true"/>
            <!-- Replace tokens in test properties files -->
            <copy todir="${test.dir}/@{module}/classes">
                <fileset dir="test/@{module}" excludes="**/*.java"/>
                <filterset refid="variables.to.replace"/>
            </copy>

            <junit printsummary="no" forkmode="once" errorProperty="test.failed" 
                failureProperty="test.failed" fork="${junit.fork}" showoutput="${junit.showoutput}">
                <classpath>
                    <!-- Instrumented classes - must be BEFORE the normal ones -->
                    <!-- ============================= -->
                    <pathelement location="${out.instr.dir}/@{module}/classes"/>

                    <pathelement path="@{additional.src.dirs}"/>
                    <path refid="@{module}.test.classpath"/>
                    <pathelement location="${build.dir}/@{module}/classes"/>
                    <pathelement location="${test.dir}/@{module}/classes"/>
                    <pathelement path="${java.class.path}"/>
                    <pathelement path="${webapp.target}"/>
                    <pathelement path="${build.dir}/dao/gen"/>
                    <!-- For .properties and .xml files -->
                    <pathelement path="${build.dir}/web/classes"/>
                    <pathelement path="src/@{module}"/>

                    <!-- Emma library -->
                    <!-- ============================= -->
                    <pathelement location="${emma.jar}"/>

                </classpath>

                <!-- emma-specific jvm parameter -->
                <!-- =========================== -->
                <jvmarg value="-Demma.coverage.out.file=${coverage.dir}/coverage-@{module}.emma"/>

                <formatter type="xml"/>
                <formatter type="brief" usefile="false"/>
                <batchtest todir="${test.dir}/data" if="testcase">
                    <fileset dir="${test.dir}/@{module}/classes">
                        <include name="**/*${testcase}*"/>
                        <exclude name="**/*TestCase.class"/>
                    </fileset>
                </batchtest>
                <batchtest todir="${test.dir}/data" unless="testcase">
                    <fileset dir="${test.dir}/@{module}/classes">
                        <include name="**/*Test.class*"/>
                    </fileset>
                </batchtest>
            </junit>

            <!-- emma report task -->
            <!-- ================================== -->
            <emma enabled="${emma.enabled}">
                <report sourcepathref="all.sources" depth="method">
                    <fileset dir="${coverage.dir}">
                        <include name="*.emma"/>
                    </fileset>
                    <html outfile="${coverage.dir}/coverage.html"/>
                </report>
            </emma>

            <fail if="test.failed">
                Unit tests failed. For error messages, check the log files in
                ${test.dir}/data or run "ant test-reports"
                to generate reports at ${test.dir}/reports.</fail>
        </sequential>
    </macrodef>

    <target name="test-reports" description="Generate test reports">
        <mkdir dir="${test.dir}/reports"/>
        <junitreport todir="${test.dir}">
            <fileset dir="${test.dir}/data">
                <include name="TEST-*.xml"/>
            </fileset>
            <report format="frames" todir="${test.dir}/reports"/>
        </junitreport>
        <echo level="info">
        Test reports generated at ${test.dir}/reports
        </echo>
    </target>

    <target name="deploy-test-reports" depends="test-reports"
        description="Deploys Generated JUnit test reports to server">
        <mkdir dir="${test.dir}/reports"/>
        <copy todir="${tomcat.home}/webapps/${webapp.name}/test-reports">
            <fileset dir="${test.dir}/reports"/>
        </copy>
    </target>

    <!-- =================================================================== -->
    <!--            Compile JSPs using jspc                                  -->
    <!-- =================================================================== -->
    <target name="compile-jsp" depends="jsp-2" if="precompile.jsp">
        <property name="jsp.src" value="${build.dir}/web/jsp/src"/>
        <mkdir dir="${jsp.src}"/>

        <taskdef classname="org.apache.jasper.JspC" name="jasper" classpathref="jspc.classpath"/>

        <jasper verbose="0" package="org.appfuse.jsp" uriroot="${webapp.target}" 
            webXmlFragment="${jsp.src}/jsp-servlets.xml" outputDir="${jsp.src}"/>
        
        <javac srcdir="${jsp.src}" destdir="${build.dir}/web/classes"
            debug="${compile.debug}" deprecation="${compile.deprecation}"
            optimize="${compile.optimize}" classpathref="jspc.classpath"/>

        <loadfile property="jsp.mappings" srcfile="${jsp.src}/jsp-servlets.xml"/>
        <replace file="${webapp.target}/WEB-INF/web.xml" value="${jsp.mappings}"
            token="&lt;!-- precompiled jsp mappings --&gt;"/>
    </target>

    <!-- =================================================================== -->
    <!--            Run Canoo WebTests in Tomcat                             -->
    <!-- =================================================================== -->
    <target name="test-canoo" if="tomcat.home" depends="ping-tomcat,db-load"
        description="Runs Canoo WebTests in Tomcat to test JSPs">

        <copy todir="${test.dir}/properties">
            <filterchain>
                <filterreader classname="org.appfuse.buildtools.EscapeHtmlEntities">
                    <classpath>
                        <path refid="web.test.classpath"/>
                        <pathelement location="${test.dir}/web/classes"/>
                    </classpath>
                    <param name="mode" value="unescape"/>
                </filterreader>
        	</filterchain>
            <fileset dir="web/WEB-INF/classes" includes="**/ApplicationResources*.properties"/>
        </copy>
        
        <taskdef file="${webtest.dir}/webtestTaskdefs.properties">
            <classpath>
                <path refid="web.test.classpath"/>
                <!-- for log4j.properties -->
                <path location="${build.dir}/web/classes"/>
            </classpath>
        </taskdef>

        <mkdir dir="${test.dir}/data"/>
        
        <!-- Delete old results file if it exists -->
        <delete file="${test.dir}/data/web-tests-result.xml"/>
        
        <!-- This is so the default will be used if no test case is specified -->
        <property name="testcase" value="run-all-tests"/>
        <echo level="info">Testing with locale '${user.language}'</echo>
        <ant antfile="test/web/web-tests.xml" target="${testcase}"/>
    </target>

    <!-- =================================================================== -->
    <!--            Run Canoo WebTests using Cargo                           -->
    <!-- =================================================================== -->
    <target name="test-jsp" if="tomcat.home" depends="war,check-debug"
        description="Runs Canoo WebTests using Cargo">
         
        <taskdef resource="cargo.tasks">
            <classpath>
                <fileset dir="${cargo.dir}" includes="*.jar"/>
            </classpath>
        </taskdef> 

        <echo>running canoo tests at:
              http://${tomcat.server}:${http.port}/${webapp.name}</echo>

        <if>
            <isset property="tomcat5"/>
            <then><property name="cargoId" value="tomcat5x"/></then>
            <else><property name="cargoId" value="tomcat4x"/></else>
        </if>
        
        <echo message="Starting ${cargoId}..."/>
        <cargo containerId="${cargoId}" id="${cargoId}" home="${tomcat.home}" action="start"
            output="${test.dir}/cargo.log" wait="false">
            <configuration home="${test.dir}/${cargoId}">
                <property name="cargo.logging" value="high"/>
                <property name="cargo.servlet.port" value="${http.port}"/>
                <!--<property name="cargo.jvmargs" value="${run.appfuse.test.debugargline}"/>-->
                <deployable type="war" file="${webapp.dist}/${webapp.war}"/>
            </configuration>   
        </cargo>

        <antcall target="test-canoo"/>

        <cargo refid="${cargoId}" action="stop"/>
    </target>

    <!-- =================================================================== -->
    <!--            Run all tests (tomcat not running)                       -->
    <!-- =================================================================== -->
    <target name="test-all" depends="test-dao,test-service,test-web,test-jsp"
        description="runs all tests for dao, service, web and jsp">
        <antcall target="db-load"/>
    </target>

    <!-- =================================================================== -->
    <!--  Run all tests (tomcat IS running). The deploy task                 -->
    <!--  should be run before this one.                                     -->
    <!-- =================================================================== -->
    <target name="test-all-running"
        description="runs all tests for DAOs, Services, Controllers and JSPs">
        <antcall target="test-dao"/>
        <antcall target="test-service"/>
        <antcall target="test-web"/>
        <antcall target="test-canoo"/>
        <antcall target="db-load"/>
    </target>
        
    <!-- =================================================================== -->
    <!--            Simple task to ping tomcat and make sure it's running    -->
    <!-- =================================================================== -->
    <target name="ping-tomcat" description="pings tomcat to make sure it's running">
        <echo level="info">Verifying that tomcat is running...</echo>
        <get src="http://${tomcat.server}:${http.port}/${webapp.name}"
            dest="../ping-${tomcat.server}.html"/>
    </target>
    
    <!-- =================================================================== -->
    <!--            Export the data                                          -->
    <!-- =================================================================== -->
    <target name="db-export" depends="prepare"
        description="Exports the current data in the database">
        <dbunit driver="${database.driver_class}" url="${database.url}"
            userid="${database.username}" password="${database.password}">
            <export dest="db-export.xml" format="xml"/>
        </dbunit>
    </target>

    <target name="db-load" depends="prepare"
        description="Loads the database with sample data">
        <property name="operation" value="CLEAN_INSERT"/>
        <property name="file" value="metadata/sql/sample-data.xml"/>
        <dbunit driver="${database.driver_class}"
            supportBatchStatement="false" url="${database.url}"
            userid="${database.username}" password="${database.password}">
            <operation type="${operation}" src="${file}" format="xml"/>
        </dbunit>
    </target>
    
    <!-- =================================================================== -->
    <!-- The "db-create" target creates a database based on properties       --> 
    <!-- from the database.properties file                                   -->
    <!-- =================================================================== -->
    <target name="db-create" depends="init"
        description="create database for ${database.type}">
        <echo level="debug">${database.jar}</echo>
        <if>
            <equals arg1="${database.type}" arg2="mysql"/>
            <then>
                <echo message="Detected MySQL, creating database..."/>
                <echo>Creating '${database.name}' database with: ${database.type}-create.sql</echo>
                <echo>URL: ${database.admin.url}</echo>
                <filter token="dbname" value="${database.name}"/>
                <copy tofile="${build.dir}/dao/gen/${database.type}-create.sql" overwrite="true" filtering="true">
                    <fileset file="metadata/sql/${database.type}-create.sql"/>
                </copy>
                <sql
                    driver="${database.driver_class}"
                    url="${database.admin.url}"
                    userid="${database.admin.username}"
                    password="${database.admin.password}">

                    <classpath>
                        <pathelement location="${database.jar}"/>
                    </classpath>

                    <fileset dir="${build.dir}/dao/gen">
                        <include name="${database.type}-create.sql"/>
                    </fileset>
                </sql>
            </then>
            <else>
                <echo level="warning">WARNING:</echo>
                <echo>You selected a '${database.type}' database which </echo>
                <echo>does NOT support creating a database via JDBC.  </echo>
                <echo>Please create a '${database.name}' database manually</echo>
                <echo>and then run "ant db-prepare" to create the </echo>
                <echo>database tables.  You might want to check the </echo>
                <echo>metadata/sql directory to see if the file</echo>
                <echo>'${database.type}-create.sql' exists.</echo>
            </else>
        </if>
    </target>
    
    <!-- =================================================================== -->
    <!-- The "db-prepare" target generates the database schema and creates   --> 
    <!-- tables based on the mapping files                                   -->
    <!-- =================================================================== -->
    <target name="db-prepare" depends="clean,package-dao"
        description="creates database tables">
        <taskdef name="schemaexport"
            classname="org.hibernate.tool.hbm2ddl.SchemaExportTask">
            <classpath>
                <path refid="xdoclet.classpath"/>
                <path refid="hibernate.classpath"/>
            </classpath>
        </taskdef>

        <generate-database-properties/>
        <schemaexport quiet="no" text="no" drop="no" delimiter=";" 
            properties="database.properties" output="create-tables.sql">
            <fileset dir="${build.dir}/dao/gen" includes="**/*.hbm.xml"/>
        </schemaexport>
    </target>

    <target name="db-drop" depends="hibernatedoclet"
        description="drops database tables">
        <taskdef name="schemaexport"
            classname="org.hibernate.tool.hbm2ddl.SchemaExportTask">
            <classpath>
                <path refid="xdoclet.classpath"/>
                <path refid="hibernate.classpath"/>
            </classpath>
        </taskdef>

        <generate-database-properties/>
        <schemaexport quiet="no" text="no" drop="yes" delimiter=";"
            properties="database.properties" output="drop-tables.sql">
            <fileset dir="${build.dir}/dao/gen" includes="**/*.hbm.xml"/>
        </schemaexport>
    </target>

    <!-- =================================================================== -->
    <!--            Setup Database                                           -->
    <!-- =================================================================== -->
    <target name="setup-db" depends="db-create,db-prepare,db-load"
        description="creates database and populates by calling other tasks"/>
        
    <!-- Remove classes directory for clean build -->
    <target name="clean" description="Removes build artifacts">
        <echo level="info">Cleaning build and distribution directories</echo>
        <delete dir="${build.dir}"/>
        <delete dir="${dist.dir}"/>
        <delete file="database.properties"/>
        <delete file="create-tables.sql"/>
        <delete dir="${out.instr.dir}"/>
        <delete dir="${coverage.dir}"/>
    </target>

    <!-- =================================================================== -->
    <!-- Create JavaDoc Documentation                                        -->
    <!-- =================================================================== -->
    <target name="javadoc" depends="java2html"
        description="Generate JavaDoc API docs">
        <javadoc
            destdir="${build.dir}/docs/api"
            packagenames="org.appfuse.*"
            author="true"
            version="true"
            windowtitle="${webapp.name} api"
            doctitle="&lt;h1&gt;${webapp.name} javadocs for
                version ${webapp.version}&lt;/h1&gt;"
            bottom="Copyright &#169; 2002-${copyright.year}"
            stylesheetfile="${build.dir}/docs/api/stylesheet.css">

            <fileset dir="${src}">
                <patternset refid="java.files.pattern"/>
            </fileset>
            <fileset dir="test">
                <patternset refid="java.files.pattern"/>
            </fileset>

            <classpath refid="web.test.classpath"/>
            <classpath>
                <pathelement location="${jmock.jar}"/>
                <pathelement location="${build.dir}/web/gen"/>
            </classpath>
            
            <!-- XDoclet Tags -->
            <tag name="hibernate.class" scope="all" description="Class:"/>
            <tag name="hibernate.id" scope="all" description="Id:"/>
            <tag name="hibernate.property" scope="all" description="Property:"/>
            <tag name="jsp.tag" scope="all" description="JSP Tag:"/>
            <tag name="jsp.attribute" scope="all" description="JSP Attribute:"/>
            <tag name="struts.action" scope="all" description="Mapping:"/>
            <tag name="struts.action-forward" scope="all" description="ActionForward:"/>
            <tag name="struts.form" scope="all" description="Form Name:"/>
            <tag name="struts.validator" scope="all" description="Validator:"/>
            <tag name="struts.validator-args" scope="all" description="Validator Args:"/>
            <tag name="struts.validator-var" scope="all" description="Validator Var:"/>
            <tag name="web.listener" scope="all" description="Listener:"/>
            <tag name="web.filter" scope="all" description="Filter:"/>
            <tag name="web.filter-prepare-param" scope="all" description="prepare-Param:"/>
            <tag name="web.filter-mapping" scope="all" description="Mapping:"/>
            <tag name="web.servlet" scope="all" description="Servlet:"/>
            <tag name="web.servlet-prepare-param" scope="all" description="prepare-Param:"/>
            <tag name="web.servlet-mapping" scope="all" description="Mapping:"/>
            
            <!-- Application frameworks -->
            <link href="http://jakarta.apache.org/commons/lang/api"/>
            <link href="http://struts.apache.org/struts-doc-1.2.9/api"/>
            <link href="http://www.springframework.org/docs/api"/>
            <link href="http://www.hibernate.org/hib_docs/api"/>
            
            <!-- Testing frameworks -->
            <link href="http://www.junit.org/junit/javadoc/${junit.version}"/>
            <link href="http://strutstestcase.sf.net/api/"/>
            
            <!-- SDKs -->
            <link href="http://java.sun.com/j2se/1.4/docs/api/"/>
            <link href="http://java.sun.com/j2ee/sdk_1.3/techdocs/api/"/>
        </javadoc>
    </target>

    <!-- =================================================================== -->
    <!-- Create HTML versions of the Java code in this project               -->
    <!-- =================================================================== -->
    <target name="java2html" depends="hibernatedoclet"
        description="creates HTML pages of code for online viewing">
        <taskdef name="java2html" classname="com.java2html.Java2HTMLTask"
            classpath="${j2h.jar}"/>

        <java2html
            destination="${build.dir}/docs/api">
            <fileset dir="${src}">
                <patternset refid="java.files.pattern"/>
            </fileset>
            <fileset dir="test">
                <patternset refid="java.files.pattern"/>
            </fileset>
        </java2html>
    </target>

    <!-- =================================================================== -->
    <!-- The "deploy-web" target deploys the web application in the in the   -->
    <!-- non-war format.                                                     -->
    <!-- =================================================================== -->
    <target name="deploy-web" depends="compile-jsp" if="tomcat.home"
        description="deploy only web classes to servlet container's deploy directory">

        <echo message="Deploying web application to ${tomcat.home}/webapps"/>
        <copy todir="${tomcat.home}/webapps/${webapp.name}">
            <fileset dir="${webapp.target}"
                excludes="**/web-test.xml,**/web.xml,**/*-resources.xml"/>
        </copy>

    </target>
    
    <!-- =================================================================== -->
    <!--            Refresh - Stops Tomcat, and refreshes everything         -->
    <!-- =================================================================== -->
    <target name="refresh" depends="undeploy,clean,deploy"
        description="Undeploys, cleans, then re-deploys"/>
    
    <!-- =================================================================== -->
    <!-- The "deploy" target deploys the web application by packaging it as  -->
    <!-- a WAR and then unpackaging it into Tomcat's webapps directory       -->
    <!-- =================================================================== -->
    <target name="deploy" depends="package-web" if="tomcat.home"
        description="unwar into the servlet container's deployment directory">

        <unwar src="${webapp.dist}/${webapp.war}"
            dest="${tomcat.home}/webapps/${webapp.name}"/>

    </target>
    
    <!-- =================================================================== -->
    <!-- The "undeploy" target deletes the web application archive and the   -->
    <!-- web application directory in the compatible servlet container.      -->
    <!-- =================================================================== -->
    <target name="undeploy" if="tomcat.home"
        description="undeploy war file to servlet container's deployment dir">
        <echo message="Undeploying webapp from Tomcat"/>
        <delete file="${tomcat.home}/webapps/${webapp.war}"/>
        <delete dir="${tomcat.home}/webapps/${webapp.name}"/>
    </target>

    <!-- =================================================================== -->
    <!-- The "deploy-war" deploys the web application in the in a war format -->
    <!-- =================================================================== -->
    <target name="deploy-war" depends="package-web" if="tomcat.home"
        description="Deploy '${webapp.name}.war' to local Tomcat">
        <copy file="${webapp.dist}/${webapp.war}"
            todir="${tomcat.home}/webapps"/>
    </target>
    
    <!-- Utilities -->
    <patternset id="java.files.pattern" includes="**/*.java"/>

    <target name="checkstyle" depends="prepare"
        description="Check code style for compliance with coding standards">
        <property name="checkstyle.data.dir"
            location="${build.dir}/docs/checkstyle"/>
        <property name="checkstyle.data.file"
            location="${checkstyle.data.dir}/checkstyle.xml"/>
        <property name="checkstyle.report.file"
            location="${checkstyle.data.dir}/checkstyle.html"/>
        <property name="checkstyle.xsl.file"
            location="${checkstyle.dir}/contrib/checkstyle-noframes.xsl"/>
        <mkdir dir="${checkstyle.data.dir}"/>
        <taskdef resource="checkstyletask.properties" classpath="${checkstyle.jar}"/>
        <checkstyle config="${checkstyle.dir}/sun_checks.xml"
            failOnViolation="false" failureProperty="checkstyle.failure">
            <fileset dir="src">
                <patternset refid="java.files.pattern"/>
            </fileset>
            <!-- uncomment to print to console as well -->
            <!--formatter type="plain"/-->
            <formatter type="xml" toFile="${checkstyle.data.file}"/>
        </checkstyle>
        <xslt in="${checkstyle.data.file}" out="${checkstyle.report.file}"
            style="${checkstyle.xsl.file}"/>
    </target>

    <target name="pmd" if="pmd.jar" depends="prepare"
        description="Locates unused imports, unused variables, etc.">
        <mkdir dir="${build.dir}/docs/pmd"/>
        <property name="pmd.data.file"  value="${build.dir}/docs/pmd/pmdreport.html"/>
        <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask">
            <classpath location="${pmd.jar}"/>
            <classpath location="${pmd.dir}/lib/jaxen-core-1.0-fcs.jar"/>
            <classpath location="${pmd.dir}/lib/saxpath-1.0-fcs.jar"/>
        </taskdef>

        <pmd rulesetfiles="rulesets/unusedcode.xml,rulesets/imports.xml"
            failonerror="no" shortFilenames="true">
            <formatter type="html" toFile="${pmd.data.file}"/>
            <fileset dir="src">
                <patternset refid="java.files.pattern"/>
            </fileset>
        </pmd>
    </target>
    
    <target name="emma" description="turns on EMMA instrumentation/reporting" >
        <property name="emma.enabled" value="true"/>
        <mkdir dir="${out.instr.dir}"/>
        <!-- Filter for classes to instrument -->
        <property name="emma.filter" value="org.appfuse.*"/>
    </target>

    <target name="todo" description="creates report of todos in code">

        <taskdef name="todo"
            classname="xdoclet.modules.doc.DocumentDocletTask"
            classpathref="xdoclet.classpath"/>
            
        <mkdir dir="${build.dir}/docs/todo"/>
        <todo destdir="${build.dir}/docs/todo">
            <fileset dir="${src}">
                <patternset refid="java.files.pattern"/>
            </fileset>
        </todo>
    </target>

    <target name="docs" depends="javadoc, todo, checkstyle, pmd"
        description="runs javadoc, todo, checkstyle and pmd tasks">
        <echo level="info">API and Reports generated successfully...</echo>
    </target>
        
    <!-- =================================================================== -->
    <!--            Setup Tomcat                                             -->
    <!-- =================================================================== -->
    <target name="setup-tomcat" depends="init" if="tomcat.home"
        description="copies jdbc driver and context.xml to tomcat">
        <if>
            <and>
                <isset property="tomcat5"/>
                <not><isset property="tomcat5.5"/></not>
            </and>
            <then>
                <echo message="Detected Tomcat 5..."/>
                <echo level="info">Copying ${webapp.name}.xml...</echo>
                <copy tofile="${tomcat.home}/conf/Catalina/localhost/${webapp.name}.xml"
                    file="metadata/conf/tomcat-context.xml" overwrite="true">
                    <filterset refid="db.variables"/>
                </copy>
            </then>
            <elseif>
                <isset property="tomcat5.5"/>
                <then>
                    <echo message="Detected Tomcat 5.5..."/>
                    <echo level="info">Copying ${webapp.name}.xml...</echo>
                    <copy tofile="${tomcat.home}/conf/Catalina/localhost/${webapp.name}.xml"
                        file="metadata/conf/tomcat-context-5.5.xml" overwrite="true">
                        <filterset refid="db.variables"/>
                    </copy>
                </then>
            </elseif>
            <else>
                <echo message="Detected Tomcat 4..."/>
                <echo level="info">Copying ${webapp.name}.xml...</echo>
                <copy tofile="${tomcat.home}/webapps/${webapp.name}.xml"
                    file="metadata/conf/tomcat-context.xml" overwrite="true">
                    <filterset refid="db.variables"/>
                </copy>
            </else>
        </if>
    </target>
    
    <!-- =================================================================== -->
    <!--            Internal targets to enable running in debug mode         -->
    <!-- =================================================================== -->
    <target name="check-debug" depends="with-debug,no-debug"/>

    <target name="with-debug" if="appfuse-debug">
        <property name="run.appfuse.test.debugargline" value="-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=y"/>
        <echo>Running in debug mode : Listening on port 4000 ...</echo>
    </target>

    <target name="no-debug" unless="appfuse-debug">
       <property name="run.appfuse.test.debugargline" value=""/>
    </target>

    <!-- =================================================================== -->
    <!--            Start Tomcat                                             -->
    <!-- =================================================================== -->
    <target name="start.tomcat"
        description="starts tomcat in the current console window" depends="check-debug">
        <java classname="org.apache.catalina.startup.Bootstrap" fork="yes">
            <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
            <jvmarg line="${run.appfuse.test.debugargline}"/>
            <arg value="start"/>
            <classpath>
                <pathelement path="${java.home}/../lib/tools.jar"/>
                <fileset dir="${tomcat.home}">
                    <include name="bin/bootstrap.jar"/>
                </fileset>
            </classpath>
        </java>
    </target>
    
    <!-- ============================================================== -->
    <!-- Tomcat tasks - remove these if you don't have Tomcat installed -->
    <!-- ============================================================== -->
    <taskdef file="${ant-contrib.dir}/tomcatTasks.properties">
        <classpath>
            <fileset dir="${tomcat.home}/server/lib" includes="catalina-ant*.jar"/>
        </classpath>
    </taskdef>
    <target name="install" description="Install application in Tomcat"
        depends="package-web">
        <deploy url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"
            path="/${webapp.name}"
            war="file:${webapp.dist}/${webapp.war}"/>
    </target>

    <target name="remove" description="Remove application in Tomcat">
        <undeploy url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"
            path="/${webapp.name}"/>
    </target>

    <target name="reload" description="Reload application in Tomcat">
        <reload url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"
            path="/${webapp.name}"/>
    </target>

    <target name="start" description="Start Tomcat application">
        <start url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"
            path="/${webapp.name}"/>
    </target>

    <target name="stop" description="Stop Tomcat application">
        <stop url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"
            path="/${webapp.name}"/>
    </target>

    <target name="list" description="List Tomcat applications">
        <list url="${tomcat.manager.url}"
            username="${tomcat.username}"
            password="${tomcat.password}"/>
    </target>

    <!-- =================================================================== -->
    <!--            Creates documentation from wiki                          -->
    <!-- =================================================================== -->
    <target name="wiki" description="downloads files from wiki for doco" unless="nodocs">
        <!-- Get latest stylesheet -->
        <get src="http://raibledesigns.com/wiki/templates/redman/jspwiki.css"
            dest="docs/style.css"/>
        <!-- Get wiki pages -->
        <get src="http://raibledesigns.com/wiki/printwikishow.jsp?${wiki.pages}"
            dest="docs/wiki.html"/>
        <!-- Add some style -->
        <replaceregexp flags="g"
            file="docs/wiki.html"
            match='&lt;/HEAD&gt;'
            replace='&lt;/HEAD&gt; &lt;link rel="stylesheet" type="text/css" href="style.css" /&gt; &lt;style type="text/css"&gt;body {margin: 20px}&lt;/style&gt;'/>
    </target>
    
    <!-- =================================================================== -->
    <!--            Creates release (source) distribution                    -->
    <!-- =================================================================== -->
    <target name="dist" depends="clean,wiki"
        description="create zip and tar.gz of entire directory for distribution">
        <property name="archive.prefix" value="${webapp.name}"/>
        <property name="archive.name" value="${archive.prefix}-${webapp.version}-src"/>
        <property name="archive.target" value="../${archive.name}"/>
        <zip zipfile="${archive.target}.zip">
            <zipfileset prefix="${webapp.name}" dir="${basedir}">
                <patternset id="srcfiles">
                    <include name="**"/>
                    <exclude name=".settings/**"/>
                    <exclude name="${build.dir}"/>
                    <exclude name="${dist.dir}"/>
                    <exclude name="extras/myjavapack/**"/>
                    <exclude name="**/*~"/>
                    <exclude name="**/*.bak"/>
                    <exclude name=".#**"/>
                    <exclude name="www/**"/>
                    <exclude name="*.sh"/>
                    <exclude name="*.sql"/>
                    <exclude name="*.iws"/>
                    <exclude name="*.log"/>
                    <exclude name="velocity.*"/>
                    <exclude name="junit*.properties"/>
                </patternset>
            </zipfileset>
        </zip>
        <tar tarfile="${archive.target}.tar">
            <tarfileset dir="${basedir}" mode="${tar.mode}" prefix="${webapp.name}"
                username="${tar.user}" group="${tar.group}">
                <patternset refid="srcfiles"/>
            </tarfileset>
        </tar>
        <gzip zipfile="${archive.target}.tar.gz" src="${archive.target}.tar"/>
        <delete file="${archive.target}.tar"/>
    </target>
    
    <!-- =================================================================== -->
    <!--            Creates release (binary) distribution                    -->
    <!-- =================================================================== -->
    <target name="bin" depends="clean,package-web"
        description="creates zip file with war, jdbc drivers, and XML file">
        
        <!-- Copy tomcat-context.xml file to webapp.name.xml so it's friendlier -->
        <copy tofile="${webapp.dist}/${webapp.name}.xml"
            file="metadata/conf/tomcat-context.xml">
            <filterset refid="db.variables"/>
        </copy>
        
        <!-- Remove version number from WAR file -->
        <move file="${webapp.dist}/${webapp.war}"
            tofile="${webapp.dist}/${webapp.name}.war"/>
        
        <!-- Copy JDBC Driver -->
        <copy todir="${webapp.dist}" file="${database.jar}"/>

        <!-- Create the zip and tar.gz files -->
        <property name="archive.name" value="${webapp.name}-${webapp.version}-bin"/>
        <property name="archive.target" value="${dist.dir}/${archive.name}"/>
        <zip zipfile="${archive.target}.zip">
            <zipfileset prefix="${webapp.name}-${webapp.version}"
                dir="${webapp.dist}">
                <patternset id="binfiles">
                    <include name="**"/>
                </patternset>
            </zipfileset>
        </zip>
        <tar tarfile="${archive.target}.tar">
            <tarfileset dir="${webapp.dist}" mode="${tar.mode}"
                prefix="${webapp.name}-${webapp.version}"
                username="${tar.user}" group="${tar.group}">
                <patternset refid="binfiles"/>
            </tarfileset>
        </tar>
        <gzip zipfile="${archive.target}.tgz" src="${archive.target}.tar"/>
        <delete file="${archive.target}.tar"/>
    </target>
    
    <!-- =================================================================== -->
    <!--            Fix CRLF so installers will work                         -->
    <!-- =================================================================== -->
    <target name="fixcrlf" depends="init">
        <echo>Running fixcrlf....</echo>
        <fixcrlf srcdir="${basedir}"
            excludes="**/ApplicationResources_zh*.properties"
            includes="**/*.txt,
                      **/*.properties,
                      **/*.sql,
                      **/*.java,
                      **/*.jsp,
                      **/*.xdt,
                      **/*.xml,
                      **/*.page,
                      **/*.html,
                      **/*.js,
                      **/*.css, 
                      **/*.reference,
                      **/*.ldif,
                      **/*.conf"/>
    </target>
    
    <!-- =================================================================== -->
    <!--            Convenience target to setup everything                   -->
    <!-- =================================================================== -->
    <target name="setup" depends="setup-db,setup-tomcat,deploy"
        description="Sets up database, tomcat and deploys expanded war"/>

    <!-- =================================================================== -->
    <!-- The "new" target is used to create a new project by duplicating     -->
    <!-- this project and replacing "appfuse" instances with the new name.   -->
    <!-- =================================================================== -->
    <target name="new" depends="clean,init"
        description="creates a new project with the specified name">
<echo level="info">
+-------------------------------------------------------------+
|    -- Welcome to the AppFuse New Application Wizard! --     |
|                                                             |
| To create a new application, please answer the following    |
| questions.                                                  |
+-------------------------------------------------------------+
</echo>
        <echo/>

        <!-- Prompt user for input -->
        <input message="What would you like to name your application [myapp]?" addproperty="app.name" defaultvalue="myapp"/>
        <input message="What would you like to name your database [mydb]?" addproperty="db.name" defaultvalue="mydb"/>
        <input message="What package name would you like to use [org.appfuse]?" addproperty="new.pkg.name" defaultvalue="org.appfuse"/>
        <input message="What web framework would you like to use [webwork,tapestry,spring,jsf,struts]?" addproperty="web.framework" defaultvalue="struts"/>
        
        <echo level="info">Creating new application named '${app.name}'...</echo>
        <copy todir="../${app.name}">
            <fileset dir="${basedir}">
                <exclude name="target/**"/>
                <exclude name="sandbox/**"/>
                <exclude name="www/**"/>
                <exclude name="${webapp.name}*"/>
                <exclude name="*.log"/>
                <exclude name="*.sh"/>
                <exclude name=".#**"/>
                <exclude name="extras/**"/>
                <include name="**"/>
            </fileset>
        </copy>
        
        <copy todir="../${app.name}/extras">
            <fileset dir="${basedir}/extras">
                <include name="appgen/**"/>
                <include name="cruisecontrol/**"/>
                <include name="ibatis/**"/>
                <include name="middlegen/**"/>
                <include name="${web.framework}/**"/>
                <include name="xfire/**"/>
                <exclude name="**/*.log*"/>
            </fileset>
        </copy>
        
        <!-- replace app name -->
        <replaceregexp flags="g">
            <regexp pattern="appfuse"/>
            <substitution expression="${app.name}"/>
            <fileset dir="../${app.name}">
                <include name="**"/>
                <exclude name="lib/rename-packages-*/*.xml"/>
                <exclude name="src/**/*.java"/>
                <exclude name="src/**/*.xml"/>
                <exclude name="test/**/*.java"/>
                <exclude name="test/**/*.xml"/>   
                <exclude name="extras/**/*.java"/>
                <exclude name="extras/**/*.xml"/>
                <exclude name="metadata/web/global-exceptions.xml"/>
                <exclude name="web/WEB-INF/*.xml"/>
                <exclude name="web/WEB-INF/classes/log4j.properties"/>
                <exclude name="web/WEB-INF/classes/mail.properties"/>
                <exclude name="**/*.page"/>
                <exclude name="**/*.application"/>
                <exclude name="**/*_page.xdt"/>
                <exclude name="**/managed-beans.xdt"/>
                <exclude name="docs/**"/>
                <exclude name="**/loginMenu.jsp"/>
                <exclude name="**/README.txt"/>
                <exclude name=".springBeansProject"/>
                <exclude name="**/*.jar"/>
            </fileset>
        </replaceregexp>

        <!-- Copy IDEA project files -->
        <copy file="appfuse.iml" tofile="../${app.name}/${app.name}.iml"/>
        <copy file="appfuse.ipr" tofile="../${app.name}/${app.name}.ipr"/>
        <replace dir="../${app.name}" value="${app.name}" token="appfuse">
            <include name="${app.name}.i*"/>
        </replace>

        <!-- Fix path for packages in build.xml -->
        <replaceregexp flags="g" match="org.${app.name}" replace="org.appfuse">
            <fileset dir="../${app.name}">
                <include name="build.xml"/>
                <include name="metadata/templates/*.xdt"/>
                <include name="metadata/web/*.java"/>
            </fileset>
        </replaceregexp>

        <!-- Replace JNDI Name for database -->
        <replaceregexp flags="g">
            <regexp pattern="jdbc(.*)${app.name}"/>
            <substitution expression="jdbc\1${db.name}"/>
            <fileset dir="../${app.name}/metadata/web" includes="*web-resource-env-refs.xml"/>
            <fileset dir="../${app.name}/metadata/conf" includes="**"/>
            <fileset dir="../${app.name}/web" includes="**/*.jsp"/>
            <fileset dir="../${app.name}" includes="database.properties.reference"/>
        </replaceregexp>

        <!-- Replace JNDI Name in Spring config files -->
        <replaceregexp flags="g" match="jdbc/appfuse" replace="jdbc/${db.name}"
            file="../${app.name}/web/WEB-INF/applicationContext-resources.xml"/>

        <!-- Replace database name in properties.xml in database creation script -->
        <replaceregexp flags="g">
            <regexp pattern="${app.name}"/>
            <substitution expression="${db.name}"/>
            <fileset dir="../${app.name}/metadata/sql" includes="*.sql"/>
            <fileset dir="../${app.name}" includes="properties.xml"/>
        </replaceregexp>

        <if>
            <and>
                <not><equals arg1="${web.framework}" arg2=""/></not>
                <not><equals arg1="${web.framework}" arg2="struts"/></not>
            </and>
            <then><ant dir="../${app.name}/extras/${web.framework}" target="install" inheritAll="false"/></then>
        </if>
        
        <if>
            <not><equals arg1="${new.pkg.name}" arg2="org.appfuse"/></not>
            <then><rename-packages newPkgName="${new.pkg.name}" existingPkgName="org.appfuse"/></then>
        </if>
        
        <condition property="isWindows"><os family="windows"/></condition> 
        <if> 
            <isset property="isWindows"/> 
            <then> 
                <ant dir="../${app.name}" target="fixcrlf"/>
            </then>
        </if>

<echo level="info">
+-------------------------------------------------------------+
|           -- Application created successfully! --           |
|                                                             |
| Now you should be able to cd to your application and run:   |
| > ant setup test-all                                        |
+-------------------------------------------------------------+
</echo>
    </target>

    <import file="${rename-packages.dir}/rename-packages-macro.xml"/>

</project>
