Avatar

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>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 !

Avatar

lszydlo

July 15, 2010, July 15, 2010 09:53, permalink

No rating. Login to rate!

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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;
	}

}

Your refactoring





Format Copy from initial code

or Cancel