Java Code Examples for com.google.common.net.InternetDomainName#from()

The following examples show how to use com.google.common.net.InternetDomainName#from() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URLRegexTransformer.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
public static String hostToPublicSuffix(String host) {
	InternetDomainName idn;

	try {
		idn = InternetDomainName.from(host);
	} catch(IllegalArgumentException e) {
		return host;
	}
	InternetDomainName tmp = idn.publicSuffix();
	if(tmp == null) {
		return host;
	}
	String pubSuff = tmp.toString();
	int idx = host.lastIndexOf(".", host.length() - (pubSuff.length()+2));
	if(idx == -1) {
		return host;
	}
	return host.substring(idx+1);
}
 
Example 2
Source File: NetworkFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
private static InternetDomainName toDomainName(Object dnObj) {
  if(dnObj != null) {
    if(dnObj instanceof String) {
      String dn = dnObj.toString();
      try {
        return InternetDomainName.from(dn);
      }
      catch(IllegalArgumentException iae) {
        return null;
      }
    }
    else {
      throw new IllegalArgumentException(dnObj + " is not a string and therefore also not a domain.");
    }
  }
  return null;
}
 
Example 3
Source File: OAuth2CookieHelper.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the top level domain of the server from the request. This is used to limit the Cookie
 * to the top domain instead of the full domain name.
 * <p>
 * A lot of times, individual gateways of the same domain get their own subdomain but authentication
 * shall work across all subdomains of the top level domain.
 * <p>
 * For example, when sending a request to <code>app1.domain.com</code>,
 * this returns <code>.domain.com</code>.
 *
 * @param request the HTTP request we received from the client.
 * @return the top level domain to set the cookies for.
 * Returns null if the domain is not under a public suffix (.com, .co.uk), e.g. for localhost.
 */
private String getCookieDomain(HttpServletRequest request) {
    String domain = oAuth2Properties.getWebClientConfiguration().getCookieDomain();
    if (domain != null) {
        return domain;
    }
    //if not explicitly defined, use top-level domain
    domain = request.getServerName().toLowerCase();
    //strip off leading www.
    if (domain.startsWith("www.")) {
        domain = domain.substring(4);
    }
    //if it isn't an IP address
    if (!InetAddresses.isInetAddress(domain)) {
        //strip off subdomains, leaving the top level domain only
        InternetDomainName domainName = InternetDomainName.from(domain);
        if (domainName.isUnderPublicSuffix() && !domainName.isTopPrivateDomain()) {
            //preserve leading dot
            return "." + domainName.topPrivateDomain().toString();
        }
    }
    //no top-level domain, stick with default domain
    return null;
}
 
Example 4
Source File: TextFilterManage.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取URL中的根域名
 * 必须 http 或 https 或 // 开头
 * @param url
 * @return
 * @throws URISyntaxException
 */
private String getTopPrivateDomain(String url){
	//java1.8.0_181以下版本的new URL(url).getHost()方法存在右斜杆和井号被绕过漏洞。例如在低版本https://www.aaa.com\www.bbb.com?a123执行结果为www.aaa.com\www.bbb.com
	url = url.replaceAll("[\\\\#]","/"); //替换掉反斜线和井号

	url = StringUtils.substringBefore(url, "?");//截取到等于第二个参数的字符串为止
	
    String host = null;
	try {
		URI uri = new URI(url);
		if(uri != null){
			host = uri.getHost();
		}
	} catch (URISyntaxException e) {
		//e.printStackTrace();
	}
    if(host != null && !"".equals(host.trim())){
    	InternetDomainName domainName = InternetDomainName.from(host);
 	    return domainName.topPrivateDomain().toString();
    }
    
    return "";
}
 
Example 5
Source File: CloudDnsWriter.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Publish A/AAAA records to Cloud DNS.
 *
 * <p>Cloud DNS has no API for glue -- A/AAAA records are automatically matched to their
 * corresponding NS records to serve glue.
 */
@Override
public void publishHost(String hostName) {
  // Get the superordinate domain name of the host.
  InternetDomainName host = InternetDomainName.from(hostName);
  Optional<InternetDomainName> tld = Registries.findTldForName(host);

  // Host not managed by our registry, no need to update DNS.
  if (!tld.isPresent()) {
    logger.atSevere().log("publishHost called for invalid host %s", hostName);
    return;
  }

  // Refresh the superordinate domain, since we shouldn't be publishing glue records if we are not
  // authoritative for the superordinate domain.
  publishDomain(getSecondLevelDomain(hostName, tld.get().toString()));
}
 
Example 6
Source File: DnsUpdateWriter.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
public void publishHost(String hostName) {
  // Get the superordinate domain name of the host.
  InternetDomainName host = InternetDomainName.from(hostName);
  ImmutableList<String> hostParts = host.parts();
  Optional<InternetDomainName> tld = Registries.findTldForName(host);

  // host not managed by our registry, no need to update DNS.
  if (!tld.isPresent()) {
    return;
  }

  ImmutableList<String> tldParts = tld.get().parts();
  ImmutableList<String> domainParts =
      hostParts.subList(hostParts.size() - tldParts.size() - 1, hostParts.size());
  String domain = Joiner.on(".").join(domainParts);

  // Refresh the superordinate domain, always delete the host first to ensure idempotency,
  // and only publish the host if it is a glue record.
  publishDomain(domain, hostName);
}
 
Example 7
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Returns parsed version of {@code name} if domain name label follows our naming rules and is
 * under one of the given allowed TLDs.
 *
 * <p><b>Note:</b> This method does not perform language validation with IDN tables.
 *
 * @see #validateDomainNameWithIdnTables(InternetDomainName)
 */
public static InternetDomainName validateDomainName(String name) throws EppException {
  if (!ALLOWED_CHARS.matchesAllOf(name)) {
    throw new BadDomainNameCharacterException();
  }
  List<String> parts = Splitter.on('.').splitToList(name);
  if (parts.size() <= 1) {
    throw new BadDomainNamePartsCountException();
  }
  if (any(parts, equalTo(""))) {
    throw new EmptyDomainNamePartException();
  }
  validateFirstLabel(parts.get(0));
  InternetDomainName domainName = InternetDomainName.from(name);
  if (getTlds().contains(domainName.toString())) {
    throw new DomainNameExistsAsTldException();
  }
  Optional<InternetDomainName> tldParsed = findTldForName(domainName);
  if (!tldParsed.isPresent()) {
    throw new TldDoesNotExistException(domainName.parent().toString());
  }
  if (domainName.parts().size() != tldParsed.get().parts().size() + 1) {
    throw new BadDomainNamePartsCountException();
  }
  return domainName;
}
 
Example 8
Source File: InternetUtils.java    From vividus with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the domain with desired levels.
 * <p>For example:</p>
 * <ul>
 * <li>for URI: "https://www.by.example.com" and levels = 2 method will return example.com</li>
 * <li>for URI: "https://www.by.example.com" and levels = 5 method will return www.by.example.com</li>
 * </ul>
 * @param uri Uri to process
 * @param domainLevels desired domain levels
 * @return processed domain with desired levels
 */
public static String getDomainName(URI uri, int domainLevels)
{
    InternetDomainName domaneName = InternetDomainName.from(uri.getHost());
    List<String> domainParts = domaneName.parts();
    if (domainLevels < domainParts.size())
    {
        List<String> resultDomainParts = domainParts.subList(domainParts.size() - domainLevels, domainParts.size());
        return String.join(DOMAIN_PARTS_SEPARATOR, resultDomainParts);
    }
    return domaneName.toString();
}
 
Example 9
Source File: TargetModelElasticSearch.java    From ache with Apache License 2.0 5 votes vote down vote up
public TargetModelElasticSearch(TargetModelCbor model) {

        URL url = Urls.toJavaURL(model.url);
        String rawContent = (String) model.response.get("body");

        Page page = new Page(url, rawContent);
        page.setParsedData(new ParsedData(new PaginaURL(url, rawContent)));

        this.html = rawContent;
        this.url = model.url;
        this.retrieved = new Date(model.timestamp * 1000);
        this.words = page.getParsedData().getWords();
        this.wordsMeta = page.getParsedData().getWordsMeta();
        this.title = page.getParsedData().getTitle();
        this.domain = url.getHost();

        try {
            this.text = DefaultExtractor.getInstance().getText(page.getContentAsString());
        } catch (Exception e) {
            this.text = "";
        }

        InternetDomainName domainName = InternetDomainName.from(page.getDomainName());
        if (domainName.isUnderPublicSuffix()) {
            this.topPrivateDomain = domainName.topPrivateDomain().toString();
        } else {
            this.topPrivateDomain = domainName.toString();
        }
    }
 
Example 10
Source File: LinkRelevance.java    From ache with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
private static InternetDomainName getDomainName(String host) {
    InternetDomainName domain = InternetDomainName.from(host);
    if(host.startsWith("www.")) {
        return InternetDomainName.from(host.substring(4));
    } else {
        return domain;
    }
}
 
Example 11
Source File: HostFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Checks that a host name is valid. */
public static InternetDomainName validateHostName(String name) throws EppException {
  checkArgumentNotNull(name, "Must specify host name to validate");
  if (name.length() > 253) {
    throw new HostNameTooLongException();
  }
  String hostNameLowerCase = Ascii.toLowerCase(name);
  if (!name.equals(hostNameLowerCase)) {
    throw new HostNameNotLowerCaseException(hostNameLowerCase);
  }
  try {
    String hostNamePunyCoded = Idn.toASCII(name);
    if (!name.equals(hostNamePunyCoded)) {
      throw new HostNameNotPunyCodedException(hostNamePunyCoded);
    }
    InternetDomainName hostName = InternetDomainName.from(name);
    if (!name.equals(hostName.toString())) {
      throw new HostNameNotNormalizedException(hostName.toString());
    }
    // The effective TLD is, in order of preference, the registry suffix, if the TLD is a real TLD
    // published in the public suffix list (https://publicsuffix.org/, note that a registry suffix
    // is in the "ICANN DOMAINS" in that list); or a TLD managed by Nomulus (in-bailiwick), found
    // by #findTldForName; or just the last part of a domain name.
    InternetDomainName effectiveTld =
        hostName.isUnderRegistrySuffix()
            ? hostName.registrySuffix()
            : findTldForName(hostName).orElse(InternetDomainName.from("invalid"));
    // Checks whether a hostname is deep enough. Technically a host can be just one level beneath
    // the effective TLD (e.g. example.com) but we require by policy that it has to be at least
    // one part beyond that (e.g. ns1.example.com).
    if (hostName.parts().size() < effectiveTld.parts().size() + 2) {
      throw new HostNameTooShallowException();
    }
    return hostName;
  } catch (IllegalArgumentException e) {
    throw new InvalidHostNameException();
  }
}
 
Example 12
Source File: DigitalAssetLinksRepository.java    From android-AutofillFramework with Apache License 2.0 5 votes vote down vote up
public static String getCanonicalDomain(String domain) {
    InternetDomainName idn = InternetDomainName.from(domain);
    while (idn != null && !idn.isTopPrivateDomain()) {
        idn = idn.parent();
    }
    return idn == null ? null : idn.toString();
}
 
Example 13
Source File: DigitalAssetLinksRepository.java    From input-samples with Apache License 2.0 5 votes vote down vote up
public static String getCanonicalDomain(String domain) {
    InternetDomainName idn = InternetDomainName.from(domain);
    while (idn != null && !idn.isTopPrivateDomain()) {
        idn = idn.parent();
    }
    return idn == null ? null : idn.toString();
}
 
Example 14
Source File: GameServer.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
public void checkFriendServer(Friend friend) {
	getOnlineFriends().remove(friend.getUsername());
	String friendServer = friend.getServer();
	if (friendServer == null || friendServer.equals("Hidden")) {
		return;
	}
	String friendHost = friendServer.split(":")[0];
	if (StringUtils.equals(friendHost, getHost())) {
		getOnlineFriends().add(friend.getUsername());
	} else {
		boolean selfValid = InternetDomainName.isValid(getHost());
		boolean friendValid = InternetDomainName.isValid(friendHost);
		if (selfValid && friendValid) {
			InternetDomainName mainDomain = InternetDomainName.from(getHost());
			InternetDomainName friendDomain = InternetDomainName.from(friendHost);
			boolean mainPublic = mainDomain.isUnderPublicSuffix();
			boolean friendPublic = friendDomain.isUnderPublicSuffix();
			if (mainPublic && friendPublic) {
				String mainServerDomain = mainDomain.topPrivateDomain().toString();
				String friendMainServerDomain = friendDomain.topPrivateDomain().toString();
				if (mainServerDomain.equals(friendMainServerDomain)) {
					getOnlineFriends().add(friend.getUsername());
				}
			}
		}
	}
}
 
Example 15
Source File: GameServer.java    From The-5zig-Mod with GNU General Public License v3.0 5 votes vote down vote up
public void checkFriendServer(Friend friend) {
	getOnlineFriends().remove(friend.getUsername());
	String friendServer = friend.getServer();
	if (friendServer == null || friendServer.equals("Hidden")) {
		return;
	}
	String friendHost = friendServer.split(":")[0];
	if (StringUtils.equals(friendHost, getHost())) {
		getOnlineFriends().add(friend.getUsername());
	} else {
		boolean selfValid = InternetDomainName.isValid(getHost());
		boolean friendValid = InternetDomainName.isValid(friendHost);
		if (selfValid && friendValid) {
			InternetDomainName mainDomain = InternetDomainName.from(getHost());
			InternetDomainName friendDomain = InternetDomainName.from(friendHost);
			boolean mainPublic = mainDomain.isUnderPublicSuffix();
			boolean friendPublic = friendDomain.isUnderPublicSuffix();
			if (mainPublic && friendPublic) {
				String mainServerDomain = mainDomain.topPrivateDomain().toString();
				String friendMainServerDomain = friendDomain.topPrivateDomain().toString();
				if (mainServerDomain.equals(friendMainServerDomain)) {
					getOnlineFriends().add(friend.getUsername());
				}
			}
		}
	}
}
 
Example 16
Source File: Registry.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/** Retrieve the actual domain name representing the TLD for which this registry operates. */
public InternetDomainName getTld() {
  return InternetDomainName.from(tldStr);
}
 
Example 17
Source File: ScalarTypesTest.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
public void testInternetDomainNameSerialization() throws Exception
{
    final String INPUT = "google.com";
    InternetDomainName name = InternetDomainName.from(INPUT);
    assertEquals(quote(INPUT), MAPPER.writeValueAsString(name));
}
 
Example 18
Source File: InternetDomainNameDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
@Override
protected InternetDomainName _deserialize(String value, DeserializationContext ctxt)
        throws IOException {
    return InternetDomainName.from(value);
}
 
Example 19
Source File: InternetDomainNameParameter.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Override
public InternetDomainName convert(String value) {
  return InternetDomainName.from(value);
}
 
Example 20
Source File: NodeUtils.java    From haven-platform with Apache License 2.0 2 votes vote down vote up
/**
 * Node name must be valid host name. In this method we check it.
 * @param name
 */
public static void checkName(String name) {
    InternetDomainName.from(name);
}