Example usage for com.amazonaws.services.route53.model HostedZone getName

List of usage examples for com.amazonaws.services.route53.model HostedZone getName

Introduction

In this page you can find the example usage for com.amazonaws.services.route53.model HostedZone getName.

Prototype


public String getName() 

Source Link

Document

The name of the domain.

Usage

From source file:br.com.ingenieux.mojo.beanstalk.cmd.dns.BindDomainsCommand.java

License:Apache License

@Override
protected Void executeInternal(BindDomainsContext ctx) throws Exception {
    Map<String, String> recordsToAssign = new LinkedHashMap<String, String>();

    ctx.singleInstance = isSingleInstance(ctx.getCurEnv());

    /**//from   w w  w.  j  a  va2s  .  c o  m
     * Step #2: Validate Parameters
     */
    {
        for (String domain : ctx.getDomains()) {
            String key = formatDomain(domain);
            String value = null;

            /*
                         * Handle Entries in the form <record>:<zoneid>
             */
            if (-1 != key.indexOf(':')) {
                String[] pair = key.split(":", 2);

                key = formatDomain(pair[0]);
                value = strip(pair[1], ".");
            }

            recordsToAssign.put(key, value);
        }

        Validate.isTrue(recordsToAssign.size() > 0, "No Domains Supplied!");

        if (isInfoEnabled()) {
            info("Domains to Map to Environment (cnamePrefix='%s')", ctx.getCurEnv().getCNAME());

            for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) {
                String key = entry.getKey();
                String zoneId = entry.getValue();

                String message = format(" * Domain: %s", key);

                if (null != zoneId) {
                    message += " (and using zoneId " + zoneId + ")";
                }

                info(message);
            }
        }
    }

    /**
     * Step #3: Lookup Domains on Route53
     */
    Map<String, HostedZone> hostedZoneMapping = new LinkedHashMap<String, HostedZone>();

    {
        Set<String> unresolvedDomains = new LinkedHashSet<String>();

        for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) {
            if (null != entry.getValue()) {
                continue;
            }

            unresolvedDomains.add(entry.getKey());
        }

        for (HostedZone hostedZone : r53.listHostedZones().getHostedZones()) {
            String id = hostedZone.getId();
            String name = hostedZone.getName();

            hostedZoneMapping.put(id, hostedZone);

            if (unresolvedDomains.contains(name)) {
                if (isInfoEnabled()) {
                    info("Mapping Domain %s to R53 Zone Id %s", name, id);
                }

                recordsToAssign.put(name, id);

                unresolvedDomains.remove(name);
            }
        }

        Validate.isTrue(unresolvedDomains.isEmpty(), "Domains not resolved: " + join(unresolvedDomains, "; "));
    }

    /**
     * Step #4: Domain Validation
     */
    {
        for (Map.Entry<String, String> entry : recordsToAssign.entrySet()) {
            String record = entry.getKey();
            String zoneId = entry.getValue();
            HostedZone hostedZone = hostedZoneMapping.get(zoneId);

            Validate.notNull(hostedZone, format("Unknown Hosted Zone Id: %s for Record: %s", zoneId, record));
            Validate.isTrue(record.endsWith(hostedZone.getName()), format(
                    "Record %s does not map to zoneId %s (domain: %s)", record, zoneId, hostedZone.getName()));
        }
    }

    /**
     * Step #5: Get ELB Hosted Zone Id - if appliable
     */
    if (!ctx.singleInstance) {
        String loadBalancerName = parentMojo.getService()
                .describeEnvironmentResources(new DescribeEnvironmentResourcesRequest()
                        .withEnvironmentId(ctx.getCurEnv().getEnvironmentId()))
                .getEnvironmentResources().getLoadBalancers().get(0).getName();

        DescribeLoadBalancersRequest req = new DescribeLoadBalancersRequest(asList(loadBalancerName));

        List<LoadBalancerDescription> loadBalancers = elb.describeLoadBalancers(req)
                .getLoadBalancerDescriptions();

        Validate.isTrue(1 == loadBalancers.size(), "Unexpected number of Load Balancers returned");

        ctx.elbHostedZoneId = loadBalancers.get(0).getCanonicalHostedZoneNameID();

        if (isInfoEnabled()) {
            info(format("Using ELB Canonical Hosted Zone Name Id %s", ctx.elbHostedZoneId));
        }
    }

    /**
     * Step #6: Apply Change Batch on Each Domain
     */
    for (Map.Entry<String, String> recordEntry : recordsToAssign.entrySet()) {
        assignDomain(ctx, recordEntry.getKey(), recordEntry.getValue());
    }

    return null;
}

From source file:com.carrotgarden.maven.aws.dns.CarrotRoute53.java

License:BSD License

public HostedZone findZone(final String source) {

    final ListHostedZonesResult zoneResult = amazonClient.listHostedZones();

    final List<HostedZone> zoneList = zoneResult.getHostedZones();

    for (final HostedZone zone : zoneList) {

        final String name = zone.getName();

        if (source.endsWith(name)) {
            return zone;
        }//ww  w .ja  v a  2  s . co m

    }

    return null;

}

From source file:com.carrotgarden.maven.aws.dns.NameServFindZone.java

License:BSD License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    try {/*w  ww.ja  va 2  s.  c om*/

        getLog().info("dns find init [" + dnsHostName + "]");

        final CarrotRoute53 route53 = newRoute53();

        final HostedZone zone = route53.findZone( //
                route53.canonical(dnsHostName));

        final Properties props = project().getProperties();

        final String zoneName;

        if (zone == null) {
            zoneName = null;
            props.remove(dnsResultProperty);
        } else {
            zoneName = zone.getName();
            props.put(dnsResultProperty, zoneName);
        }

        getLog().info("dns zone name : " + zoneName);

        getLog().info("dns find done [" + dnsHostName + "]");

    } catch (final Exception e) {

        throw new MojoFailureException("bada-boom", e);

    }

}

From source file:com.deploymentio.ec2namer.helpers.DnsRegistrar.java

License:Apache License

@Override
public boolean validate(NamerRequest req, LambdaContext context) {

    if (StringUtils.isEmpty(req.getBaseDomain())) {
        context.log("BaseDomain is missing");
        return false;
    }/*from  w  w  w. jav a  2 s .c  o  m*/

    if (StringUtils.isEmpty(req.getEnvironment())) {
        context.log("Environment is missing");
        return false;
    }

    if (StringUtils.isEmpty(req.getGroup())) {
        context.log("Group is missing");
        return false;
    }

    if (StringUtils.isEmpty(req.getInstanceId())) {
        context.log("InstanceId is missing");
        return false;
    }

    ListHostedZonesResult result = route53.listHostedZones();
    String lookingFor = req.getBaseDomain() + ".";
    for (HostedZone zone : result.getHostedZones()) {
        if (lookingFor.equals(zone.getName())) {
            context.put("hosted-zone", zone.getId());
            context.log("Found hosted-zone: Id=" + zone.getId() + " Name=" + zone.getName());
            return true;
        }
    }

    context.log("HostedZone is not found: BaseDomain=" + req.getBaseDomain());
    return false;
}

From source file:com.github.blacklocus.rdsecho.EchoPromote.java

License:Open Source License

@Override
boolean traverseStage(DBInstance instance) {

    LOG.info("Reading current DNS records");
    String tld = EchoUtil.getTLD(cfg.promoteCname()) + '.';
    HostedZone hostedZone = route53Find.hostedZone(nameEquals(tld)).get();
    LOG.info("  Found corresponding HostedZone. name: {} id: {}", hostedZone.getName(), hostedZone.getId());

    ResourceRecordSet resourceRecordSet = route53Find
            .resourceRecordSet(hostedZone.getId(), cnameEquals(cfg.promoteCname())).get();
    ResourceRecord resourceRecord = getOnlyElement(resourceRecordSet.getResourceRecords());
    LOG.info("  Found CNAME {} with current value {}", resourceRecordSet.getName(), resourceRecord.getValue());

    Endpoint endpoint = instance.getEndpoint();
    String tagEchoManaged = echo.getTagEchoManaged();
    String dbInstanceId = instance.getDBInstanceIdentifier();
    if (null == endpoint) {
        LOG.info("Echo DB instance {} (id: {}) has no address. Is it still initializing?", tagEchoManaged,
                dbInstanceId);/*from  w w w .  j ava 2s  .c o  m*/
        return false;
    }
    String instanceAddr = endpoint.getAddress();
    if (resourceRecord.getValue().equals(instanceAddr)) {
        LOG.info("  Echo DB instance {} ({}) lines up with CNAME {}. Nothing to do.", tagEchoManaged,
                instanceAddr, resourceRecordSet.getName());
        return false;
    } else {
        LOG.info("  Echo DB instance {} ({}) differs from CNAME {}.", tagEchoManaged, instanceAddr,
                resourceRecordSet.getName());
    }

    if (cfg.interactive()) {
        String format = "Are you sure you want to promote %s to be the new target of %s? Input %s to confirm.";
        if (!EchoUtil.prompt(dbInstanceId, format, dbInstanceId, cfg.promoteCname(), dbInstanceId)) {
            LOG.info("User declined to proceed. Exiting.");
            return false;
        }
    }

    LOG.info("Updating CNAME {} from {} to {}", cfg.name(), resourceRecord.getValue(), instanceAddr);
    ChangeResourceRecordSetsRequest request = new ChangeResourceRecordSetsRequest()
            .withHostedZoneId(hostedZone.getId())
            .withChangeBatch(new ChangeBatch().withChanges(
                    new Change(ChangeAction.UPSERT, new ResourceRecordSet(cfg.promoteCname(), RRType.CNAME)
                            .withResourceRecords(new ResourceRecord(instanceAddr)).withTTL(cfg.promoteTtl()))));
    route53.changeResourceRecordSets(request);

    Optional<String[]> promoteTags = cfg.promoteTags();
    if (promoteTags.isPresent()) {
        List<Tag> tags = EchoUtil.parseTags(promoteTags.get());
        if (tags.size() > 0) {
            LOG.info("Applying tags on promote: {}", Arrays.asList(tags));
            AddTagsToResourceRequest tagsRequest = new AddTagsToResourceRequest().withResourceName(
                    RdsFind.instanceArn(cfg.region(), cfg.accountNumber(), instance.getDBInstanceIdentifier()));
            tagsRequest.setTags(tags);
            rds.addTagsToResource(tagsRequest);
        }
    }

    LOG.info("Searching for any existing promoted instance to demote.");

    return true;
}

From source file:com.github.blacklocus.rdsecho.utl.Route53Find.java

License:Open Source License

public static Predicate<HostedZone> nameEquals(final String name) {
    return new Predicate<HostedZone>() {
        @Override//from w  w w.j a v a  2  s  .  c  o  m
        public boolean apply(HostedZone hostedZone) {
            return hostedZone.getName().equals(name);
        }
    };
}

From source file:com.msi.dns53.client.DNS53MetadataUtil.java

License:Apache License

public void populateServiceMetadata(final ServletConfig config, String serviceName) {
    logger.debug("init(): TXT record will be created for this service regarding its port and context path.");
    String contextPath = config.getServletContext().getContextPath();
    String port = Appctx.getBean("TOMCAT_PORT");
    String master_passwd = Appctx.getBean("DB_PASSWORD");

    final String fqdn = (String) ConfigurationUtil.getConfiguration(Arrays.asList(new String[] { "FQDN" }));
    final String domain = (String) ConfigurationUtil
            .getConfiguration(Arrays.asList(new String[] { "FQDN_DOMAIN" }));
    String txtRecordValue = ":" + port + contextPath;
    String baseDNSServerURL = "http://localhost:" + port + "/DNS53Server/2012-02-29/";

    logger.debug("Tomcat port = " + port + "; FQDN = " + fqdn + "; domain = " + domain + "; TXT Record Value = "
            + txtRecordValue + "; BaseDNSServerUrl = " + baseDNSServerURL);

    DNS53Client client = new DNS53Client(baseDNSServerURL + "hostedzone", baseDNSServerURL + "change", "admin",
            master_passwd);/*from   w  w  w  .  ja va2  s  .c  o m*/

    logger.debug("Service name = " + serviceName);
    String recordName = serviceName + "-" + fqdn;
    logger.debug("TXT Record Name: " + recordName);

    logger.debug("init(): Calling ListHostedZones to find the target zone!");
    ListHostedZonesRequest lhzReq = new ListHostedZonesRequest();
    lhzReq.setMaxItems("1");

    ListHostedZonesResult lhzResult = client.listHostedZones(lhzReq);

    HostedZone zone = null;
    List<HostedZone> zones = lhzResult.getHostedZones();
    if (zones != null && zones.size() > 0) {
        for (HostedZone hz : zones) {
            if (hz.getName().equals(domain + ".") || hz.getName().equals(domain)) {
                zone = hz;
            }
        }
    } else {
        logger.error(
                "BaseAsyncServlet encountered an error while it was trying to find the target hosted zone.");
        throw ErrorResponse.InternalFailure();
    }

    if (zone == null) {
        logger.error("BaseAsyncServlet could not find any zone for this TopStackWeb instance.");
        throw ErrorResponse.InternalFailure();
    }

    // TODO (optional) check for the CNAME record for this service before proceeding

    logger.debug("init(): Creating a new TXT record for " + recordName + " with \"" + txtRecordValue
            + "\" as its value!");
    String zoneId = zone.getId();
    ChangeResourceRecordSetsRequest crrsReq = new ChangeResourceRecordSetsRequest();
    crrsReq.setHostedZoneId(zoneId);
    ChangeBatch cb = new ChangeBatch();
    cb.setComment(
            "BaseAsyncServlet => init(): Registering " + serviceName + " service for Transcend TopStack.");
    Collection<Change> changes = new LinkedList<Change>();
    Change change = new Change();
    change.setAction(ChangeAction.CREATE);
    ResourceRecordSet rrSet = new ResourceRecordSet();
    rrSet.setName(recordName);
    rrSet.setTTL(900L);
    rrSet.setType(RRType.TXT);
    Collection<ResourceRecord> rr = new LinkedList<ResourceRecord>();
    ResourceRecord record = new ResourceRecord();
    record.setValue(txtRecordValue);
    rr.add(record);
    rrSet.setResourceRecords(rr);
    change.setResourceRecordSet(rrSet);
    changes.add(change);
    cb.setChanges(changes);
    crrsReq.setChangeBatch(cb);
    ChangeResourceRecordSetsResult result = client.changeResourceRecordSets(crrsReq);
    logger.debug("Result for the last ChangeResourceRecordSets request: " + result.toString());
}

From source file:com.msi.dns53.util.DNS53QueryUtil.java

License:Apache License

public static void marshallHostedZone(HostedZone hostedZone, XMLNode response) {
    XMLNode hz = QueryUtil.addNode(response, DNS53Constants.HOSTEDZONE);
    QueryUtil.addNode(hz, DNS53Constants.ID, hostedZone.getId());
    QueryUtil.addNode(hz, DNS53Constants.NAME, hostedZone.getName());
    QueryUtil.addNode(hz, DNS53Constants.CALLERREFERENCE, hostedZone.getCallerReference());
    if (hostedZone.getConfig() != null) {
        XMLNode config = QueryUtil.addNode(hz, DNS53Constants.CONFIG);
        QueryUtil.addNode(config, DNS53Constants.COMMENT, hostedZone.getConfig().getComment());
    }//from  w w w  .  ja  v  a 2 s  . co m
    QueryUtil.addNode(hz, DNS53Constants.RESOURCERECORDSETCOUNT, hostedZone.getResourceRecordSetCount());
}

From source file:com.oneops.inductor.AbstractOrderExecutor.java

License:Apache License

/**
 * Gets dns servers//from  www  . j  a  v a 2s .c o  m
 *
 * @param awsCredentials AWSCredentials
 * @param zoneDomainName zoneDomainName
 * @return dns servers
 */
private List<String> getAuthoritativeServersWithAwsCreds(AWSCredentials awsCredentials, String zoneDomainName) {

    if (!zoneDomainName.endsWith(".")) {
        zoneDomainName += ".";
    }

    AmazonRoute53 route53 = new AmazonRoute53Client(awsCredentials);
    ListHostedZonesResult result = route53.listHostedZones();
    List<HostedZone> zones = result.getHostedZones();
    List<String> dnsServers = new ArrayList<String>();
    for (int i = 0; i < zones.size(); i++) {
        HostedZone hostedZone = zones.get(i);
        logger.info("zone: " + hostedZone.getName());
        if (hostedZone.getName().equalsIgnoreCase(zoneDomainName)) {
            logger.info("matched zone");
            GetHostedZoneResult zone = route53.getHostedZone(
                    new GetHostedZoneRequest().withId(hostedZone.getId().replace("/hostedzone/", "")));
            DelegationSet delegationSet = zone.getDelegationSet();
            dnsServers = delegationSet.getNameServers();
            break;
        }
    }
    logger.info("dnsServer: " + dnsServers.toString());
    return dnsServers;
}

From source file:io.kodokojo.service.aws.Route53DnsManager.java

License:Open Source License

private HostedZone getHostedZone() {
    ListHostedZonesByNameRequest listHostedZonesByNameRequest = new ListHostedZonesByNameRequest();
    listHostedZonesByNameRequest.setDNSName(domainName);
    ListHostedZonesByNameResult result = client.listHostedZonesByName(listHostedZonesByNameRequest);

    Iterator<HostedZone> iterator = result.getHostedZones().iterator();
    HostedZone hostedZone = null;//  w ww.  j  a v a2  s  . c o m
    while (hostedZone == null && iterator.hasNext()) {
        HostedZone currentZone = iterator.next();
        hostedZone = currentZone.getName().equals(domainName) ? currentZone : null;
    }
    return hostedZone;
}