Example usage for com.google.common.net InternetDomainName parent

List of usage examples for com.google.common.net InternetDomainName parent

Introduction

In this page you can find the example usage for com.google.common.net InternetDomainName parent.

Prototype

public InternetDomainName parent() 

Source Link

Document

Returns an InternetDomainName that is the immediate ancestor of this one; that is, the current domain with the leftmost part removed.

Usage

From source file:google.registry.flows.domain.DomainFlowUtils.java

/**
 * Returns parsed version of {@code name} if domain name label follows our naming rules and is
 * under one of the given allowed TLDs./*from   w  w w .  j av a  2s  . c o  m*/
 *
 * <p><b>Note:</b> This method does not perform language validation with IDN tables.
 *
 * @see #validateDomainNameWithIdnTables(InternetDomainName)
 */
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);
    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;
}

From source file:google.registry.flows.domain.DomainCheckFlow.java

private String getMessageForCheck(InternetDomainName domainName, Set<String> existingIds, DateTime now) {
    if (existingIds.contains(domainName.toString())) {
        return "In use";
    }/*from w  ww .j  a  va 2s .c  om*/
    Registry registry = Registry.get(domainName.parent().toString());
    if (PENDING_ALLOCATION_TLD_STATES.contains(registry.getTldState(now))
            && FluentIterable.from(loadActiveApplicationsByDomainName(domainName.toString(), now))
                    .anyMatch(new Predicate<DomainApplication>() {
                        @Override
                        public boolean apply(DomainApplication input) {
                            return !input.getApplicationStatus().isFinalStatus();
                        }
                    })) {
        return "Pending allocation";
    }
    ReservationType reservationType = getReservationType(domainName);
    if (reservationType == UNRESERVED && isDomainPremium(domainName.toString(), now)
            && registry.getPremiumPriceAckRequired()
            && eppInput.getSingleExtension(FeeCheckCommandExtension.class) == null) {
        return "Premium names require EPP ext.";
    }
    return reservationType.getMessageForCheck();
}

From source file:google.registry.flows.domain.DomainAllocateFlow.java

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(FeeCreateCommandExtension.class, SecDnsCreateExtension.class,
            MetadataExtension.class, AllocateCreateExtension.class);
    extensionManager.validate();/*from   ww w.j  ava  2s  .c  o  m*/
    validateClientIsLoggedIn(clientId);
    verifyIsSuperuser();
    DateTime now = ofy().getTransactionTime();
    Create command = cloneAndLinkReferences((Create) resourceCommand, now);
    failfastForCreate(targetId, now);
    verifyResourceDoesNotExist(DomainResource.class, targetId, now);
    InternetDomainName domainName = validateDomainName(command.getFullyQualifiedDomainName());
    Registry registry = Registry.get(domainName.parent().toString());
    Period period = command.getPeriod();
    Integer years = period.getValue();
    verifyUnitIsYears(period);
    validateCreateCommandContactsAndNameservers(command, registry.getTldStr());
    SecDnsCreateExtension secDnsCreate = validateSecDnsExtension(
            eppInput.getSingleExtension(SecDnsCreateExtension.class));
    boolean isSunrushAddGracePeriod = isNullOrEmpty(command.getNameservers());
    AllocateCreateExtension allocateCreate = eppInput.getSingleExtension(AllocateCreateExtension.class);
    DomainApplication application = loadAndValidateApplication(allocateCreate.getApplicationRoid(), now);
    String repoId = createDomainRepoId(ObjectifyService.allocateId(), registry.getTldStr());
    ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
    HistoryEntry historyEntry = buildHistory(repoId, period, now);
    entitiesToSave.add(historyEntry);
    ImmutableSet<? extends ImmutableObject> billsAndPolls = createBillingEventsAndPollMessages(domainName,
            application, historyEntry, isSunrushAddGracePeriod, registry, now, years);
    entitiesToSave.addAll(billsAndPolls);
    DateTime registrationExpirationTime = leapSafeAddYears(now, years);
    DomainResource newDomain = new DomainResource.Builder().setCreationClientId(clientId)
            .setCurrentSponsorClientId(clientId).setRepoId(repoId)
            .setIdnTableName(validateDomainNameWithIdnTables(domainName))
            .setRegistrationExpirationTime(registrationExpirationTime)
            .setAutorenewBillingEvent(Key.create(getOnly(billsAndPolls, BillingEvent.Recurring.class)))
            .setAutorenewPollMessage(Key.create(getOnly(billsAndPolls, PollMessage.Autorenew.class)))
            .setApplicationTime(allocateCreate.getApplicationTime()).setApplication(Key.create(application))
            .setSmdId(allocateCreate.getSmdId()).setLaunchNotice(allocateCreate.getNotice())
            .setDsData(secDnsCreate == null ? application.getDsData() : secDnsCreate.getDsData())
            .addGracePeriod(createGracePeriod(isSunrushAddGracePeriod,
                    getOnly(billsAndPolls, BillingEvent.OneTime.class)))
            // Names on the collision list will not be delegated. Set server hold.
            .setStatusValues(ReservationType.NAME_COLLISION == getReservationType(domainName)
                    ? ImmutableSet.of(StatusValue.SERVER_HOLD)
                    : ImmutableSet.<StatusValue>of())
            .setRegistrant(command.getRegistrant()).setAuthInfo(command.getAuthInfo())
            .setFullyQualifiedDomainName(targetId).setNameservers(command.getNameservers())
            .setContacts(command.getContacts()).build();
    entitiesToSave.add(newDomain, buildApplicationHistory(application, now), updateApplication(application),
            ForeignKeyIndex.create(newDomain, newDomain.getDeletionTime()),
            EppResourceIndex.create(Key.create(newDomain)));
    // Anchor tenant registrations override LRP.
    String authInfoToken = authInfo.getPw().getValue();
    if (hasLrpToken(domainName, registry, authInfoToken, now)) {
        entitiesToSave.add(prepareMarkedLrpTokenEntity(authInfoToken, domainName, historyEntry));
    }
    ofy().save().entities(entitiesToSave.build());
    enqueueTasks(allocateCreate, newDomain);
    return responseBuilder.setResData(DomainCreateData.create(targetId, now, registrationExpirationTime))
            .setExtensions(createResponseExtensions(now, registry, years)).build();
}

From source file:google.registry.flows.domain.DomainCheckFlow.java

@Override
public EppResponse run() throws EppException {
    extensionManager.register(FeeCheckCommandExtension.class, LaunchCheckExtension.class);
    customLogic.beforeValidation();//w  ww .  j  a  v  a2s.  co m
    extensionManager.validate();
    validateClientIsLoggedIn(clientId);
    List<String> targetIds = ((Check) resourceCommand).getTargetIds();
    verifyTargetIdCount(targetIds, maxChecks);
    DateTime now = clock.nowUtc();
    ImmutableMap.Builder<String, InternetDomainName> domains = new ImmutableMap.Builder<>();
    // Only check that the registrar has access to a TLD the first time it is encountered
    Set<String> seenTlds = new HashSet<>();
    for (String targetId : ImmutableSet.copyOf(targetIds)) {
        InternetDomainName domainName = validateDomainName(targetId);
        validateDomainNameWithIdnTables(domainName);
        // This validation is moderately expensive, so cache the results.
        domains.put(targetId, domainName);
        String tld = domainName.parent().toString();
        if (seenTlds.add(tld)) {
            checkAllowedAccessToTld(clientId, tld);
            if (!isSuperuser) {
                verifyNotInPredelegation(Registry.get(tld), now);
            }
        }
    }
    ImmutableMap<String, InternetDomainName> domainNames = domains.build();
    customLogic.afterValidation(
            DomainCheckFlowCustomLogic.AfterValidationParameters.newBuilder().setDomainNames(domainNames)
                    // TODO: Use as of date from fee extension v0.12 instead of now, if specificed.
                    .setAsOfDate(now).build());
    Set<String> existingIds = checkResourcesExist(DomainResource.class, targetIds, now);
    ImmutableList.Builder<DomainCheck> checks = new ImmutableList.Builder<>();
    for (String targetId : targetIds) {
        String message = getMessageForCheck(domainNames.get(targetId), existingIds, now);
        checks.add(DomainCheck.create(message == null, targetId, message));
    }
    BeforeResponseReturnData responseData = customLogic
            .beforeResponse(BeforeResponseParameters.newBuilder().setDomainChecks(checks.build())
                    .setResponseExtensions(getResponseExtensions(domainNames, now)).setAsOfDate(now).build());
    return responseBuilder.setResData(DomainCheckData.create(responseData.domainChecks()))
            .setExtensions(responseData.responseExtensions()).build();
}

From source file:google.registry.flows.domain.DomainApplicationCreateFlow.java

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(FeeCreateCommandExtension.class, SecDnsCreateExtension.class,
            MetadataExtension.class, LaunchCreateExtension.class);
    customLogic.beforeValidation();//www .ja v a 2  s  .  co m
    extensionManager.validate();
    validateClientIsLoggedIn(clientId);
    DateTime now = ofy().getTransactionTime();
    Create command = cloneAndLinkReferences((Create) resourceCommand, now);
    failfastForCreate(targetId, now);
    // Fail if the domain is already registered (e.g. this is a landrush application but the domain
    // was awarded at the end of sunrise). However, multiple domain applications can be created for
    // the same domain name, so don't try to load an existing application.
    verifyResourceDoesNotExist(DomainResource.class, targetId, now);
    // Validate that this is actually a legal domain name on a TLD that the registrar has access to.
    InternetDomainName domainName = validateDomainName(targetId);
    String idnTableName = validateDomainNameWithIdnTables(domainName);
    String tld = domainName.parent().toString();
    checkAllowedAccessToTld(clientId, tld);
    Registry registry = Registry.get(tld);
    FeesAndCredits feesAndCredits = pricingLogic.getCreatePrice(registry, targetId, now,
            command.getPeriod().getValue());
    // Superusers can create reserved domains, force creations on domains that require a claims
    // notice without specifying a claims key, and override blocks on registering premium domains.
    verifyUnitIsYears(command.getPeriod());
    int years = command.getPeriod().getValue();
    validateCreateCommandContactsAndNameservers(command, tld);
    LaunchCreateExtension launchCreate = eppInput.getSingleExtension(LaunchCreateExtension.class);
    if (launchCreate != null) {
        validateLaunchCreateExtension(launchCreate, registry, domainName, now);
    }
    boolean isAnchorTenant = matchesAnchorTenantReservation(domainName, authInfo.getPw().getValue());
    if (!isSuperuser) {
        verifyPremiumNameIsNotBlocked(targetId, now, clientId);
        prohibitLandrushIfExactlyOneSunrise(registry, now);
        if (!isAnchorTenant) {
            boolean isSunriseApplication = !launchCreate.getSignedMarks().isEmpty();
            verifyNotReserved(domainName, isSunriseApplication);
        }
    }
    FeeCreateCommandExtension feeCreate = eppInput.getSingleExtension(FeeCreateCommandExtension.class);
    validateFeeChallenge(targetId, tld, now, feeCreate, feesAndCredits);
    SecDnsCreateExtension secDnsCreate = validateSecDnsExtension(
            eppInput.getSingleExtension(SecDnsCreateExtension.class));
    customLogic.afterValidation(
            AfterValidationParameters.newBuilder().setDomainName(domainName).setYears(years).build());
    DomainApplication newApplication = new DomainApplication.Builder().setCreationTrid(trid)
            .setCreationClientId(clientId).setCurrentSponsorClientId(clientId)
            .setRepoId(createDomainRepoId(ObjectifyService.allocateId(), tld))
            .setLaunchNotice(launchCreate == null ? null : launchCreate.getNotice())
            .setIdnTableName(idnTableName).setPhase(launchCreate.getPhase()).setPeriod(command.getPeriod())
            .setApplicationStatus(ApplicationStatus.VALIDATED).addStatusValue(StatusValue.PENDING_CREATE)
            .setDsData(secDnsCreate == null ? null : secDnsCreate.getDsData())
            .setRegistrant(command.getRegistrant()).setAuthInfo(command.getAuthInfo())
            .setFullyQualifiedDomainName(targetId).setNameservers(command.getNameservers())
            .setContacts(command.getContacts())
            .setEncodedSignedMarks(FluentIterable.from(launchCreate.getSignedMarks())
                    .transform(new Function<AbstractSignedMark, EncodedSignedMark>() {
                        @Override
                        public EncodedSignedMark apply(AbstractSignedMark abstractSignedMark) {
                            return (EncodedSignedMark) abstractSignedMark;
                        }
                    }).toList())
            .build();
    HistoryEntry historyEntry = buildHistory(newApplication.getRepoId(), command.getPeriod(), now);
    ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
    entitiesToSave.add(newApplication, historyEntry,
            DomainApplicationIndex.createUpdatedInstance(newApplication),
            EppResourceIndex.create(Key.create(newApplication)));
    // Anchor tenant registrations override LRP, and landrush applications can skip it.
    // If a token is passed in outside of an LRP phase, it is simply ignored (i.e. never redeemed).
    if (registry.getLrpPeriod().contains(now) && !isAnchorTenant) {
        entitiesToSave.add(prepareMarkedLrpTokenEntity(authInfo.getPw().getValue(), domainName, historyEntry));
    }
    EntityChanges entityChanges = customLogic
            .beforeSave(DomainApplicationCreateFlowCustomLogic.BeforeSaveParameters.newBuilder()
                    .setNewApplication(newApplication).setHistoryEntry(historyEntry)
                    .setEntityChanges(EntityChanges.newBuilder().setSaves(entitiesToSave.build()).build())
                    .setYears(years).build());
    persistEntityChanges(entityChanges);
    BeforeResponseReturnData responseData = customLogic.beforeResponse(
            BeforeResponseParameters.newBuilder().setResData(DomainCreateData.create(targetId, now, null))
                    .setResponseExtensions(createResponseExtensions(newApplication.getForeignKey(),
                            launchCreate.getPhase(), feeCreate, feesAndCredits))
                    .build());
    return responseBuilder.setResData(responseData.resData()).setExtensions(responseData.responseExtensions())
            .build();
}

From source file:org.archive.modules.fetcher.BdbCookieStore.java

/**
 * Returns a {@link LimitedCookieStoreFacade} whose
 * {@link LimitedCookieStoreFacade#getCookies()} method returns only cookies
 * from {@code host} and its parent domains, if applicable.
 *///from w  ww  .  ja  v  a  2s  .com
public CookieStore cookieStoreFor(String host) {
    CompositeCollection cookieCollection = new CompositeCollection();

    if (InternetDomainName.isValid(host)) {
        InternetDomainName domain = InternetDomainName.from(host);

        while (domain != null) {
            Collection<Cookie> subset = hostSubset(domain.toString());
            cookieCollection.addComposited(subset);

            if (domain.hasParent()) {
                domain = domain.parent();
            } else {
                domain = null;
            }
        }
    } else {
        Collection<Cookie> subset = hostSubset(host.toString());
        cookieCollection.addComposited(subset);
    }

    @SuppressWarnings("unchecked")
    List<Cookie> cookieList = new RestrictedCollectionWrappedList<Cookie>(cookieCollection);
    LimitedCookieStoreFacade store = new LimitedCookieStoreFacade(cookieList);
    return store;
}

From source file:google.registry.flows.domain.DomainCreateFlow.java

@Override
public final EppResponse run() throws EppException {
    extensionManager.register(FeeCreateCommandExtension.class, SecDnsCreateExtension.class,
            MetadataExtension.class, LaunchCreateExtension.class);
    customLogic.beforeValidation();/*  ww  w  .  j av  a 2s  .  co m*/
    extensionManager.validate();
    validateClientIsLoggedIn(clientId);
    DateTime now = ofy().getTransactionTime();
    Create command = cloneAndLinkReferences((Create) resourceCommand, now);
    Period period = command.getPeriod();
    verifyUnitIsYears(period);
    int years = period.getValue();
    failfastForCreate(targetId, now);
    verifyResourceDoesNotExist(DomainResource.class, targetId, now);
    // Validate that this is actually a legal domain name on a TLD that the registrar has access to.
    InternetDomainName domainName = validateDomainName(command.getFullyQualifiedDomainName());
    String domainLabel = domainName.parts().get(0);
    Registry registry = Registry.get(domainName.parent().toString());
    validateCreateCommandContactsAndNameservers(command, registry.getTldStr());
    TldState tldState = registry.getTldState(now);
    boolean isAnchorTenant = isAnchorTenant(domainName);
    LaunchCreateExtension launchCreate = eppInput.getSingleExtension(LaunchCreateExtension.class);
    boolean hasSignedMarks = launchCreate != null && !launchCreate.getSignedMarks().isEmpty();
    boolean hasClaimsNotice = launchCreate != null && launchCreate.getNotice() != null;
    if (launchCreate != null) {
        verifyNoCodeMarks(launchCreate);
        validateLaunchCreateNotice(launchCreate.getNotice(), domainLabel, isSuperuser, now);
    }
    boolean isSunriseCreate = hasSignedMarks && SUNRISE_STATES.contains(tldState);
    // Superusers can create reserved domains, force creations on domains that require a claims
    // notice without specifying a claims key, ignore the registry phase, and override blocks on
    // registering premium domains.
    if (!isSuperuser) {
        checkAllowedAccessToTld(clientId, registry.getTldStr());
        if (launchCreate != null) {
            verifyLaunchPhaseMatchesRegistryPhase(registry, launchCreate, now);
        }
        if (!isAnchorTenant) {
            verifyNotReserved(domainName, isSunriseCreate);
        }
        if (hasClaimsNotice) {
            verifyClaimsPeriodNotEnded(registry, now);
        }
        if (now.isBefore(registry.getClaimsPeriodEnd())) {
            verifyClaimsNoticeIfAndOnlyIfNeeded(domainName, hasSignedMarks, hasClaimsNotice);
        }
        verifyPremiumNameIsNotBlocked(targetId, now, clientId);
        verifyNoOpenApplications(now);
        verifyIsGaOrIsSpecialCase(tldState, isAnchorTenant);
    }
    String signedMarkId = hasSignedMarks
            // If a signed mark was provided, then it must match the desired domain label. Get the mark
            // at this point so that we can verify it before the "after validation" extension point.
            ? tmchUtils.verifySignedMarks(launchCreate.getSignedMarks(), domainLabel, now).getId()
            : null;
    customLogic.afterValidation(
            DomainCreateFlowCustomLogic.AfterValidationParameters.newBuilder().setDomainName(domainName)
                    .setYears(years).setSignedMarkId(Optional.fromNullable(signedMarkId)).build());
    FeeCreateCommandExtension feeCreate = eppInput.getSingleExtension(FeeCreateCommandExtension.class);
    FeesAndCredits feesAndCredits = pricingLogic.getCreatePrice(registry, targetId, now, years);
    validateFeeChallenge(targetId, registry.getTldStr(), now, feeCreate, feesAndCredits);
    SecDnsCreateExtension secDnsCreate = validateSecDnsExtension(
            eppInput.getSingleExtension(SecDnsCreateExtension.class));
    String repoId = createDomainRepoId(ObjectifyService.allocateId(), registry.getTldStr());
    DateTime registrationExpirationTime = leapSafeAddYears(now, years);
    HistoryEntry historyEntry = buildHistory(repoId, period, now);
    // Bill for the create.
    BillingEvent.OneTime createBillingEvent = createOneTimeBillingEvent(registry, isAnchorTenant, years,
            feesAndCredits, historyEntry, now);
    // Create a new autorenew billing event and poll message starting at the expiration time.
    BillingEvent.Recurring autorenewBillingEvent = createAutorenewBillingEvent(historyEntry,
            registrationExpirationTime);
    PollMessage.Autorenew autorenewPollMessage = createAutorenewPollMessage(historyEntry,
            registrationExpirationTime);
    ImmutableSet.Builder<ImmutableObject> entitiesToSave = new ImmutableSet.Builder<>();
    entitiesToSave.add(historyEntry, createBillingEvent, autorenewBillingEvent, autorenewPollMessage);
    // Bill for EAP cost, if any.
    if (!feesAndCredits.getEapCost().isZero()) {
        entitiesToSave.add(createEapBillingEvent(feesAndCredits, createBillingEvent));
    }
    DomainResource newDomain = new DomainResource.Builder().setCreationClientId(clientId)
            .setCurrentSponsorClientId(clientId).setRepoId(repoId)
            .setIdnTableName(validateDomainNameWithIdnTables(domainName))
            .setRegistrationExpirationTime(registrationExpirationTime)
            .setAutorenewBillingEvent(Key.create(autorenewBillingEvent))
            .setAutorenewPollMessage(Key.create(autorenewPollMessage))
            .setLaunchNotice(hasClaimsNotice ? launchCreate.getNotice() : null).setSmdId(signedMarkId)
            .setDsData(secDnsCreate == null ? null : secDnsCreate.getDsData())
            .setRegistrant(command.getRegistrant()).setAuthInfo(command.getAuthInfo())
            .setFullyQualifiedDomainName(targetId).setNameservers(command.getNameservers())
            .setContacts(command.getContacts())
            .addGracePeriod(GracePeriod.forBillingEvent(GracePeriodStatus.ADD, createBillingEvent)).build();
    entitiesToSave.add(newDomain, ForeignKeyIndex.create(newDomain, newDomain.getDeletionTime()),
            EppResourceIndex.create(Key.create(newDomain)));

    // Anchor tenant registrations override LRP, and landrush applications can skip it.
    // If a token is passed in outside of an LRP phase, it is simply ignored (i.e. never redeemed).
    if (isLrpCreate(registry, isAnchorTenant, now)) {
        entitiesToSave.add(prepareMarkedLrpTokenEntity(authInfo.getPw().getValue(), domainName, historyEntry));
    }
    enqueueTasks(isSunriseCreate, hasClaimsNotice, newDomain);

    EntityChanges entityChanges = customLogic.beforeSave(DomainCreateFlowCustomLogic.BeforeSaveParameters
            .newBuilder().setNewDomain(newDomain).setHistoryEntry(historyEntry)
            .setEntityChanges(EntityChanges.newBuilder().setSaves(entitiesToSave.build()).build())
            .setYears(years).build());
    persistEntityChanges(entityChanges);

    BeforeResponseReturnData responseData = customLogic.beforeResponse(BeforeResponseParameters.newBuilder()
            .setResData(DomainCreateData.create(targetId, now, registrationExpirationTime))
            .setResponseExtensions(createResponseExtensions(feeCreate, feesAndCredits)).build());
    return responseBuilder.setResData(responseData.resData()).setExtensions(responseData.responseExtensions())
            .build();
}

From source file:google.registry.flows.domain.DomainFlowUtils.java

/**
 * Validates a {@link FeeQueryCommandExtensionItem} and sets the appropriate fields on a {@link
 * FeeQueryResponseExtensionItem} builder.
 *///from  www  .  jav  a2  s.co  m
static void handleFeeRequest(FeeQueryCommandExtensionItem feeRequest,
        FeeQueryResponseExtensionItem.Builder<?, ?> builder, InternetDomainName domain,
        @Nullable CurrencyUnit topLevelCurrency, DateTime currentDate, DomainPricingLogic pricingLogic)
        throws EppException {
    DateTime now = currentDate;
    // Use the custom effective date specified in the fee check request, if there is one.
    if (feeRequest.getEffectiveDate().isPresent()) {
        now = feeRequest.getEffectiveDate().get();
        builder.setEffectiveDateIfSupported(now);
    }
    String domainNameString = domain.toString();
    Registry registry = Registry.get(domain.parent().toString());
    int years = verifyUnitIsYears(feeRequest.getPeriod()).getValue();
    boolean isSunrise = registry.getTldState(now).equals(TldState.SUNRISE);

    if (feeRequest.getPhase() != null || feeRequest.getSubphase() != null) {
        throw new FeeChecksDontSupportPhasesException();
    }

    CurrencyUnit currency = feeRequest.getCurrency() != null ? feeRequest.getCurrency() : topLevelCurrency;
    if ((currency != null) && !currency.equals(registry.getCurrency())) {
        throw new CurrencyUnitMismatchException();
    }

    builder.setCommand(feeRequest.getCommandName(), feeRequest.getPhase(), feeRequest.getSubphase())
            .setCurrencyIfSupported(registry.getCurrency()).setPeriod(feeRequest.getPeriod())
            .setClass(pricingLogic.getFeeClass(domainNameString, now).orNull());

    ImmutableList<Fee> fees = ImmutableList.of();
    switch (feeRequest.getCommandName()) {
    case CREATE:
        if (isReserved(domain, isSunrise)) { // Don't return a create price for reserved names.
            builder.setClass("reserved"); // Override whatever class we've set above.
            builder.setAvailIfSupported(false);
            builder.setReasonIfSupported("reserved");
        } else {
            builder.setAvailIfSupported(true);
            fees = pricingLogic.getCreatePrice(registry, domainNameString, now, years).getFees();
        }
        break;
    case RENEW:
        builder.setAvailIfSupported(true);
        fees = pricingLogic.getRenewPrice(registry, domainNameString, now, years).getFees();
        break;
    case RESTORE:
        if (years != 1) {
            throw new RestoresAreAlwaysForOneYearException();
        }
        builder.setAvailIfSupported(true);
        fees = pricingLogic.getRestorePrice(registry, domainNameString, now).getFees();
        break;
    case TRANSFER:
        builder.setAvailIfSupported(true);
        fees = pricingLogic.getTransferPrice(registry, domainNameString, now, years).getFees();
        break;
    case UPDATE:
        builder.setAvailIfSupported(true);
        fees = pricingLogic.getUpdatePrice(registry, domainNameString, now).getFees();
        break;
    default:
        throw new UnknownFeeCommandException(feeRequest.getUnparsedCommandName());
    }

    // Set the fees, and based on the validDateRange of the fees, set the notAfterDate.
    if (!fees.isEmpty()) {
        builder.setFees(fees);
        DateTime notAfterDate = null;
        for (Fee fee : fees) {
            if (fee.hasValidDateRange()) {
                DateTime endDate = fee.getValidDateRange().upperEndpoint();
                if (notAfterDate == null || notAfterDate.isAfter(endDate)) {
                    notAfterDate = endDate;
                }
            }
        }
        if (notAfterDate != null && !notAfterDate.equals(END_OF_TIME)) {
            builder.setNotAfterDateIfSupported(notAfterDate);
        }
    }
}

From source file:google.registry.whois.WhoisReader.java

/**
 * Given a WHOIS command string, parse it into its command type and target string. See class level
 * comments for a full description of the command syntax accepted.
 *//*from  ww  w.  j  a  v a  2s.  co m*/
private WhoisCommand parseCommand(String command) throws WhoisException {
    // Split the string into tokens based on whitespace.
    List<String> tokens = filterEmptyStrings(command.split("\\s"));

    if (tokens.isEmpty()) {
        throw new WhoisException(now, SC_BAD_REQUEST, "No WHOIS command specified.");
    }

    final String arg1 = tokens.get(0);

    // Check if the first token is equal to the domain lookup command.
    if (arg1.equalsIgnoreCase(DOMAIN_LOOKUP_COMMAND)) {
        if (tokens.size() != 2) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Wrong number of arguments to '%s' command.", DOMAIN_LOOKUP_COMMAND));
        }

        // Try to parse the argument as a domain name.
        try {
            return new DomainLookupCommand(InternetDomainName.from(canonicalizeDomainName(tokens.get(1))));
        } catch (IllegalArgumentException iae) {
            // If we can't interpret the argument as a host name, then return an error.
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Could not parse argument to '%s' command", DOMAIN_LOOKUP_COMMAND));
        }
    }

    // Check if the first token is equal to the nameserver lookup command.
    if (arg1.equalsIgnoreCase(NAMESERVER_LOOKUP_COMMAND)) {
        if (tokens.size() != 2) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Wrong number of arguments to '%s' command.", NAMESERVER_LOOKUP_COMMAND));
        }

        // Try to parse the argument as an IP address.
        try {
            return new NameserverLookupByIpCommand(InetAddresses.forString(tokens.get(1)));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // Try to parse the argument as a host name.
        try {
            return new NameserverLookupByHostCommand(
                    InternetDomainName.from(canonicalizeDomainName(tokens.get(1))));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // If we can't interpret the argument as either a host name or IP address, return an error.
        throw new WhoisException(now, SC_BAD_REQUEST,
                String.format("Could not parse argument to '%s' command", NAMESERVER_LOOKUP_COMMAND));
    }

    // Check if the first token is equal to the registrar lookup command.
    if (arg1.equalsIgnoreCase(REGISTRAR_LOOKUP_COMMAND)) {
        if (tokens.size() == 1) {
            throw new WhoisException(now, SC_BAD_REQUEST,
                    String.format("Too few arguments to '%s' command.", REGISTRAR_LOOKUP_COMMAND));
        }
        return new RegistrarLookupCommand(Joiner.on(' ').join(tokens.subList(1, tokens.size())));
    }

    // If we have a single token, then try to interpret that in various ways.
    if (tokens.size() == 1) {
        // Try to parse it as an IP address. If successful, then this is a lookup on a nameserver.
        try {
            return new NameserverLookupByIpCommand(InetAddresses.forString(arg1));
        } catch (IllegalArgumentException iae) {
            // Silently ignore this exception.
        }

        // Try to parse it as a domain name or host name.
        try {
            final InternetDomainName targetName = InternetDomainName.from(canonicalizeDomainName(arg1));

            // We don't know at this point whether we have a domain name or a host name. We have to
            // search through our configured TLDs to see if there's one that prefixes the name.
            Optional<InternetDomainName> tld = findTldForName(targetName);
            if (!tld.isPresent()) {
                // This target is not under any configured TLD, so just try it as a registrar name.
                return new RegistrarLookupCommand(arg1);
            }

            // If the target is exactly one level above the TLD, then this is an second level domain
            // (SLD) and we should do a domain lookup on it.
            if (targetName.parent().equals(tld.get())) {
                return new DomainLookupCommand(targetName, tld.get());
            }

            // The target is more than one level above the TLD, so we'll assume it's a nameserver.
            return new NameserverLookupByHostCommand(targetName, tld.get());
        } catch (IllegalArgumentException e) {
            // Silently ignore this exception.
        }

        // Purposefully fall through to code below.
    }

    // The only case left is that there are multiple tokens with no particular command given. We'll
    // assume this is a registrar lookup, since there's really nothing else it could be.
    return new RegistrarLookupCommand(Joiner.on(' ').join(tokens));
}

From source file:org.apache.commons.httpclient.cookie.CookieSpecBase.java

/**
 * Return an array of {@link Cookie}s that should be submitted with a
 * request with given attributes, <tt>false</tt> otherwise. 
 * /*ww  w  . j ava2 s.c o  m*/
 * If the SortedMap comes from an HttpState and is not itself
 * thread-safe, it may be necessary to synchronize on the HttpState
 * instance to protect against concurrent modification. 
 *
 * @param host the host to which the request is being submitted
 * @param port the port to which the request is being submitted (currently
 * ignored)
 * @param path the path to which the request is being submitted
 * @param secure <tt>true</tt> if the request is using a secure protocol
 * @param cookies SortedMap of <tt>Cookie</tt>s to be matched
 * @return an array of <tt>Cookie</tt>s matching the criterium
 */
@Override
public Cookie[] match(String host, int port, String path, boolean secure,
        final SortedMap<String, Cookie> cookies) {

    LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, SortedMap)");

    if (cookies == null) {
        return null;
    }
    List<Cookie> matching = new LinkedList<Cookie>();
    InternetDomainName domain;
    try {
        domain = InternetDomainName.fromLenient(host);
    } catch (IllegalArgumentException e) {
        domain = null;
    }

    String candidate = (domain != null) ? domain.name() : host;
    while (candidate != null) {
        Iterator<Cookie> iter = cookies.subMap(candidate, candidate + Cookie.DOMAIN_OVERBOUNDS).values()
                .iterator();
        while (iter.hasNext()) {
            Cookie cookie = (Cookie) (iter.next());
            if (match(host, port, path, secure, cookie)) {
                addInPathOrder(matching, cookie);
            }
        }
        StoredIterator.close(iter);
        if (domain != null && domain.isUnderPublicSuffix()) {
            domain = domain.parent();
            candidate = domain.name();
        } else {
            candidate = null;
        }
    }

    return (Cookie[]) matching.toArray(new Cookie[matching.size()]);
}