001    package edu.nrao.sss.webapp.faces.converter;
002    
003    import javax.faces.convert.Converter;
004    import javax.faces.convert.ConverterException;
005    import javax.faces.context.FacesContext;
006    import javax.faces.component.UIComponent;
007    import javax.faces.application.FacesMessage;
008    
009    import java.net.URL;
010    import java.net.MalformedURLException;
011    
012    import org.apache.log4j.Logger;
013    
014    /**
015     * This class converts a URL to and from a String.
016     */
017    public class UrlConverter implements Converter
018    {
019            private static Logger log = Logger.getLogger(UrlConverter.class);
020            
021            public Object getAsObject(FacesContext context, UIComponent component, String value)
022            {
023                    URL url = null;
024                    if (value != null && value.length() > 0)
025                    {
026                            try
027                            {
028                                    url = new URL(value);
029                            }
030                            
031                            catch (MalformedURLException e)
032                            {
033            // Try prepending a default protocol to the front and see if that flies.
034            try { url = new URL("http://" + value); }
035    
036            catch (MalformedURLException e2)
037            {
038              //Deliberately using e to report the error, not e2!
039              throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Value '" + value + "' is not a valid URL."), e);
040            }
041                            }
042                    }
043                    
044                    return url;
045            }
046    
047            public String getAsString(FacesContext context, UIComponent component, Object value)
048            {
049                    if (value == null)
050                            return "";
051    
052                    else if (value instanceof URL)
053                    {
054                            return value.toString();
055                    }
056    
057                    else
058                    {
059                            log.warn("Can not Convert objects of type: " + value.getClass());
060                            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_WARN, "", "Can not Convert objects of type: " + value.getClass()));
061                    }
062            }
063    }