com.google.common.net.InternetDomainName Java Examples

The following examples show how to use com.google.common.net.InternetDomainName. 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: AllocationTokenFlowUtilsTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
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: DomainFlowUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example #5
Source File: NetworkFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #6
Source File: NetworkFunctions.java    From metron with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #7
Source File: Endpoint.java    From armeria with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #8
Source File: DomainPricingLogic.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** 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());
}
 
Example #9
Source File: DomainPricingLogic.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** 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());
}
 
Example #10
Source File: DomainPricingLogic.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** 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());
}
 
Example #11
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 #12
Source File: GuavaDeserializers.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #13
Source File: DomainCheckFlow.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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)));
}
 
Example #14
Source File: DomainLabelEntry.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #15
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 #16
Source File: DomainNameUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #17
Source File: CreateAnchorTenantCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #18
Source File: RegistriesTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #19
Source File: AllocationTokenFlowUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
  }
}
 
Example #20
Source File: DomainRestoreRequestFlow.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #21
Source File: GuavaDeserializers.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@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;
    }
 
Example #22
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 #23
Source File: CheckApiAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private Optional<String> checkReserved(InternetDomainName domainName) {
  ImmutableSet<ReservationType> reservationTypes =
      getReservationTypes(domainName.parts().get(0), domainName.parent().toString());
  if (!reservationTypes.isEmpty()) {
    return Optional.of(getTypeOfHighestSeverity(reservationTypes).getMessageForCheck());
  }
  return Optional.empty();
}
 
Example #24
Source File: DomainCheckFlow.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Loads and returns all existing domains that are having restore fees checked.
 *
 * <p>This is necessary so that we can check their expiration dates to determine if a one-year
 * renewal is part of the cost of a restore.
 *
 * <p>This may be resource-intensive for large checks of many restore fees, but those are
 * comparatively rare, and we are at least using an in-memory cache. Also this will get a lot
 * nicer in Cloud SQL when we can SELECT just the fields we want rather than having to load the
 * entire entity.
 */
private ImmutableMap<String, EppResource> loadDomainsForRestoreChecks(
    FeeCheckCommandExtension<?, ?> feeCheck,
    ImmutableMap<String, InternetDomainName> domainNames,
    ImmutableMap<String, ForeignKeyIndex<DomainBase>> existingDomains) {
  ImmutableList<String> restoreCheckDomains;
  if (feeCheck instanceof FeeCheckCommandExtensionV06) {
    // The V06 fee extension supports specifying the command fees to check on a per-domain basis.
    restoreCheckDomains =
        feeCheck.getItems().stream()
            .filter(fc -> fc.getCommandName() == CommandName.RESTORE)
            .map(FeeCheckCommandExtensionItem::getDomainName)
            .collect(toImmutableList());
  } else if (feeCheck.getItems().stream()
      .anyMatch(fc -> fc.getCommandName() == CommandName.RESTORE)) {
    // The more recent fee extension versions support specifying the command fees to check only on
    // the overall domain check, not per-domain.
    restoreCheckDomains = ImmutableList.copyOf(domainNames.keySet());
  } else {
    // Fall-through case for more recent fee extension versions when the restore fee isn't being
    // checked.
    restoreCheckDomains = ImmutableList.of();
  }

  // Filter down to just domains we know exist and then use the EppResource cache to load them.
  ImmutableMap<String, VKey<DomainBase>> existingDomainsToLoad =
      restoreCheckDomains.stream()
          .filter(existingDomains::containsKey)
          .collect(toImmutableMap(d -> d, d -> existingDomains.get(d).getResourceKey()));
  ImmutableMap<VKey<? extends EppResource>, EppResource> loadedDomains =
      EppResource.loadCached(ImmutableList.copyOf(existingDomainsToLoad.values()));
  return ImmutableMap.copyOf(
      Maps.transformEntries(existingDomainsToLoad, (k, v) -> loadedDomains.get(v)));
}
 
Example #25
Source File: StaticPremiumListPricingEngine.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Override
public DomainPrices getDomainPrices(String fullyQualifiedDomainName, DateTime priceTime) {
  String tld = getTldFromDomainName(fullyQualifiedDomainName);
  String label = InternetDomainName.from(fullyQualifiedDomainName).parts().get(0);
  Registry registry = Registry.get(checkNotNull(tld, "tld"));
  Optional<Money> premiumPrice = getPremiumPrice(label, registry);
  return DomainPrices.create(
      premiumPrice.isPresent(),
      premiumPrice.orElse(registry.getStandardCreateCost()),
      premiumPrice.orElse(registry.getStandardRenewCost(priceTime)));
}
 
Example #26
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Returns name of first matching IDN table for domain label.
 *
 * @throws InvalidIdnDomainLabelException if IDN table or language validation failed
 * @see #validateDomainName(String)
 */
public static String validateDomainNameWithIdnTables(InternetDomainName domainName)
    throws InvalidIdnDomainLabelException {
  Optional<String> idnTableName =
      IDN_LABEL_VALIDATOR.findValidIdnTableForTld(
          domainName.parts().get(0), domainName.parent().toString());
  if (!idnTableName.isPresent()) {
    throw new InvalidIdnDomainLabelException();
  }
  return idnTableName.get();
}
 
Example #27
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Returns whether a given domain create request is for a valid reserved domain. */
public static boolean isValidReservedCreate(
    InternetDomainName domainName, Optional<AllocationToken> token) {
  // If the domain is reserved for specific use, then check if the allocation token exists and
  // is for this domain.
  return getReservationTypes(domainName).contains(RESERVED_FOR_SPECIFIC_USE)
      && token.isPresent()
      && token.get().getDomainName().isPresent()
      && token.get().getDomainName().get().equals(domainName.toString());
}
 
Example #28
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static void validateNameserversCountForTld(String tld, InternetDomainName domainName, int count)
    throws EppException {
  // For TLDs with a nameserver allow list, all domains must have at least 1 nameserver.
  ImmutableSet<String> tldNameserversAllowList =
      Registry.get(tld).getAllowedFullyQualifiedHostNames();
  if (!tldNameserversAllowList.isEmpty() && count == 0) {
    throw new NameserversNotSpecifiedForTldWithNameserverAllowListException(
        domainName.toString());
  }
  if (count > MAX_NAMESERVERS_PER_DOMAIN) {
    throw new TooManyNameserversException(
        String.format("Only %d nameservers are allowed per domain", MAX_NAMESERVERS_PER_DOMAIN));
  }
}
 
Example #29
Source File: AllocationTokenFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Loads an allocation token given a string and verifies that the token is valid for the domain
 * create request.
 *
 * @return the loaded {@link AllocationToken} for that string.
 * @throws EppException if the token doesn't exist, is already redeemed, or is otherwise invalid
 *     for this request.
 */
public AllocationToken loadTokenAndValidateDomainCreate(
    DomainCommand.Create command, String token, Registry registry, String clientId, DateTime now)
    throws EppException {
  AllocationToken tokenEntity = loadToken(token);
  validateToken(
      InternetDomainName.from(command.getFullyQualifiedDomainName()), tokenEntity, clientId, now);
  return tokenCustomLogic.validateToken(command, tokenEntity, registry, clientId, now);
}
 
Example #30
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();
}