Today I have been inspired by reading I Fought The Gorm to blog something. So I will blog to share how I use JDepend in an ANT target to fail the build if a package cycle is detected (yes I really hate circular dependencies).

The basic logic of what the target does is:

  • Run JDepend to generate the XML data
  • Generate an HTML report
  • Run XSL to detect cycles in the XML data
  • Fail if cycles have been found.

The ANT target is:

  <target name="jdepend" depends="-init"
          description="Run JDepend to detect cycles"
    <!-- Run JDepend to collect data -->
    <mkdir dir="${}/jdepend"/>
    <jdepend outputfile="${}/jdepend/mldef-jdepend.xml"
      <exclude name="java.*"/>
      <exclude name="javax.*"/>

        <pathelement location="${}/dist/shared-${build.revision}.jar"/>
        <pathelement location="${}/dist/datareceipt-DO-NOT-USE-${build.revision}.jar"/>
        <pathelement location="${}/dist/webapp-DO-NOT-USE-${build.revision}.jar"/>

    <!-- Generate HTML report -->
    <xslt in="${}/jdepend/mldef-jdepend.xml"

    <!-- Detect if cycles -->
    <xslt in="${}/jdepend/mldef-jdepend.xml"

    <!-- Fail if cycles -->
    <fail message="There are cycles in the packages, see ${}/jdepend/mldef-jdepend.html"
        <length file="${}/jdepend/cycle-check.txt"
                when="gt" length="0"


The contents of jdepend-cycles-check.xsl is:

      <xsl:output method="text" indent="no"/>

      <xsl:template match="/JDepend">
        <xsl:apply-templates select="Cycles/Package"/>

      <xsl:template match="Cycles/Package">
    Cycle involving <xsl:value-of select="@Name"/>