package edu.upmc.ccweb.stripesCommon.stripes; import java.util.Collection; import java.util.Locale; import sun.net.util.IPAddressUtil; import net.sourceforge.stripes.validation.ScopedLocalizableError; import net.sourceforge.stripes.validation.TypeConverter; import net.sourceforge.stripes.validation.ValidationError; /** *

A faux TypeConverter that validates that the String supplied is a valid IPv4 address. * Relies on sun.net.util.IPAddressUtil for the bulk of the work.

* *

If the String cannot be parsed, a single error message will be generated. The error * message is a scoped message with a default scope of converter.ip and name * invalidIp. As a result error messages will be looked for in the following * order:

* * * */ public class IpTypeConverter implements TypeConverter { /** Accepts the Locale provide, but does nothing with it since IPs are Locale-less. */ public void setLocale(Locale locale) { /* Doesn't matter for IP. */} /** * Validates the user input to ensure that it is a valid IP address. * * @param input the String input, always a non-null non-empty String * @param targetType realistically always String since java.lang.String is final * @param errors a non-null collection of errors to populate in case of error * @return the parsed IP address, or null if there are errors. */ public String convert(String input, Class targetType, Collection errors) { if (IPAddressUtil.isIPv4LiteralAddress(input)) { return input; } errors.add(new ScopedLocalizableError("converter.ip", "invalidIp")); return null; } }