mitm.common.util.DomainUtils.java Source code

Java tutorial

Introduction

Here is the source code for mitm.common.util.DomainUtils.java

Source

/*
 * Copyright (c) 2008-2011, Martijn Brinkers, Djigzo.
 * 
 * This file is part of Djigzo email encryption.
 *
 * Djigzo is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License 
 * version 3, 19 November 2007 as published by the Free Software 
 * Foundation.
 *
 * Djigzo 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public 
 * License along with Djigzo. If not, see <http://www.gnu.org/licenses/>
 *
 * Additional permission under GNU AGPL version 3 section 7
 * 
 * If you modify this Program, or any covered work, by linking or 
 * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, 
 * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, 
 * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, 
 * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, 
 * wsdl4j-1.6.1.jar (or modified versions of these libraries), 
 * containing parts covered by the terms of Eclipse Public License, 
 * tyrex license, freemarker license, dom4j license, mx4j license,
 * Spice Software License, Common Development and Distribution License
 * (CDDL), Common Public License (CPL) the licensors of this Program grant 
 * you additional permission to convey the resulting work.
 */
package mitm.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * Domain related helper functions like validating domain names etc. 
 * 
 * @author Martijn Brinkers
 *
 */
public class DomainUtils {
    public enum DomainType {
        FULLY_QUALIFIED, WILD_CARD, FRAGMENT
    };

    /*
     * Regular expression pattern for a fully qualified domain with wild card. 
     */
    private final static Pattern wildcardPattern = Pattern
            .compile("^\\s*(([a-zA-Z0-9-]+|[\\*])\\.([a-zA-Z0-9-]+\\.)*([a-zA-Z0-9-]+)+)\\s*$");

    /*
     * Regular expression pattern for a fully qualified domain. 
     */
    private final static Pattern fullyQualifiedPattern = Pattern
            .compile("^\\s*([a-zA-Z0-9-]+\\.([a-zA-Z0-9-]+\\.)*([a-zA-Z0-9-]+)+)\\s*$");

    /*
     * Regular expression pattern for a fully or partly qualified domain. 
     */
    private final static Pattern fragmentPattern = Pattern.compile("^\\s*([a-zA-Z0-9-.]+)\\s*$");

    /**
     * Checks if the domain is valid for the domain type. If not valid null will be returned
     * if valid, leading white space will be removed.
     */
    public static String validate(String domain, DomainType domainType) {
        if (domain == null) {
            return null;
        }

        Pattern pattern = null;

        switch (domainType) {
        case FULLY_QUALIFIED:
            pattern = fullyQualifiedPattern;
            break;
        case WILD_CARD:
            pattern = wildcardPattern;
            break;
        case FRAGMENT:
            pattern = fragmentPattern;
            break;

        default:
            throw new IllegalArgumentException("Unknown domainType.");
        }

        Matcher matcher = pattern.matcher(domain);

        String validated = null;

        if (matcher.matches()) {
            validated = matcher.group(1);

            String trimmed = StringUtils.trim(validated);

            /*
             * A domain should not start or end with -
             */
            if (StringUtils.startsWith(trimmed, "-") || StringUtils.endsWith(trimmed, "-")) {
                validated = null;
            }
        }

        return validated;
    }

    /**
     * Checks if the domain is valid for the domain type. If not valid null will be returned
     * if valid leading white space will be removed and the domain will be all lowercase.
     */
    public static String canonicalizeAndValidate(String domain, DomainType domainType) {
        String validated = validate(domain, domainType);

        if (validated != null) {
            validated = validated.toLowerCase();
        }

        return validated;
    }

    /**
     * Returns true if the domain is a wildcard domain (example: *.example.com)
     */
    public static boolean isWildcardDomain(String domain) {
        String validated = canonicalizeAndValidate(domain, DomainType.WILD_CARD);

        return validated != null && validated.startsWith("*.");
    }

    /**
     * Removes the wildcard part of a domain. If domain does not have a wildcard part the complete domain
     * is returned. The returned domain is canonicalized. 
     */
    public static String removeWildcard(String domain) {
        String validated = canonicalizeAndValidate(domain, DomainType.WILD_CARD);

        return StringUtils.removeStart(validated, "*.");
    }

    /**
     * Return true if the domain is matched by the wildcard domain
     * 
     * Examples: 
     * - example.com is matched by *.example.com
     * - test.example.com is matched by *.example.com
     * - test.test.example.com is NOT matched by *.example.com
     */
    public static boolean isWildcardMatchDomain(String domain, String wildcardDomain) {
        if (domain == null || wildcardDomain == null) {
            return false;
        }

        if (!isWildcardDomain(wildcardDomain)) {
            return false;
        }

        String validDomain = canonicalizeAndValidate(domain, DomainType.FULLY_QUALIFIED);

        if (validDomain == null) {
            return false;
        }

        String noWildcard = removeWildcard(wildcardDomain);

        if (StringUtils.equalsIgnoreCase(validDomain, noWildcard)) {
            return true;
        }

        /*
         * Check if we have a match when we remove the first part of the domain
         */
        return StringUtils.equalsIgnoreCase(getUpperLevelDomain(validDomain), noWildcard);
    }

    /**
     * Returns the upper level domain. 
     * 
     * Example: sub.example.com returns example.com
     */
    public static String getUpperLevelDomain(String domain) {
        return StringUtils.substringAfter(StringUtils.trimToEmpty(domain), ".");
    }
}