Wednesday, December 5, 2012

Generating Java sources from multiple DTD schemas

found out i could not generate Java source from multiple DTD's using xjc (JAXB), so I had to write this script. This script solves two thing: xjc cannot compile multiple DTDs and xjc will generate the same file ObjectFactory.java for each call (overwriting file from previous call).

#!/bin/sh

while IFS= read -r -u3 -d $'\0' file; do
 filename="${file##*/}"                      # Strip longest match of */ from start
    dir="${file:0:${#file} - ${#filename}}" # Substring from 0 thru pos of filename
    base="${filename%.[^.]*}"                       # Strip shortest match of . plus at least one non-dot char from end
    ext="${filename:${#base} + 1}"

newDir="$dir$base"
echo "Package dir to create $newDir"
DIRECTORY="generatedsrc/$newDir"
if [ ! -d "$DIRECTORY" ]; then
    # Control will enter here if $DIRECTORY doesn't exist.
mkdir -p $DIRECTORY
fi
    PACKAGE=${newDir//.\//};
    PACKAGE=${PACKAGE//\//.};
    cmd="$JAVA_HOME/bin/xjc -dtd -d generatedsrc -p "$PACKAGE" $file"
    echo "Running: $cmd"
    $cmd
done 3< <(find . -iname *.dtd -type f -print0)