/*
 * 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.bebop.parameters;

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

import org.apache.oro.text.perl.Perl5Util;

/**
 *     Verifies that the
 *    parameter's value is composed of only alpha-numeric,
 *    underscore, or hyphen characters. [a-zA-Z_0-9\-]
 *
 *    Note: An empty string will pass the validation tests.
 *
 *    @author Michael Pih 
 *    @version $Revision: #8 $ $DateTime: 2004/04/07 16:07:11 $
 **/
public class URLTokenValidationListener implements ParameterListener {

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

    // match 1 or more instances of a non-alpha-numeric character
    private static final String NON_KEYWORD_PATTERN = "/[^a-zA-Z_0-9\\-]+/";

    private String m_label;

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

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

    /**
     * Validates the parameter by checking if the value is a valid keyword.
     * A keyword is defined as any combination of alph-numeric characters,
     * hyphens, and/or underscores.  [a-zA-Z_0-9\-]
     *
     * Note: An empty string will pass the validation tests.
     *
     * @param event The parameter event
     */
    public void validate(ParameterEvent event) {
        ParameterData data = event.getParameterData();
        Object value = data.getValue();

        Perl5Util util = new Perl5Util();
        if ( !util.match(NON_KEYWORD_PATTERN, value.toString()) ) {
            return;
        }

        // The error message
        StringBuffer msg = new StringBuffer(128);
        msg
            .append(m_label)
            .append(
                    " must contain only alpha-numeric, hyphen, or underscore characters");
        data.addError(msg.toString());
    }
}
