Example usage for com.amazonaws.services.rds.model Endpoint getAddress

List of usage examples for com.amazonaws.services.rds.model Endpoint getAddress

Introduction

In this page you can find the example usage for com.amazonaws.services.rds.model Endpoint getAddress.

Prototype


public String getAddress() 

Source Link

Document

Specifies the DNS address of the DB instance.

Usage

From source file:beanstalk.BeansDatabase.java

License:Apache License

public String getDBEndpoint(String AWSKeyId, String AWSSecretKey, String dbname) {//throws Exception {

    String endpoint_str = "";
    BasicAWSCredentials basic_credentials = new BasicAWSCredentials(AWSKeyId, AWSSecretKey);

    AmazonRDSClient rDSClient = new AmazonRDSClient(basic_credentials);

    ModifyDBInstanceRequest mod_db = new ModifyDBInstanceRequest(dbname + "cloud4soaid");
    DBInstance dbInstance = new DBInstance();
    ////CHECK THIS. in order to make correct ModifyDBInstanceRequest an attribute must be sent for modification.
    ///5 (GB) is the minimum
    mod_db.setAllocatedStorage(6);/*from ww  w. j  av a2  s . com*/

    dbInstance = rDSClient.modifyDBInstance(mod_db);
    Endpoint endpoint = new Endpoint();
    endpoint = dbInstance.getEndpoint();
    if (endpoint != null) {
        endpoint_str = endpoint.getAddress();
        System.out.println("endpoint to string:" + endpoint_str);/////{Address: cloud4soadbid.coaodqyxxykq.us-east-1.rds.amazonaws.com, Port: 3306, }
        System.out.println("endpoint get address:" + endpoint.getAddress());/////cloud4soadbid.coaodqyxxykq.us-east-1.rds.amazonaws.com
    }

    return endpoint_str;
}

From source file:com.amazon.aws.myyoutube.videoUtil.GetRDSInstance.java

License:Open Source License

public static void main(String[] args) throws Exception {

    credentials = new PropertiesCredentials(
            GetRDSInstance.class.getResourceAsStream("AwsCredentials.properties"));

    try {/*from   w w w .j  a v  a2  s .  co m*/
        rds = new AmazonRDSClient(credentials);

        /*********************************************
         *  RDS DB
         *********************************************/

        System.out.println("Creating a database instance");

        CreateDBSecurityGroupRequest d = new CreateDBSecurityGroupRequest()
                .withDBSecurityGroupName("javaSecurityGroup1")
                .withDBSecurityGroupDescription("DB security group1");
        rds.createDBSecurityGroup(d);

        AuthorizeDBSecurityGroupIngressRequest auth = new AuthorizeDBSecurityGroupIngressRequest()
                .withDBSecurityGroupName("javaSecurityGroup1")
                //         .withEC2SecurityGroupName("javaSecurityGroup")
                .withCIDRIP("0.0.0.0/0");
        //         .withCIDRIP("216.165.95.69/32");

        DBSecurityGroup dbsecuritygroup = rds.authorizeDBSecurityGroupIngress(auth);
        String[] dBSecurityGroups = { dbsecuritygroup.getDBSecurityGroupName() };

        CreateDBInstanceRequest createDBInstanceRequest = new CreateDBInstanceRequest().withEngine("MySQL")
                .withLicenseModel("general-public-license").withEngineVersion("5.6.13")
                .withDBInstanceClass("db.t1.micro").withMultiAZ(false).withAutoMinorVersionUpgrade(true)
                .withAllocatedStorage(5).withDBInstanceIdentifier("mydbinstance1").withMasterUsername("awsuser")
                .withMasterUserPassword("mypassword").withDBName("dbname1").withPort(3306)
                .withAvailabilityZone(null).withDBSecurityGroups(dBSecurityGroups);

        ArrayList<String> arrDbSecur = new ArrayList<String>();
        arrDbSecur.add("javaSecurityGroup1");
        createDBInstanceRequest.setDBSecurityGroups(arrDbSecur);

        DBInstance dbInstance = rds.createDBInstance(createDBInstanceRequest);

        Thread.sleep(600000);

        DescribeDBInstancesRequest instRequest = new DescribeDBInstancesRequest()
                .withDBInstanceIdentifier("mydbinstance1");

        DescribeDBInstancesResult instres = rds.describeDBInstances(instRequest);

        Endpoint e = instres.getDBInstances().get(0).getEndpoint();
        System.out.println("ENd point " + e.getAddress() + " " + e.getPort());
        System.out.println("Database Created");
        System.out.println("Creating a table");
        //connection
        java.sql.Connection con = null;
        Statement st = null;
        // Format "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password;
        String url = "jdbc:mysql://" + e.getAddress() + ":" + e.getPort()
                + "/dbname1?user=awsuser&password=mypassword"; //  "jdbc:mysql://master:password@"+e+"/dbname";
        System.out.println("Url is " + url);
        String user = "awsuser";
        String password = "mypassword";

        con = DriverManager.getConnection(url, user, password);

        System.out.println("Connection created");

        java.sql.Statement stat = con.createStatement();

        String query = "CREATE TABLE Items ( item_id VARCHAR(200), type INTEGER, quantity INTEGER, user VARCHAR(100), price FLOAT(5,2) );";
        stat.execute(query);

        String query1 = "CREATE TABLE WishList ( user VARCHAR(200), wishlistId VARCHAR(100) );";
        stat.execute(query1);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Response Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
}

From source file:com.amediamanager.dao.RdsDriverManagerDataSource.java

License:Apache License

private void initializeDataSource() {
    // Use the RDS DB and the dbEndpointRetriever to discover the URL of the
    // database. If there
    // are read replicas, set the correct driver and use them.
    final String masterId = config.getProperty(ConfigurationSettings.ConfigProps.RDS_INSTANCEID);

    try {/*w w w .j a  va 2 s .co m*/
        Endpoint master = dbEndpointRetriever.getMasterDbEndpoint(masterId);
        List<Endpoint> replicas = dbEndpointRetriever.getReadReplicaEndpoints(masterId);

        if (master != null) {
            LOG.info("Detected RDS Master database");
            StringBuilder builder = new StringBuilder();
            builder.append("jdbc:mysql:");
            if (replicas != null) {
                builder.append("replication:");
                super.setDriverClassName("com.mysql.jdbc.ReplicationDriver");
            } else {
                super.setDriverClassName("com.mysql.jdbc.Driver");
            }

            builder.append("//" + master.getAddress() + ":" + master.getPort());
            if (replicas != null) {
                LOG.info("Detected RDS Read Replicas");
                for (Endpoint endpoint : replicas) {
                    builder.append("," + endpoint.getAddress() + ":" + endpoint.getPort());
                }
            } else {
                LOG.info("No Read Replicas detected");
            }
            builder.append("/" + config.getProperty(ConfigurationSettings.ConfigProps.RDS_DATABASE));
            String connectionString = builder.toString();
            LOG.info("MySQL Connection String: " + connectionString);
            super.setUrl(connectionString);
        } else {
            LOG.warn("No RDS master database detected!");
        }
    } catch (Exception e) {
        LOG.warn("Failed to initialize datasource.", e);
    }
}

From source file:com.cloudera.director.aws.rds.RDSInstance.java

License:Apache License

/**
 * Returns the private IP address of the specified RDS instance.
 *
 * @param dbInstance the RDS instance/*  w w w .  ja v a2 s .  c  om*/
 * @return the private IP address of the specified RDS instance
 */
private static InetAddress getPrivateIpAddress(DBInstance dbInstance) {
    Preconditions.checkNotNull(dbInstance, "dbInstance is null");
    InetAddress privateIpAddress = null;
    try {
        Endpoint endpoint = dbInstance.getEndpoint();
        if (endpoint != null) {
            String endpointAddress = endpoint.getAddress();
            if (endpointAddress != null) {
                privateIpAddress = InetAddress.getByName(endpointAddress);
            }
        }
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Invalid private IP address", e);
    }
    return privateIpAddress;
}

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 ww w  . j  a  v  a 2 s  . 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:de.tuhrig.deployman.launch.Launcher.java

/**
 * Runs the given database configuration (~setup) on an AWS database instance. Make sure the setup
 * fits the database (e.g. a MSSQL setup for a MSSQL database).
 *//*from   ww w. j a va 2 s  . c o  m*/
private void runSetup(DBInstance dbInstance, Database database) {
    String setup = database.getSetup();
    String buildFilePath = new LocaleRepository().getLocation() + SLASH + setup + "/build.xml";
    Endpoint endpoint = dbInstance.getEndpoint();
    File buildFile = new File(buildFilePath);

    this.console.write("Run database setup " + buildFilePath);
    this.console.write("Endpoint " + endpoint);

    Project project = new Project();
    project.setUserProperty(Variable.ANT_FILE, buildFile.getAbsolutePath());
    project.setUserProperty(Variable.DEST_ROOT_LOCAL, new LocaleRepository().getLocation() + SLASH + "tmp");
    project.setUserProperty(Variable.DB_SERVER, endpoint.getAddress());
    project.setUserProperty(Variable.DB_PORT, endpoint.getPort().toString());
    project.setUserProperty(Variable.DB_USER, database.getUsername());
    project.setUserProperty(Variable.DB_PASSWORD, database.getPassword());
    project.setUserProperty(Variable.ENV_NLS_LANG, "American_America.UTF8");
    project.setUserProperty(Variable.HEADLESS, "true");
    project.init();

    DefaultLogger consoleLogger = createConsoleLogger();
    project.addBuildListener(consoleLogger);

    ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference("ant.projectHelper", helper);
    helper.parse(project, buildFile);
    project.executeTarget(project.getDefaultTarget());

    this.console.newLine();
}

From source file:org.cloudml.connectors.BeanstalkConnector.java

License:Open Source License

public String getDBEndPoint(String dbInstanceId, int timeout) {
    DescribeDBInstancesRequest ddbir = new DescribeDBInstancesRequest().withDBInstanceIdentifier(dbInstanceId);
    System.out.println("Waiting for DB endpoints");
    while (timeout-- > 0) {
        System.out.print("-");
        DescribeDBInstancesResult ddbi = rdsClient.describeDBInstances(ddbir);
        Endpoint endpoint = ddbi.getDBInstances().get(0).getEndpoint();
        if (endpoint != null && endpoint.toString().length() != 0)
            return endpoint.getAddress() + ":" + endpoint.getPort();

        try {//w w  w  . j  ava  2s.  c  o  m
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BeanstalkConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return "";
}