下面列出了怎么用com.google.common.net.InternetDomainName的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
@Override
public Object apply(List<Object> objects) {
if(objects.isEmpty()) {
return null;
}
Object dnObj = objects.get(0);
InternetDomainName idn = toDomainName(dnObj);
if(idn != null) {
String dn = dnObj.toString();
String tld = extractTld(idn, dn);
if(!StringUtils.isEmpty(dn)) {
String suffix = safeSubstring(dn, 0, dn.length() - tld.length());
String hostnameWithoutTLD = safeSubstring(suffix, 0, suffix.length() - 1);
if(hostnameWithoutTLD == null) {
return dn;
}
String hostnameWithoutSubsAndTLD = Iterables.getLast(Splitter.on(".").split(hostnameWithoutTLD), null);
if(hostnameWithoutSubsAndTLD == null) {
return null;
}
return hostnameWithoutSubsAndTLD + "." + tld;
}
}
return null;
}
@Override
public Object apply(List<Object> objects) {
Object dnObj = objects.get(0);
InternetDomainName idn = toDomainName(dnObj);
if(idn != null) {
String dn = dnObj.toString();
String tld = extractTld(idn, dn);
String suffix = safeSubstring(dn, 0, dn.length() - tld.length());
if(StringUtils.isEmpty(suffix)) {
return suffix;
}
else {
return suffix.substring(0, suffix.length() - 1);
}
}
return null;
}
@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);
}
@Override
public JsonDeserializer<?> findBeanDeserializer(final JavaType type, DeserializationConfig config,
BeanDescription beanDesc)
{
if (type.hasRawClass(RangeSet.class)) {
return new RangeSetDeserializer();
}
if (type.hasRawClass(Range.class)) {
return new RangeDeserializer(type, _defaultBoundType);
}
if (type.hasRawClass(HostAndPort.class)) {
return HostAndPortDeserializer.std;
}
if (type.hasRawClass(InternetDomainName.class)) {
return InternetDomainNameDeserializer.std;
}
if (type.hasRawClass(HashCode.class)) {
return HashCodeDeserializer.std;
}
return null;
}
@Override
public boolean hasDeserializerFor(DeserializationConfig config, Class<?> valueType) {
if (valueType.getName().startsWith("com.google.")) {
System.err.println("DEBUG: hasDeserializerFor? "+valueType+"...");
return (valueType == Optional.class)
|| (valueType == RangeSet.class)
|| (valueType == HostAndPort.class)
|| (valueType == InternetDomainName.class)
|| (valueType == HashCode.class)
// Ok to claim we might support; not a guarantee
|| Multiset.class.isAssignableFrom(valueType)
|| Multimap.class.isAssignableFrom(valueType)
|| ImmutableCollection.class.isAssignableFrom(valueType)
|| ImmutableMap.class.isAssignableFrom(valueType)
|| BiMap.class.isAssignableFrom(valueType)
;
}
return false;
}
/**
* Returns the second level domain name for a fully qualified host name under a given tld.
*
* <p>This function is merely a string parsing utility, and does not verify if the tld is operated
* by the registry.
*
* @throws IllegalArgumentException if either argument is null or empty, or the domain name is not
* under the tld
*/
public static String getSecondLevelDomain(String hostName, String tld) {
checkArgument(
!Strings.isNullOrEmpty(hostName),
"hostName cannot be null or empty");
checkArgument(!Strings.isNullOrEmpty(tld), "tld cannot be null or empty");
ImmutableList<String> domainParts = InternetDomainName.from(hostName).parts();
ImmutableList<String> tldParts = InternetDomainName.from(tld).parts();
checkArgument(
domainParts.size() > tldParts.size(),
"hostName must be at least one level below the tld");
checkArgument(
domainParts
.subList(domainParts.size() - tldParts.size(), domainParts.size())
.equals(tldParts),
"hostName must be under the tld");
ImmutableList<String> sldParts =
domainParts.subList(domainParts.size() - tldParts.size() - 1, domainParts.size());
return Joiner.on(".").join(sldParts);
}
@Test
public void test_checkDomainsWithToken_successfullyVerifiesValidToken() {
persistResource(
new AllocationToken.Builder().setToken("tokeN").setTokenType(SINGLE_USE).build());
assertThat(
flowUtils
.checkDomainsWithToken(
ImmutableList.of(
InternetDomainName.from("blah.tld"), InternetDomainName.from("blah2.tld")),
"tokeN",
"TheRegistrar",
DateTime.now(UTC))
.domainCheckResults())
.containsExactlyEntriesIn(
ImmutableMap.of(
InternetDomainName.from("blah.tld"), "", InternetDomainName.from("blah2.tld"), ""))
.inOrder();
}
@Override
public T build() {
checkArgumentNotNull(emptyToNull(getInstance().label), "Label must be specified");
checkArgument(
getInstance().label.equals(canonicalizeDomainName(getInstance().label)),
"Label '%s' must be in puny-coded, lower-case form",
getInstance().label);
checkArgumentNotNull(getInstance().getValue(), "Value must be specified");
// Verify that the label creates a valid SLD if we add a TLD to the end of it.
// We require that the label is not already a full domain name including a dot.
// Domain name validation is tricky, so let InternetDomainName handle it for us.
checkArgument(
InternetDomainName.from(getInstance().label + ".tld").parts().size() == 2,
"Label %s must not be a multi-level domain name",
getInstance().label);
return super.build();
}
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);
}
@Override
protected void initMutatingEppToolCommand() {
checkArgument(superuser, "This command must be run as a superuser.");
findTldForNameOrThrow(InternetDomainName.from(domainName)); // Check that the tld exists.
if (isNullOrEmpty(password)) {
password = passwordGenerator.createString(DEFAULT_PASSWORD_LENGTH);
}
Money cost = null;
if (fee) {
cost = getDomainCreateCost(domainName, DateTime.now(UTC), DEFAULT_ANCHOR_TENANT_PERIOD_YEARS);
}
setSoyTemplate(CreateAnchorTenantSoyInfo.getInstance(),
CreateAnchorTenantSoyInfo.CREATEANCHORTENANT);
addSoyRecord(clientId, new SoyMapData(
"domainName", domainName,
"contactId", contact,
"reason", reason,
"password", password,
"period", DEFAULT_ANCHOR_TENANT_PERIOD_YEARS,
"feeCurrency", cost != null ? cost.getCurrencyUnit().toString() : null,
"fee", cost != null ? cost.getAmount().toString() : null));
}
@Test
public void testFindTldForName() {
initTestTlds();
assertThat(Registries.findTldForName(InternetDomainName.from("example.foo")).get().toString())
.isEqualTo("foo");
assertThat(Registries.findTldForName(InternetDomainName.from("x.y.a.b.c")).get().toString())
.isEqualTo("a.b.c");
// We don't have an "example" tld.
assertThat(Registries.findTldForName(InternetDomainName.from("foo.example"))).isEmpty();
// A tld is not a match for itself.
assertThat(Registries.findTldForName(InternetDomainName.from("foo"))).isEmpty();
// The name must match the entire tld.
assertThat(Registries.findTldForName(InternetDomainName.from("x.y.a.b"))).isEmpty();
assertThat(Registries.findTldForName(InternetDomainName.from("x.y.b.c"))).isEmpty();
// Substring tld matches aren't considered.
assertThat(Registries.findTldForName(InternetDomainName.from("example.barfoo"))).isEmpty();
}
/**
* Validates a given token. The token could be invalid if it has allowed client IDs or TLDs that
* do not include this client ID / TLD, or if the token has a promotion that is not currently
* running.
*
* @throws EppException if the token is invalid in any way
*/
private void validateToken(
InternetDomainName domainName, AllocationToken token, String clientId, DateTime now)
throws EppException {
if (!token.getAllowedClientIds().isEmpty() && !token.getAllowedClientIds().contains(clientId)) {
throw new AllocationTokenNotValidForRegistrarException();
}
if (!token.getAllowedTlds().isEmpty()
&& !token.getAllowedTlds().contains(domainName.parent().toString())) {
throw new AllocationTokenNotValidForTldException();
}
if (token.getDomainName().isPresent()
&& !token.getDomainName().get().equals(domainName.toString())) {
throw new AllocationTokenNotValidForDomainException();
}
// Tokens without status transitions will just have a single-entry NOT_STARTED map, so only
// check the status transitions map if it's non-trivial.
if (token.getTokenStatusTransitions().size() > 1
&& !TokenStatus.VALID.equals(token.getTokenStatusTransitions().getValueAtTime(now))) {
throw new AllocationTokenNotInPromotionException();
}
}
private void verifyRestoreAllowed(
Update command,
DomainBase existingDomain,
Optional<FeeUpdateCommandExtension> feeUpdate,
FeesAndCredits feesAndCredits,
DateTime now) throws EppException {
verifyOptionalAuthInfo(authInfo, existingDomain);
if (!isSuperuser) {
verifyResourceOwnership(clientId, existingDomain);
verifyNotReserved(InternetDomainName.from(targetId), false);
verifyPremiumNameIsNotBlocked(targetId, now, clientId);
checkAllowedAccessToTld(clientId, existingDomain.getTld());
}
// No other changes can be specified on a restore request.
if (!command.noChangesPresent()) {
throw new RestoreCommandIncludesChangesException();
}
// Domain must be within the redemptionPeriod to be eligible for restore.
if (!existingDomain.getGracePeriodStatuses().contains(GracePeriodStatus.REDEMPTION)) {
throw new DomainNotEligibleForRestoreException();
}
validateFeeChallenge(targetId, now, feeUpdate, feesAndCredits);
}
private Optional<String> getMessageForCheck(
InternetDomainName domainName,
ImmutableMap<String, ForeignKeyIndex<DomainBase>> existingDomains,
ImmutableMap<InternetDomainName, String> tokenCheckResults,
ImmutableMap<String, TldState> tldStates,
Optional<AllocationToken> allocationToken) {
if (existingDomains.containsKey(domainName.toString())) {
return Optional.of("In use");
}
TldState tldState = tldStates.get(domainName.parent().toString());
if (isReserved(domainName, START_DATE_SUNRISE.equals(tldState))) {
if (!isValidReservedCreate(domainName, allocationToken)
&& !isAnchorTenant(domainName, allocationToken, Optional.empty())) {
ImmutableSet<ReservationType> reservationTypes = getReservationTypes(domainName);
if (!reservationTypes.isEmpty()) {
ReservationType highestSeverityType = getTypeOfHighestSeverity(reservationTypes);
return Optional.of(highestSeverityType.getMessageForCheck());
}
}
}
return Optional.ofNullable(emptyToNull(tokenCheckResults.get(domainName)));
}
/**
* 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()));
}
/** Returns a new renew price for the pricer. */
@SuppressWarnings("unused")
public FeesAndCredits getRenewPrice(
Registry registry, String domainName, DateTime dateTime, int years) throws EppException {
DomainPrices domainPrices = getPricesForDomainName(domainName, dateTime);
BigDecimal renewCost = domainPrices.getRenewCost().multipliedBy(years).getAmount();
return customLogic.customizeRenewPrice(
RenewPriceParameters.newBuilder()
.setFeesAndCredits(
new FeesAndCredits.Builder()
.setCurrency(registry.getCurrency())
.addFeeOrCredit(Fee.create(renewCost, FeeType.RENEW, domainPrices.isPremium()))
.build())
.setRegistry(registry)
.setDomainName(InternetDomainName.from(domainName))
.setAsOfDate(dateTime)
.setYears(years)
.build());
}
/** Returns a new restore price for the pricer. */
public FeesAndCredits getRestorePrice(
Registry registry, String domainName, DateTime dateTime, boolean isExpired)
throws EppException {
DomainPrices domainPrices = getPricesForDomainName(domainName, dateTime);
FeesAndCredits.Builder feesAndCredits =
new FeesAndCredits.Builder()
.setCurrency(registry.getCurrency())
.addFeeOrCredit(
Fee.create(registry.getStandardRestoreCost().getAmount(), FeeType.RESTORE, false));
if (isExpired) {
feesAndCredits.addFeeOrCredit(
Fee.create(
domainPrices.getRenewCost().getAmount(), FeeType.RENEW, domainPrices.isPremium()));
}
return customLogic.customizeRestorePrice(
RestorePriceParameters.newBuilder()
.setFeesAndCredits(feesAndCredits.build())
.setRegistry(registry)
.setDomainName(InternetDomainName.from(domainName))
.setAsOfDate(dateTime)
.build());
}
/** Returns a new transfer price for the pricer. */
public FeesAndCredits getTransferPrice(Registry registry, String domainName, DateTime dateTime)
throws EppException {
DomainPrices domainPrices = getPricesForDomainName(domainName, dateTime);
return customLogic.customizeTransferPrice(
TransferPriceParameters.newBuilder()
.setFeesAndCredits(
new FeesAndCredits.Builder()
.setCurrency(registry.getCurrency())
.addFeeOrCredit(
Fee.create(
domainPrices.getRenewCost().getAmount(),
FeeType.RENEW,
domainPrices.isPremium()))
.build())
.setRegistry(registry)
.setDomainName(InternetDomainName.from(domainName))
.setAsOfDate(dateTime)
.build());
}
private static Endpoint create(String host, int port) {
requireNonNull(host, "host");
if (NetUtil.isValidIpV4Address(host)) {
return new Endpoint(host, host, port, DEFAULT_WEIGHT, HostType.IPv4_ONLY);
}
if (NetUtil.isValidIpV6Address(host)) {
final String ipV6Addr;
if (host.charAt(0) == '[') {
// Strip surrounding '[' and ']'.
ipV6Addr = host.substring(1, host.length() - 1);
} else {
ipV6Addr = host;
}
return new Endpoint(ipV6Addr, ipV6Addr, port, DEFAULT_WEIGHT, HostType.IPv6_ONLY);
}
return new Endpoint(InternetDomainName.from(host).toString(),
null, port, DEFAULT_WEIGHT, HostType.HOSTNAME_ONLY);
}
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;
}
/** Returns whether a given domain create request is for a valid anchor tenant. */
public static boolean isAnchorTenant(
InternetDomainName domainName,
Optional<AllocationToken> token,
Optional<MetadataExtension> metadataExtension) {
// If the domain is reserved for anchor tenants, then check if the allocation token exists and
// is for this domain.
if (getReservationTypes(domainName).contains(RESERVED_FOR_ANCHOR_TENANT)
&& token.isPresent()
&& token.get().getDomainName().isPresent()
&& token.get().getDomainName().get().equals(domainName.toString())) {
return true;
}
// Otherwise check whether the metadata extension is being used by a superuser to specify that
// it's an anchor tenant creation.
return metadataExtension.isPresent() && metadataExtension.get().getIsAnchorTenant();
}
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());
}
}
}
}
}
/**
* 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();
}
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());
}
}
}
}
}
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();
}
public static MdId asMdId(InternetDomainName mdName) {
if (mdName == null || mdName.toString().length() < MD_NAME_MIN_LEN ||
mdName.toString().length() > MD_NAME_MAX_LEN) {
throw new IllegalArgumentException("MD Domain Name must be between " +
MD_NAME_MIN_LEN + " and " + MD_NAME_MAX_LEN + " chars long"
+ " Rejecting: " + mdName);
}
return new MdIdDomainName(mdName);
}
public static String getRootDomain(String inputDomain) {
try {
String rootDomain =InternetDomainName.from(inputDomain).topPrivateDomain().toString();
return rootDomain;
}catch(Exception e) {
return null;
}
}
/**
* Helper function for grouping sets of domain names into respective TLDs. Useful for batched
* EPP calls when invoking commands (i.e. domain check) with sets of domains across multiple TLDs.
*/
protected static Multimap<String, String> validateAndGroupDomainNamesByTld(List<String> names) {
ImmutableMultimap.Builder<String, String> builder = new ImmutableMultimap.Builder<>();
for (String name : names) {
InternetDomainName tld = findTldForNameOrThrow(InternetDomainName.from(name));
builder.put(tld.toString(), name);
}
return builder.build();
}
private CookieStore prepareCookieStore(ScreenshotContext screenshotContext) throws MalformedURLException {
List<Cookie> cookies = screenshotContext.urlConfig.cookies;
CookieStore cookieStore = new BasicCookieStore();
//If a cookie is added without a domain, Apache HTTP Client 4.5.5 throws a NullPointerException, so we extract the domain from the URL here
String domain;
if (isUrlLocalHost(screenshotContext.url)) {
domain = ".localhost";
} else {
domain = ".".concat(InternetDomainName.from(new URL(screenshotContext.url).getHost()).topPrivateDomain().toString());
}
if (cookies != null) addCookiesToStore(cookies, cookieStore, domain);
return cookieStore;
}