2009/02/14

Java and Spring - Property Editor for InetAddress


import
java.beans.PropertyEditorSupport;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;

/**
* Custom property editor for java.netInetAddress class
*
* Author: Rostislav Matl
* Date: Feb-2009
*/
public class InetAddressEditor extends PropertyEditorSupport
{
private static Pattern ipv4 =
Pattern.compile( "(([01][0-9][0-9]|2[0-4][0-9]|25[0-5])\\.)
{3}([01][0-9][0-9]|2[0-4][0-9]|25[0-5])"
);

private static Pattern ipv6 =
Pattern.compile( "([0-9a-fA-F]{4}:){7}[0-9a-fA-F]{4}" );

@Override
/** Converts String IP address to InetAddress object.
*
* @param textValue "255.255.222.255" e.g.
*/
public void setAsText (String textValue)
{
InetAddress address = null;

try
{
// IPv4 address
if ( ipv4.matcher(textValue).matches() )
{
String[] addressParts = textValue.split("\\.");
assert addressParts.length == 4;

byte[] addressBytes = new byte[addressParts.length];
for (int i=0; i<addressParts.length; i++)
{
addressBytes[i] = (byte)Short.parseShort( addressParts[i] );
}

address = InetAddress.getByAddress(addressBytes);
}
// IPv6 address
else if ( ipv6.matcher(textValue).matches() )
{
String[] addressParts = textValue.split(":");
assert addressParts.length == 8;

byte[] addressBytes = new byte[addressParts.length*2];
for (int i=0; i<addressParts.length; i++)
{
addressBytes[i*2] = Byte.parseByte( addressParts[i].substring(0,2) );
addressBytes[i*2+1] = Byte.parseByte( addressParts[i].substring(2,4) );
}

address = InetAddress.getByAddress(addressBytes);
}
// host name
else
{
address = InetAddress.getByName(textValue);
}
}
catch (UnknownHostException ex)
{
throw new IllegalArgumentException(ex);
}

setValue(address);
}

/** Get text representation of the value.
*
* @return InetAddress text.
*/
@Override
public String getAsText()
{
return ((InetAddress) getValue()).getHostAddress();
}
}


Excerpt from Spring config file with example of usage:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.net.InetAddress">
<bean id="inetAddressEditor" class="net.bithill.InetAddressEditor" />
</entry>
</map>
</property>
</bean>

<bean id="mpingData" class="net.bithill.mping.MPingData">

<property name="hosts">
<list value-type="java.net.InetAddress">
<value>192.168.111.254</value>
<value>10.1.5.254</value>
</list>
</property>

...