commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Eric Galluzzo <egallu...@einnovation.com>
Subject Re: Digester: setting a java.net.URL property
Date Tue, 05 Aug 2003 20:35:28 GMT
Brian Sayatovic/AMIG wrote:

>I have an XML file that contains this sort of element:
>
>        <FtpUrl>ftp://user:pass@host:21/some/path</FtpUrl>
>
>I also have a Config object that has a java.net.URL property with a 
>getter/setter:
>
>        public class MyConfig {
>                // ...
>                public URL getFtpUrl();
>                public void setFtpUrl(URL url);
>                // ...
>        }
>
>However, I can't decide how to tie these together with Digester.  I 
>couldn't get a bean property setter to work, I suspect because there is no 
>conversion between the String in the XML file and a java.net.URL.
>
That's right.  Try creating a new BeanUtils Converter, something like:

package whatever;

import java.net.MalformedURLException;
import org.apache.commons.beanutils.Converter;

public class URLConverter implements Converter
{
   public Object convert(Class type, Object value)
   {
      if ( value == null )
      {
         return null;
      }
      else if ( value instanceof URL )
      {
         return value;
      }
      else // assume it's a string
      {
         String strValue = (String) value;
         if ( strValue.equals( "" ) )
         {
            return null;
         }
         else
         {
            try
            {
               return new URL( strValue );
            }
            catch ( MalformedURLException mue )
            {
               return null; // FIXME: Should log the error somehow
            }
         }
      }
   }
}

Then register it with BeanUtils' ConvertUtils class, thus:

import org.apache.commons.beanutils.ConvertUtils;
import whatever.URLConverter;

...
// Near the beginning of your app...
ConvertUtils.register( new URLConverter(), URL.class );
...

Warning: The above may not quite compile, but you can probably figure it 
out from there.

    - Eric



Mime
View raw message