private LinkedList<String> basePackages;
private String getAttribute( Node node, String name )
{
// .....
}
private String getBasePackage( org.w3c.dom.Node node )
{
final String name;
if ( node.getNodeName().equals( "package" ) )
{
name = this.getAttribute( node, "name" );
}
else
{
name = null;
}
final String basePackage = this.getAttribute( node, "basePackage" );
if ( basePackage == null )
{
if ( node.getNodeName().equals( "package" ) )
{
if ( name == null || name.isEmpty() )
{
return this.basePackages.peek();
}
else
{
return this.basePackages.peek() + "." + name;
}
}
else if ( this.basePackages.isEmpty() )
{
return "";
}
else
{
return this.basePackages.peek();
}
}
else if ( basePackage.isEmpty() )
{
if ( node.getNodeName().equals( "package" ) )
{
if ( !( name == null || name.isEmpty() ) )
{
return name;
}
}
return "";
}
else if ( node.getNodeName().equals( "package" ) )
{
if ( name == null || name.isEmpty() )
{
return basePackage;
}
else
{
return basePackage + "." + name;
}
}
else
{
return basePackage;
}
}
Refactorings
No refactoring yet !
lszydlo
July 15, 2010, July 15, 2010 09:53, permalink
It is hard to refactor without unit tests and with only one example of XML. I am not sure if I covered all cases but idea is probably clear.
public class PackageStack {
private LinkedList<String> basePackages;
private String getAttributeValue(Node node, String name) {
NamedNodeMap attributes = node.getAttributes();
return attributes.getNamedItem(name).getNodeValue();
}
public String getBasePackage(Node node) {
if(nodeHasBasePackageAttribute(node)) {
return getAttributeValue(node, "basePackage");
}
if(nodeIsPackage(node)) {
return basePackages.peek() + appendPackageNameIfExists(node);
}
if(basePackages.isEmpty()) {
return EMPTY;
} else {
return basePackages.peek();
}
}
private String appendPackageNameIfExists(Node node) {
String packageName = getAttributeValue(node, "name");
return isBlank(packageName) ? EMPTY : "." + packageName;
}
private boolean nodeIsPackage(Node node) {
return "package".equals(node.getNodeName());
}
private boolean nodeHasBasePackageAttribute(Node node) {
return getAttributeValue(node, "basePackage") != null;
}
}
Figures out the current full package name and keeps a stack of package names to parallel the DOM traversal and maintain context between elements.
<test basePackage="com.rmc">
<package name="misc">
</package>
</test>