DomainCheckUtil.java 1.79 KB
package com.yohoufo.common.utils;

import com.google.common.collect.Sets;

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

/**
 * Created by li.ma on 2019/5/7.
 */
public class DomainCheckUtil {
    // 图片的域名只能是公司内部的域名
    private static Set<String> YOHODOMAINLIST = Sets.newHashSet("yohobuy.com", "yoho.cn", "yhbimg.com", "yohoboys.com");

    /**
     * 是否存在非法的域名
     * @param imageUrl
     * @return true 存在
     */
    public static boolean existInvalidDomain(String imageUrl) {
        if (imageUrl.startsWith("//")) {
            return compareDomain(imageUrl.substring(2, imageUrl.indexOf('/', 2)));
        }

        String  propertyStr = imageUrl.replace('\\', '/');
        Pattern p = Pattern.compile("[http:|https:]//(.+?)[/|'|\"|\\s|>]", Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(propertyStr);
        while (matcher.find()) {
            String domainStr = matcher.group(1);       // 查询字符串中链接的域名
            if (compareDomain(domainStr)) {
                return true;
            }
        }
        return false;
    }

    public static boolean compareDomain(String domain) {
        boolean result = true;
        for (String yohoDomainStr : YOHODOMAINLIST) {
            if (domain.endsWith(yohoDomainStr)) { // 如果域名并不是YOHO相关的域名,则剔除
                result = false;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        //System.out.println(queryInvalidDomain("//img01.yohoboys.com/license/1554113944689/Screenshot_20190401_173857_com.yoho.jpg"));
        System.out.println(existInvalidDomain("http://img01.yohoboys.com/license/1554113944689/Screenshot_20190401_173857_com.yoho.jpg"));
    }
}