Example usage for com.amazonaws.services.ec2 AmazonEC2Client describeRegions

List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client describeRegions

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2Client describeRegions.

Prototype

@Override
    public DescribeRegionsResult describeRegions() 

Source Link

Usage

From source file:com.axemblr.yab.YaB.java

License:Apache License

/**
 * Constructs a new YaB client by fetching credentials in this order:
 * <p>//from   w w w.  j  a v  a 2s .c o  m
 * - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
 * - Java System Properties - aws.accessKeyId and aws.secretKey
 * - Instance profile credentials delivered through the Amazon EC2 metadata service
 * </p>
 */
public static YaB createWithEnvironmentCredentials(String region) {
    AmazonEC2Client client = new AmazonEC2Client();

    boolean regionFound = false;
    DescribeRegionsResult result = client.describeRegions();
    for (Region candidate : result.getRegions()) {
        if (candidate.getRegionName().equals(region)) {
            client.setEndpoint(candidate.getEndpoint());
            regionFound = true;
            break;
        }
    }

    if (!regionFound) {
        throw new IllegalArgumentException("No region found with this name: " + region);
    }

    return new YaB(client);
}

From source file:com.boxupp.dao.AwsProjectDAOManager.java

License:Apache License

private StatusBean validateKeyPair(AmazonEC2Client ec2Client, String keyPair) throws AmazonServiceException {
    StatusBean statusBean = new StatusBean();
    List<com.amazonaws.services.ec2.model.Region> regions = ec2Client.describeRegions().getRegions();
    for (com.amazonaws.services.ec2.model.Region region : regions) {
        ec2Client.setRegion(com.amazonaws.regions.Region
                .getRegion(com.amazonaws.regions.Regions.fromName(region.getRegionName())));
        List<KeyPairInfo> keyPairs = ec2Client.describeKeyPairs().getKeyPairs();
        for (KeyPairInfo keyPairInfo : keyPairs) {
            if (keyPairInfo.getKeyName().equals(keyPair)) {
                statusBean.setStatusCode(0);
                statusBean.setStatusMessage("Key Pair validated with region " + region.getRegionName());
                return statusBean;
            }//from   w  w  w.j a v a 2 s  .  com
        }
    }
    statusBean.setStatusCode(1);
    statusBean.setStatusMessage("Key Pair not found Please enter a valid key pair");
    return statusBean;
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Configures the specified EC2 client./*from   www  .  ja  va2s.co m*/
 *
 * @param configuration               the provider configuration
 * @param accumulator                 the exception accumulator
 * @param client                      the EC2 client
 * @param providerLocalizationContext the resource provider localization context
 * @param verify                      whether to verify the configuration by making an API call
 * @return the configured client
 * @throws InvalidCredentialsException    if the supplied credentials are invalid
 * @throws TransientProviderException     if a transient exception occurs communicating with the
 *                                        provider
 * @throws UnrecoverableProviderException if an unrecoverable exception occurs communicating with
 *                                        the provider
 */
protected static AmazonEC2Client configureClient(Configured configuration,
        PluginExceptionConditionAccumulator accumulator, AmazonEC2Client client,
        LocalizationContext providerLocalizationContext, boolean verify) {
    checkNotNull(client, "client is null");

    try {
        String regionEndpoint = configuration.getConfigurationValue(REGION_ENDPOINT,
                providerLocalizationContext);
        if (regionEndpoint != null) {
            LOG.info("<< Using configured region endpoint for EC2 client: {}", regionEndpoint);
        } else {
            String region = configuration.getConfigurationValue(REGION, providerLocalizationContext);
            regionEndpoint = getEndpointForRegion(client, region);
        }
        client.setEndpoint(regionEndpoint);

        if (verify) {
            // Attempt to use client, to validate credentials and connectivity
            client.describeRegions();
        }

    } catch (AmazonClientException e) {
        throw AWSExceptions.propagate(e);
    } catch (IllegalArgumentException e) {
        accumulator.addError(REGION.unwrap().getConfigKey(), e.getMessage());
    }
    return client;
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Returns the endpoint URL for the specified region.
 *
 * @param client     the EC2 client/*w w w.j a v  a  2 s  .c  o m*/
 * @param regionName the desired region
 * @return the endpoint URL for the specified region
 * @throws IllegalArgumentException if the endpoint cannot be determined
 */
private static String getEndpointForRegion(AmazonEC2Client client, String regionName) {
    checkNotNull(client, "client is null");
    checkNotNull(regionName, "regionName is null");

    LOG.info(">> Describing all regions to find endpoint for '{}'", regionName);

    DescribeRegionsResult result = client.describeRegions();
    List<String> regions = Lists.newArrayListWithExpectedSize(result.getRegions().size());

    for (Region candidate : result.getRegions()) {
        regions.add(candidate.getRegionName());

        if (candidate.getRegionName().equals(regionName)) {
            LOG.info("<< Found endpoint '{}' for region '{}'", candidate.getEndpoint(), regionName);

            return candidate.getEndpoint();
        }
    }

    throw new IllegalArgumentException(String.format(
            "Unable to find an endpoint for region '%s'. " + "Choose one of the following regions: %s",
            regionName, Joiner.on(", ").join(regions)));
}

From source file:com.noctarius.hazelcast.aws.HazelcastAwsDiscoveryStrategy.java

License:Open Source License

private Map<String, String> buildRegionLookup(AmazonEC2Client client) {
    Map<String, String> regionLookup = new HashMap<String, String>();

    DescribeRegionsResult regionsResult = client.describeRegions();
    for (Region region : regionsResult.getRegions()) {
        regionLookup.put(region.getRegionName(), region.getEndpoint());
    }//from   ww  w.  ja  v a 2  s.c o m
    return Collections.unmodifiableMap(regionLookup);
}

From source file:com.norbl.cbp.ppe.AmiDescription.java

License:Open Source License

public static Region getRegion(AmazonEC2Client ec2Client, String amiID) {

    DescribeRegionsResult rr = ec2Client.describeRegions();
    for (Region reg : rr.getRegions()) {
        ec2Client.setEndpoint(reg.getEndpoint());
        if (hasAmi(ec2Client, amiID)) {
            return (reg);
        }//ww  w .  java 2  s. com
    }
    // Reset the endpoint to the default
    ec2Client.setEndpoint("ec2.amazonaws.com");

    return (null);

}

From source file:de.fischer.thotti.ec2.clients.EC2ExecutorITHelper.java

License:Apache License

public void retrieveRegions() {
    AmazonEC2Client awsClient = getAmazonClient();

    DescribeRegionsResult regionsResult = awsClient.describeRegions();

    awsRegions = regionsResult.getRegions();
}

From source file:io.macgyver.plugin.cloud.aws.scanner.RegionScanner.java

License:Apache License

@Override
public void scan(Region region) {

    GraphNodeGarbageCollector gc = newGarbageCollector().region(region).label("AwsRegion");

    AmazonEC2Client c = getAWSServiceClient().createEC2Client(region);

    DescribeRegionsResult result = c.describeRegions();
    result.getRegions().forEach(it -> {
        try {//from   w  w  w .  ja  v  a2  s  . co m
            ObjectNode n = convertAwsObject(it, region);

            n.remove("aws_account");
            String cypher = "merge (x:AwsRegion {aws_regionName:{aws_regionName}}) set x+={props}  remove x.aws_region,x.aws_account set x.updateTs=timestamp() return x";

            NeoRxClient neoRx = getNeoRxClient();
            Preconditions.checkNotNull(neoRx);

            neoRx.execCypher(cypher, "aws_regionName", n.path("aws_regionName").asText(), "aws_region",
                    n.path("aws_region").asText(), "props", n).forEach(gc.MERGE_ACTION);

        } catch (RuntimeException e) {
            logger.warn("problem scanning regions", e);
        }
    });

    gc.invoke();

}

From source file:org.elasticdroid.model.RetrieveRegionModel.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*  w  w  w .  ja  va 2  s .  com*/
protected Object doInBackground(HashMap<?, ?>... params) {
    HashMap<String, String> connectionData;
    HashMap<String, String> regionData = new HashMap<String, String>();

    List<Region> regions;//data from AWS.

    //we accept only one param, but AsyncTask forces us to potentially accept
    //a whole bloody lot of them. :P
    if (params.length != 1) {
        return new IllegalArgumentException(
                "Only one Hashtable<String,String> parameter " + "should be passed.");
    }

    connectionData = (HashMap<String, String>) params[0]; //convenience variable, so that
    //i dont have to keep typing params[0] everywhere in this method.;)

    Log.v(this.getClass().getName(), "Getting EC2 region data...");

    //prepare to get region data
    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create Amazon EC2 Client object, and set tye end point to the region. params[3]
    //contains endpoint
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);
    try {
        regions = amazonEC2Client.describeRegions().getRegions();
    } catch (AmazonServiceException amazonServiceException) {
        //this is an unchecked exception subclassed from RuntimeException. So throw it manually
        Log.v(this.getClass().getName(), "Caught ServiceException.");
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //this is an unchecked exception subclassed from RuntimeException. So throw it manually
        Log.v(this.getClass().getName(), "Caught ClientException.");
        return amazonClientException;
    }

    if (regions.size() == 0) {
        return new IllegalArgumentException("No regions found");
    }

    //populate the region data with regionName: regionEndPoint
    for (Region region : regions) {
        regionData.put(region.getRegionName(), region.getEndpoint());
        Log.v("AWSUtilities.getRegions", region.getRegionName());
    }

    return regionData;
}