de.unentscheidbar.validation.builtin.Ipv4AddressValidator.java Source code

Java tutorial

Introduction

Here is the source code for de.unentscheidbar.validation.builtin.Ipv4AddressValidator.java

Source

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved. Portions Copyrighted 2012 Daniel
 * Huss.
 *
 * The contents of this file are subject to the terms of either the GNU General Public License
 * Version 2 only ("GPL") or the Common Development and Distribution License("CDDL") (collectively,
 * the "License"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.netbeans.org/cddl-gplv2.html or nbbuild/licenses/CDDL-GPL-2-CP.
 * See the License for the specific language governing permissions and limitations under the
 * License. When distributing the software, include this License Header Notice in each file and
 * include the License file at nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this particular file
 * as subject to the "Classpath" exception as provided by Sun in the GPL Version 2 section of the
 * License file that accompanied this code. If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * Contributor(s):
 *
 * The Original Software is NetBeans. The Initial Developer of the Original Software is Sun
 * Microsystems, Inc. Portions Copyright 1997-2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * If you wish your version of this file to be governed by only the CDDL or only the GPL Version 2,
 * indicate your decision by adding "[Contributor] elects to include this software in this
 * distribution under the [CDDL or GPL Version 2] license." If you do not indicate a single choice
 * of license, a recipient has the option to distribute your version of this file under either the
 * CDDL, the GPL Version 2 or to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL Version 2 license, then the
 * option applies only if the new code is made subject to such option by the copyright holder.
 */
package de.unentscheidbar.validation.builtin;

import static com.google.common.base.Preconditions.*;

import javax.annotation.Nonnegative;
import javax.annotation.concurrent.Immutable;

import org.apache.commons.lang3.StringUtils;

import com.google.common.primitives.Ints;

import de.unentscheidbar.validation.Severity;
import de.unentscheidbar.validation.ValidationMessage;
import de.unentscheidbar.validation.ValidationResult;
import de.unentscheidbar.validation.swing.Validation;

/**
 *
 */
@Immutable
public final class Ipv4AddressValidator extends EmptyStringAcceptingValidator {

    private static final int BITS_PER_IPV4 = 32;

    private static final long serialVersionUID = Validation.VERSION;

    public static enum Id implements ValidationMessage.Id {
        TOO_FEW_SEGMENTS, TOO_MANY_SEGMENTS, BAD_SUBNET_MASK, SEGMENT_INVALID
    }

    private static final int IPV4_SEGMENT_COUNT = 4;

    private final int minBits;
    private final int maxBits;

    private static final Ipv4AddressValidator SINGLE_ADDRESS_INSTANCE = new Ipv4AddressValidator(BITS_PER_IPV4,
            BITS_PER_IPV4);

    private static final NumberValidator BYTE_RANGE_VALIDATOR = NumberValidator.rangeOfIntegers(0, 255);

    public static Ipv4AddressValidator singleAddress() {

        return SINGLE_ADDRESS_INSTANCE;
    }

    public static Ipv4AddressValidator addressRange(int minBits, int maxBits) {

        return new Ipv4AddressValidator(Math.min(minBits, maxBits), Math.max(minBits, maxBits));
    }

    private Ipv4AddressValidator(@Nonnegative int minBits, @Nonnegative int maxBits) {

        super();
        checkArgument(minBits >= 0 && minBits <= BITS_PER_IPV4, "minBits must be between 0 and " + BITS_PER_IPV4);
        checkArgument(maxBits >= 0 && maxBits <= BITS_PER_IPV4, "maxBits must be between 0 and " + BITS_PER_IPV4);
        this.maxBits = maxBits;
        this.minBits = minBits;
    }

    @Override
    protected void validateNonEmptyString(ValidationResult result, String s) {

        String[] parts = StringUtils.splitPreserveAllTokens(s, '.');

        /*
         * Number of segments ok?
         */
        if (parts.length < IPV4_SEGMENT_COUNT) {
            result.add(Id.TOO_FEW_SEGMENTS, s, parts.length);
            return;
        } else if (parts.length > IPV4_SEGMENT_COUNT) {
            result.add(Id.TOO_MANY_SEGMENTS, s, parts.length);
            return;
        }
        assert parts.length == IPV4_SEGMENT_COUNT;

        /* Handle bitmask modifier, if present (such as 10.37.0.0/16) */
        String maskStr = "";
        int maxIdx = parts.length - 1;
        int slashIndex = parts[maxIdx].lastIndexOf('/');
        if (slashIndex != -1) {
            maskStr = StringUtils.substring(parts[maxIdx], slashIndex + 1);
            parts[maxIdx] = parts[maxIdx].substring(0, slashIndex);
        }

        Integer bits = maskStr.isEmpty() ? Integer.valueOf(BITS_PER_IPV4) : Ints.tryParse(maskStr);
        if (bits == null || bits < minBits || bits > maxBits) {
            result.add(Id.BAD_SUBNET_MASK, bits == null ? maskStr : bits.toString(), minBits, maxBits);
            return;
        }
        for (int i = 0; i < parts.length; i++) {
            if (!BYTE_RANGE_VALIDATOR.wouldAcceptWithout(Severity.ERROR, parts[i])) {
                result.add(Id.SEGMENT_INVALID, i, parts[i]);
                break;
            }
        }
    }
}