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

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

Introduction

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

Prototype

@Deprecated
public void setEndpoint(String endpoint) throws IllegalArgumentException 

Source Link

Document

Overrides the default endpoint for this client.

Usage

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.InfrastructureConfiguration.java

License:Apache License

@Bean
@ConditionalOnProperty("aws.accessKeyId")
AmazonEC2Client amazonEC2(@Value("${aws.accessKeyId}") String accessKeyId,
        @Value("${aws.secretAccessKey}") String secretAccessKey,
        @Value("${aws.region:us-east-1}") String regionName) {

    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(
            new BasicAWSCredentials(accessKeyId, secretAccessKey));
    Region region = Region.getRegion(Regions.fromName(regionName));
    amazonEC2Client.setEndpoint(region.getServiceEndpoint("ec2"));

    return amazonEC2Client;
}

From source file:it.openutils.mgnlaws.magnolia.AmazonMgnlServletContextListener.java

License:Open Source License

protected void initEc2(String accessKey, String secretKey, String endpoint)
        throws IOException, AmazonEc2InstanceNotFound {
    String ec2InstanceId;/*w  w w .ja  va 2  s .  co  m*/
    BufferedReader in = null;
    try {
        URL url = new URL("http://169.254.169.254/latest/meta-data/instance-id");
        URLConnection connection = url.openConnection();
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        ec2InstanceId = in.readLine();
        in.close();
    } finally {
        IOUtils.closeQuietly(in);
    }

    AmazonEC2Client client = new AmazonEC2Client(new BasicAWSCredentials(accessKey, secretKey));
    client.setEndpoint(endpoint);
    DescribeInstancesResult result = client
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(ec2InstanceId));
    if (result.getReservations().size() > 0 && result.getReservations().get(0).getInstances().size() > 0) {
        ec2Instance = result.getReservations().get(0).getInstances().get(0);
        if (ec2Instance == null) {
            // should never happen
            throw new AmazonEc2InstanceNotFound(ec2InstanceId);
        }
    } else {
        throw new AmazonEc2InstanceNotFound(ec2InstanceId);
    }

    for (Tag tag : ec2Instance.getTags()) {
        if (StringUtils.startsWith(tag.getKey(), "__")) {
            System.setProperty(StringUtils.substring(tag.getKey(), 2), tag.getValue());
        } else {
            System.setProperty("aws.instance." + tag.getKey(), tag.getValue());
        }
    }

    String clusterId = System.getProperty(EC2_TAG_CLUSTERID);
    if (StringUtils.isNotEmpty(clusterId)) {
        System.setProperty(JR_CLUSTERID, clusterId);
    }
}

From source file:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

@GET
@RolesAllowed("authenticated")
@Path("dump")
public String dump(@QueryParam("id") String id, @QueryParam("key") String key,
        @DefaultValue("https://ec2.amazonaws.com") @QueryParam("location") String location) {
    log.info("Id=" + id + " key=" + key);
    ClientConfiguration clientConfiguration = new ClientConfiguration();

    try {//from   w w  w. j  a v  a 2s  .  c o  m
        clientConfiguration
                .setProtocol(Protocol.valueOf(URI.create(location).toURL().getProtocol().toUpperCase()));
    } catch (MalformedURLException e) {
        throw new WebApplicationException();
    }
    AmazonEC2Client client = new AmazonEC2Client(new BasicAWSCredentials(id, key), clientConfiguration);
    client.setEndpoint(location.toString());

    DescribeKeyPairsResult result = client.describeKeyPairs();
    log.info("Key pairs " + result.getKeyPairs());

    return (result.getKeyPairs().size() + " key pairs ");
}

From source file:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

private AmazonEC2Client getEC2Client(String accessKey, String encryptedKey, URI location) {
    AWSCredentials credentials = null;//from   www .  ja  v  a 2  s .c  o m
    try {
        credentials = new EncryptedAWSCredentials(accessKey, encryptedKey);
    } catch (UnsupportedEncodingException e) {
        throw new WebApplicationException();
    } catch (NoSuchAlgorithmException e) {
        throw new WebApplicationException();
    } catch (Exception e) {
        throw new WebApplicationException();
    }
    ClientConfiguration clientConfiguration = new ClientConfiguration();

    try {
        clientConfiguration.setProtocol(Protocol.valueOf(location.toURL().getProtocol().toUpperCase()));
    } catch (MalformedURLException e) {
        throw new WebApplicationException();
    }
    AmazonEC2Client client = new AmazonEC2Client(credentials, clientConfiguration);
    client.setEndpoint(location.toString());
    return client;
}

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

License:Open Source License

public Collection<String> getEnvIPs(String envName, int timeout) {
    DescribeEnvironmentResourcesRequest request = new DescribeEnvironmentResourcesRequest()
            .withEnvironmentName(envName);
    List<Instance> instances = null;
    System.out.print("Waiting for environment ips");
    while (timeout-- > 0) {
        try {//  w w w .  j a  va 2 s  .  com
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BeanstalkConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.print("-");
        DescribeEnvironmentResourcesResult res = beanstalkClient.describeEnvironmentResources(request);
        instances = res.getEnvironmentResources().getInstances();
        if (instances.size() == 0)
            continue;
        AmazonEC2Client ec2 = new AmazonEC2Client(awsCredentials);
        ec2.setEndpoint(beanstalkEndpoint.replace("elasticbeanstalk", "ec2"));
        List<String> instanceIds = new ArrayList<String>();
        for (Instance instance : instances) {
            instanceIds.add(instance.getId());
        }
        List<String> ips = new ArrayList<String>();
        DescribeInstancesRequest desins = new DescribeInstancesRequest().withInstanceIds(instanceIds);
        DescribeInstancesResult desinres = ec2.describeInstances(desins);
        for (Reservation reservation : desinres.getReservations()) {
            for (com.amazonaws.services.ec2.model.Instance ins : reservation.getInstances()) {
                String ip = ins.getPublicIpAddress();
                if (ip != null && ip.length() > 0)
                    ips.add(ip);
            }
        }
        if (ips.size() > 0)
            return ips;

    }
    return Collections.EMPTY_LIST;
}

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

License:Open Source License

/**
 * Method that does the actual work of starting or stopping the instances
 * // w w w  . j  a  v  a 2  s . com
 * This method uses the stop boolean to identify whether the instances should be stopped 
 * (stop = true) or started (stop = false).
 * 
 * @return Returns one of the following:
 * <ul>
 *    <li>newInstanceStates: Returns a list of stateCodes and state names for all of the instances
 *    </li>
 *    <li> AmazonServiceException</li>
 *    <li> AmazonClientException</li>
 * </ul>
 * 
 */
public Object controlInstances(List<String> instances) {

    for (String instance : instances) {
        Log.v(TAG, "Starting instance: " + instance);
    }

    //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);
    //override the default connection endpoint if provided.
    if (connectionData.get("endpoint") != null) {
        amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    }

    //if you want to start an instance
    if (operationType == ControlType.START_INSTANCE) {
        StartInstancesRequest request = new StartInstancesRequest(instances);
        StartInstancesResult result = null;
        try {
            result = amazonEC2Client.startInstances(request);
        } catch (AmazonServiceException amazonServiceException) {
            return amazonServiceException;
        } catch (AmazonClientException amazonClientException) {
            return amazonClientException;
        }
        //redundant check.
        if (result != null) {
            return result.getStartingInstances();
        }
    }
    //stop = true, start the instance.
    else {
        StopInstancesRequest request = new StopInstancesRequest(instances);
        StopInstancesResult result = null;

        try {
            result = amazonEC2Client.stopInstances(request);
        } catch (AmazonServiceException amazonServiceException) {
            return amazonServiceException;
        } catch (AmazonClientException amazonClientException) {
            return amazonClientException;
        }

        if (result != null) {
            return result.getStoppingInstances();
        }
    }

    return null;
}

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

License:Open Source License

/**
 * Create/override tags of key name for the instances.
 * @param instances: list of instances/*from  w  w  w  .j  a  v a 2 s . c o m*/
 * @return
 * <ul>
 *    <li> true: to indicate success in reassigning the tags </li>
 *    <li>IllegalArgumentException: If the number of instances != number of tags</li>
 * <li>AmazonServicesException: Serverside issues with AWS</li>
 * <li>AmazonClientException: (Probably) connectivity issues</li>
 * </ul>
 */
public Object tagInstance(List<String> instances) {
    if (instances.size() != ec2Tags.size()) {
        return new IllegalArgumentException("The number of instances should be equal to be " + "the number");
    }
    //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);

    //override the default connection endpoint if provided.
    if (connectionData.get("endpoint") != null) {
        amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    }

    //create a TagsRequest
    for (String instance : instances) {
        Log.v(TAG, "Tagging " + instance);
    }
    CreateTagsRequest request = new CreateTagsRequest(instances, ec2Tags);

    //okay, tag the instance
    try {
        amazonEC2Client.createTags(request);
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    return new Boolean(true); //return true to indicate success!
}

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

License:Open Source License

public Object deleteTags(List<String> instances) {

    //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);

    //override the default connection endpoint if provided.
    if (connectionData.get("endpoint") != null) {
        amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    }/*from  w w  w  . jav a 2s  .c  o m*/

    //create empty tags for each of the instances from which the name tag is to be deleted.
    for (String instance : instances) {
        Log.v(TAG, "Tagging " + instance);
        //create a tag with Name for each instance from which Name tag is to be deleted.
        ec2Tags.add(new Tag("Name"));
    }

    DeleteTagsRequest request = new DeleteTagsRequest(instances);
    request.setTags(ec2Tags);

    //okay, tag the instance
    try {
        amazonEC2Client.deleteTags(request);
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    return new Boolean(true); //return true to indicate success!
}

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

License:Open Source License

/**
 * Gets the data to populate the EC2 Dashboard with in the background thread, and loads it into
 * a Hashtable<String, Integer>. // w  w  w . ja v  a2s . c om
 * 
 * @param This method accepts *ONE* Hashtable<String, String> of LoginDetails arguments. The
 * required keys are as follows (anything else is ignored):
 * <ul>
 * <li> accessKey: The accesskey for the AWS/AWS IAM account used.</li> 
 * <li> secretAccessKey: The secretAccessKey for the AWS/AWS IAM account used.</li> 
 * <li> endpoint: AWS Endpoint for the selected region (@see {@link AWSConstants.EndPoints}</li>
 * </ul>
 * If you're missing any of these keys, AmazonServiceExceptions will be thrown. This shouldn't
 * be visible to the end-user as this is a programmer fault!!! :P
 * 
 * @return This method can return:
 * <ul>
 * <li>{@link IllegalArgumentException}: If there are too many/few arguments, or the keys are  
 * incorrect. Only one Hashtable<String, String> accepted.</li>
 * <li>{@link Hashtable<String, Integer}: data to populate dashboard with.
 *       <ul>
 *       <li><i>runningInstances:</i> The number of running instances for the user in the current 
 *       region</li>
 *       <li><i>stoppedInstances:</i> The number of stopped instances for the user in the current 
 *       region</li>
 *       <li><i>elasticIp:</i> The number of elastic IPs owned by the user (in the current region)
 *      </li>
 *       <li><i>securityGroups:</i> The number of security groups avail 2 the user (in the current
 *       region)</li>
 *       <li><i>keyPairs:</i> The number of keypairs avail 2 the user (in the current
 *       region)</li>
 *       </ul> 
 * </li>
 * </ul>
 */
@SuppressWarnings("unchecked")
@Override
protected Object doInBackground(HashMap<?, ?>... params) {
    HashMap<String, String> connectionData;
    HashMap<String, Integer> dashboardData;

    //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 dashboard data...");

    //prepare to get the dashboard 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);
    amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    //initialise result holder variable
    dashboardData = new HashMap<String, Integer>();

    try {
        //get the number of running and stopped instances
        DescribeInstancesResult instances = amazonEC2Client.describeInstances();

        int numOfRunningInstances = 0;
        int numOfStoppedInstances = 0;
        //get the list of reservations in the results
        for (Reservation reservation : instances.getReservations()) {
            //for each reservation, get the list of instances associated
            for (Instance instance : reservation.getInstances()) {
                if (instance.getState().getCode().byteValue() == InstanceStateConstants.RUNNING) {
                    numOfRunningInstances++;
                } else if (instance.getState().getCode().byteValue() == InstanceStateConstants.STOPPED) {
                    numOfStoppedInstances++;
                }
            }
        }
        dashboardData.put("runningInstances", numOfRunningInstances);
        dashboardData.put("stoppedInstances", numOfStoppedInstances);

        //get the list of elastic Ips.
        dashboardData.put("elasticIp", amazonEC2Client.describeAddresses().getAddresses().size());

        //get the list of security groups
        dashboardData.put("securityGroups",
                amazonEC2Client.describeSecurityGroups().getSecurityGroups().size());

        //get the list of keypairs
        dashboardData.put("keyPairs", amazonEC2Client.describeKeyPairs().getKeyPairs().size());
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    return dashboardData;
}

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

License:Open Source License

/**
 * //from w w  w .j  ava 2  s . co m
 * @param filters
 * @return This method can return:
 * <ul>
 * <li>ArrayList<SerializableInstance>: If all goes well</li>
 * <li>AmazonClientException: If there's connectivity problems on the client.</li>
 * <li>AmazonServiceException: If there's AWS service problems.</li>
 * <li>IllegalArgumentException: If the region can't be found.</li>
 * </ul>
 */
public Object getInstances(Filter... filters) {
    ArrayList<SerializableInstance> serInstances = new ArrayList<SerializableInstance>();
    //result passed to Activity
    List<Region> regions;
    List<Reservation> reservations; //restult from EC2

    //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);

    //1. create a filter for this region name
    Filter regionFilter = new Filter("region-name");
    regionFilter.setValues(new ArrayList<String>(Arrays.asList(new String[] { selectedRegion })));

    //2. query using this filter
    try {
        regions = amazonEC2Client.describeRegions(new DescribeRegionsRequest().withFilters(regionFilter))
                .getRegions();
    } catch (AmazonServiceException exc) {
        return exc;
    } catch (AmazonClientException exc) {
        return exc;
    }

    //3. Make sure the region was found.
    if (regions.size() != 1) {
        return new IllegalArgumentException("Invalid region passed to model.");
    }

    Log.v(TAG + ".doInBackground()",
            "endpoint for region : " + selectedRegion + "=" + regions.get(0).getEndpoint());
    //set the endpoint
    amazonEC2Client.setEndpoint(regions.get(0).getEndpoint());

    //now get the instances

    Log.v(TAG, "Size of filters:" + filters.length);
    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setFilters(Arrays.asList(filters));

    //get the list of instances using this filter
    try {
        reservations = amazonEC2Client.describeInstances(request).getReservations();
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    //add each instance found into the list of instances to return to the view
    for (Reservation reservation : reservations) {
        List<String> securityGroups = reservation.getGroupNames();
        //note to self: List is an interface ArrayList implements.
        //for each reservation, get the list of instances associated
        for (Instance instance : reservation.getInstances()) {
            serInstances.add(new SerializableInstance(instance, securityGroups));
        }
    }

    return serInstances;
}