/** BEGIN COPYRIGHT BLOCK
 * Copyright (C) 2001 Sun Microsystems, Inc.  Used by permission.
 * Copyright (C) 2005 Red Hat, Inc.
 * All rights reserved.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 * 
 * END COPYRIGHT BLOCK **/
package com.netscape.management.admserv.config;

/**
 * A text model (document) that restrects JTextField charaters to a specified character set. It
 * can be used to create, for instance, digit-only text fields, alphanumeric-only text fields,
 * etc. If a non allowed character is entered by the user, the charachter does not get echoed back
 * to the screen and the Console beeps.
 *
 * Usage example for digits only text field: <code>
 * JtextField tfPortNumber = new JTextField();
 * tfPortNumber.setDocument(new FilteredInputDocument("1234567890");
 * </code>
 *
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class FilteredInputDocument extends PlainDocument {

    public static final String DIGITS = "01234567890";
    public static final String IPADDRESS = "01234567890.";

    String _allowSet;

    public FilteredInputDocument(String allowSet) {
        _allowSet = allowSet;
    }

    public static FilteredInputDocument allowDigitsOnly() {
        return new FilteredInputDocument(DIGITS);
    }

    public static FilteredInputDocument allowIPAddressOnly() {
        return new FilteredInputDocument(IPADDRESS);
    }

    public void insertString(int offs, String str,
            AttributeSet a) throws BadLocationException {
        String filtered = new String();
        for (int i = 0; i < str.length(); i++) {
            if (_allowSet.indexOf(str.charAt(i)) < 0) {
                Toolkit.getDefaultToolkit().beep();
            } else {
                filtered += str.charAt(i);
            }
        }
        if (filtered.length() > 0) {
            super.insertString(offs, filtered, a);
        }
    }
}
