/*
 * Copyright (C) 2001-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.ui.admin;

import com.arsdigita.bebop.parameters.ParameterData;
import com.arsdigita.bebop.event.ParameterListener;
import com.arsdigita.bebop.event.ParameterEvent;

import java.net.URL;
import java.net.MalformedURLException;

/**
 *  Verifies that the
 * parameter is a valid URL specification.  Does this by trying to
 * construct an actual URL object from the parameter and catching any
 * MalformedURLException thrown by the URL constructor.
 *
 * <p><b>Note</b>: Validates empty parameters so that URLs can be left
 * blank without generating a form error.  If you require a URL be
 * sure to add a NotEmptyValidationListener.  This class will also
 * validate a protocol-only URL like "http://".
 *
 * @see com.arsdigita.bebop.parameters.NotEmptyValidationListener
 * @see java.net.URL
 *
 * @version $Id: //core-platform/dev/src/com/arsdigita/ui/admin/URLValidationListener.java#9 $
 */

public class URLValidationListener implements ParameterListener {

    public static final String versionId = "$Id: //core-platform/dev/src/com/arsdigita/ui/admin/URLValidationListener.java#9 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    /**
     * A label for the item being validated
     */

    private String m_label;

    /**
     * Constructor
     */

    public URLValidationListener() {
        this("This parameter");
    }

    /**
     * Constructor
     */

    public URLValidationListener(String label) {
        m_label = label;
    }


    /**
     * Validate the parameter using the URL constructor.
     */

    public void validate (ParameterEvent event) {

        ParameterData data = event.getParameterData();

        String value = data.getValue().toString();

        if (value != null && value.length() > 0) {
            try {
                new URL(value);
            } catch (MalformedURLException ex) {
                StringBuffer msg = new StringBuffer(128);
                msg.append(m_label);
                msg.append(" is not a valid URL specification: ");
                msg.append(ex.getMessage());
                msg.append(". A valid URL looks like \"http://mysite.net\".");
                data.addError(msg.toString());
            }
        }
    }
}
