Example usage for com.amazonaws.services.cloudwatch AmazonCloudWatchClient setEndpoint

List of usage examples for com.amazonaws.services.cloudwatch AmazonCloudWatchClient setEndpoint

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudwatch AmazonCloudWatchClient setEndpoint.

Prototype

@Deprecated
void setEndpoint(String endpoint);

Source Link

Document

Overrides the default endpoint for this client ("https://monitoring.us-east-1.amazonaws.com").

Usage

From source file:br.unb.cic.bionimbuz.elasticity.AmazonMonitoring.java

License:Open Source License

public AmazonCloudWatchClient client(final String awsAccessKey, final String awsSecretKey) {
    final AmazonCloudWatchClient client = new AmazonCloudWatchClient(
            new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    client.setEndpoint("monitoring.sa-east-1.amazonaws.com");
    return client;
}

From source file:com.aipo.aws.cloudwatch.CloudWatch.java

License:Open Source License

public static AmazonCloudWatch getClient() {
    AWSContext awsContext = AWSContext.get();
    if (awsContext == null) {
        throw new IllegalStateException("AWSContext is not initialized.");
    }/*from w w w  . j a  v  a 2  s  .  co  m*/
    AmazonCloudWatchClient client = new AmazonCloudWatchClient(awsContext.getAwsCredentials());
    String endpoint = awsContext.getCloudWatchEndpoint();
    if (endpoint != null && endpoint != "") {
        client.setEndpoint(endpoint);
    }
    return client;
}

From source file:com.ec2box.manage.action.SystemAction.java

License:Apache License

@Action(value = "/admin/viewSystems", results = {
        @Result(name = "success", location = "/admin/view_systems.jsp") })
public String viewSystems() {

    Long userId = AuthUtil.getUserId(servletRequest.getSession());
    String userType = AuthUtil.getUserType(servletRequest.getSession());

    List<String> ec2RegionList = EC2KeyDB.getEC2Regions();
    List<String> instanceIdList = new ArrayList<String>();

    //default instance state
    if (sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE) == null) {
        sortedSet.getFilterMap().put(FILTER_BY_INSTANCE_STATE, AppConfig.getProperty("defaultInstanceState"));
    }/*from w  w  w .  j a  v  a2s.  c om*/

    try {
        Map<String, HostSystem> hostSystemList = new HashMap<String, HostSystem>();

        //if user profile has been set or user is a manager
        List<Profile> profileList = UserProfileDB.getProfilesByUser(userId);
        if (profileList.size() > 0 || Auth.MANAGER.equals(userType)) {
            //set tags for profile
            List<String> profileTags = new ArrayList<>();
            for (Profile profile : profileList) {
                profileTags.add(profile.getTag());
            }
            Map<String, List<String>> profileTagMap = parseTags(profileTags);

            //set tags from input filters
            Map<String, List<String>> filterTags = fetchInputFilterTags(userType, profileTagMap);

            //parse out security group list in format group[,group]
            List<String> securityGroupList = new ArrayList<>();
            if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP))) {
                securityGroupList = Arrays
                        .asList(sortedSet.getFilterMap().get(FILTER_BY_SECURITY_GROUP).split(","));
            }

            //get AWS credentials from DB
            for (AWSCred awsCred : AWSCredDB.getAWSCredList()) {

                if (awsCred != null) {
                    //set  AWS credentials for service
                    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(),
                            awsCred.getSecretKey());

                    for (String ec2Region : ec2RegionList) {
                        //create service

                        AmazonEC2 service = new AmazonEC2Client(awsCredentials,
                                AWSClientConfig.getClientConfig());
                        service.setEndpoint(ec2Region);

                        //only return systems that have keys set
                        List<String> keyValueList = new ArrayList<String>();
                        for (EC2Key ec2Key : EC2KeyDB.getEC2KeyByRegion(ec2Region, awsCred.getId())) {
                            keyValueList.add(ec2Key.getKeyNm());
                        }

                        DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();

                        Filter keyNmFilter = new Filter("key-name", keyValueList);
                        describeInstancesRequest.withFilters(keyNmFilter);

                        //instance state filter
                        if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE))) {
                            List<String> instanceStateList = new ArrayList<String>();
                            instanceStateList.add(sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATE));
                            Filter instanceStateFilter = new Filter("instance-state-name", instanceStateList);
                            describeInstancesRequest.withFilters(instanceStateFilter);
                        }

                        if (securityGroupList.size() > 0) {
                            Filter groupFilter = new Filter("group-name", securityGroupList);
                            describeInstancesRequest.withFilters(groupFilter);
                        }
                        //set name value pair for tag filter
                        List<String> tagList = new ArrayList<String>();

                        //always add all profile tags to filter list
                        addTagsToDescribeInstanceRequest(profileTagMap, describeInstancesRequest, tagList);

                        //add all additional filter tags provided by the user
                        addTagsToDescribeInstanceRequest(filterTags, describeInstancesRequest, tagList);

                        if (tagList.size() > 0) {
                            Filter tagFilter = new Filter("tag-key", tagList);
                            describeInstancesRequest.withFilters(tagFilter);
                        }

                        DescribeInstancesResult describeInstancesResult = service
                                .describeInstances(describeInstancesRequest);

                        for (Reservation res : describeInstancesResult.getReservations()) {
                            for (Instance instance : res.getInstances()) {

                                HostSystem hostSystem = new HostSystem();
                                hostSystem.setInstance(instance.getInstanceId());

                                //check for public dns if doesn't exist set to ip or pvt dns
                                if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS"))
                                        && StringUtils.isNotEmpty(instance.getPublicDnsName())) {
                                    hostSystem.setHost(instance.getPublicDnsName());
                                } else if (!"true".equals(AppConfig.getProperty("useEC2PvtDNS"))
                                        && StringUtils.isNotEmpty(instance.getPublicIpAddress())) {
                                    hostSystem.setHost(instance.getPublicIpAddress());
                                } else if (StringUtils.isNotEmpty(instance.getPrivateDnsName())) {
                                    hostSystem.setHost(instance.getPrivateDnsName());
                                } else {
                                    hostSystem.setHost(instance.getPrivateIpAddress());
                                }

                                hostSystem.setKeyId(EC2KeyDB
                                        .getEC2KeyByNmRegion(instance.getKeyName(), ec2Region, awsCred.getId())
                                        .getId());
                                hostSystem.setEc2Region(ec2Region);
                                hostSystem.setState(instance.getState().getName());
                                for (Tag tag : instance.getTags()) {
                                    if ("Name".equals(tag.getKey())) {
                                        hostSystem.setDisplayNm(tag.getValue());
                                    }
                                }
                                instanceIdList.add(hostSystem.getInstance());
                                hostSystemList.put(hostSystem.getInstance(), hostSystem);
                            }
                        }

                        if (instanceIdList.size() > 0) {
                            //set instance id list to check permissions when creating sessions
                            servletRequest.getSession().setAttribute("instanceIdList",
                                    new ArrayList<String>(instanceIdList));
                            if (showStatus) {
                                //make service call 100 instances at a time b/c of AWS limitation
                                int i = 0;
                                List<String> idCallList = new ArrayList<String>();
                                while (!instanceIdList.isEmpty()) {
                                    idCallList.add(instanceIdList.remove(0));
                                    i++;
                                    //when i eq 100 make call
                                    if (i >= 100 || instanceIdList.isEmpty()) {

                                        //get status for host systems
                                        DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest();
                                        describeInstanceStatusRequest.withInstanceIds(idCallList);
                                        DescribeInstanceStatusResult describeInstanceStatusResult = service
                                                .describeInstanceStatus(describeInstanceStatusRequest);

                                        for (InstanceStatus instanceStatus : describeInstanceStatusResult
                                                .getInstanceStatuses()) {

                                            HostSystem hostSystem = hostSystemList
                                                    .remove(instanceStatus.getInstanceId());
                                            hostSystem.setSystemStatus(
                                                    instanceStatus.getSystemStatus().getStatus());
                                            hostSystem.setInstanceStatus(
                                                    instanceStatus.getInstanceStatus().getStatus());

                                            //check and filter by instance or system status
                                            if ((StringUtils.isEmpty(
                                                    sortedSet.getFilterMap().get(FILTER_BY_INSTANCE_STATUS))
                                                    && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                            .get(FILTER_BY_SYSTEM_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_INSTANCE_STATUS))
                                                            && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS))
                                                            && StringUtils.isEmpty(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_INSTANCE_STATUS)))
                                                    || (hostSystem.getInstanceStatus()
                                                            .equals(sortedSet.getFilterMap()
                                                                    .get(FILTER_BY_SYSTEM_STATUS))
                                                            && hostSystem.getInstanceStatus()
                                                                    .equals(sortedSet.getFilterMap()
                                                                            .get(FILTER_BY_INSTANCE_STATUS)))) {
                                                hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                            }
                                        }

                                        //start over
                                        i = 0;
                                        //clear list
                                        idCallList.clear();
                                    }

                                }

                                //check alarms for ec2 instances
                                AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(
                                        awsCredentials, AWSClientConfig.getClientConfig());
                                cloudWatchClient.setEndpoint(ec2Region.replace("ec2", "monitoring"));

                                DescribeAlarmsResult describeAlarmsResult = cloudWatchClient.describeAlarms();

                                for (MetricAlarm metricAlarm : describeAlarmsResult.getMetricAlarms()) {

                                    for (Dimension dim : metricAlarm.getDimensions()) {

                                        if (dim.getName().equals("InstanceId")) {
                                            HostSystem hostSystem = hostSystemList.remove(dim.getValue());
                                            if (hostSystem != null) {
                                                if ("ALARM".equals(metricAlarm.getStateValue())) {
                                                    hostSystem
                                                            .setMonitorAlarm(hostSystem.getMonitorAlarm() + 1);
                                                } else if ("INSUFFICIENT_DATA"
                                                        .equals(metricAlarm.getStateValue())) {
                                                    hostSystem.setMonitorInsufficientData(
                                                            hostSystem.getMonitorInsufficientData() + 1);
                                                } else {
                                                    hostSystem.setMonitorOk(hostSystem.getMonitorOk() + 1);
                                                }
                                                //check and filter by alarm state
                                                if (StringUtils.isEmpty(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("ALARM".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorAlarm() > 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("INSUFFICIENT_DATA".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorInsufficientData() > 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                } else if ("OK".equals(
                                                        sortedSet.getFilterMap().get(FILTER_BY_ALARM_STATE))
                                                        && hostSystem.getMonitorOk() > 0
                                                        && hostSystem.getMonitorInsufficientData() <= 0
                                                        && hostSystem.getMonitorAlarm() <= 0) {
                                                    hostSystemList.put(hostSystem.getInstance(), hostSystem);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //set ec2 systems
            SystemDB.setSystems(hostSystemList.values());
            sortedSet = SystemDB.getSystemSet(sortedSet, new ArrayList<String>(hostSystemList.keySet()));

        }
    } catch (AmazonServiceException ex) {
        log.error(ex.toString(), ex);
    }

    if (script != null && script.getId() != null) {
        script = ScriptDB.getScript(script.getId(), userId);
    }

    return SUCCESS;
}

From source file:com.netflix.atlas.client.CloudWatchObserver.java

License:Apache License

/**
 * Create the observer with a given configuration.
 *///from   ww  w  .j a v  a2s  .c o  m
public CloudWatchObserver(PluginConfig config, PushManager pushManager) {
    this.config = config;
    this.pushManager = pushManager;
    final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    final AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(credentialsProvider);
    final String region = NetflixEnvironment.region();
    if (region != null) {
        cloudWatchClient.setEndpoint(String.format("monitoring.%s.amazonaws.com", region));
    }
    this.cloudWatchMetricObserver = new CloudWatchMetricObserver(getName(), config.getCloudwatchNamespace(),
            cloudWatchClient);
}

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

License:Open Source License

/**
 * Retrieve the list of metrics/*from   w ww  .ja  va2s. c  o  m*/
 * 
 * @return Either
 * <ul>
 *    <li>AmazonServiceException</li>
 *  <li>AmazonClientException</li>
 *  <li>List\<Metric\></li>
 * </ul>
 */
public Object retrieveMetricsList(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    List<Metric> returnedMetrics = null;
    ArrayList<String> measureNames = new ArrayList<String>();
    ListMetricsRequest request = new ListMetricsRequest();

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));

    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    cloudWatchClient.setEndpoint(cloudWatchEndpoint);

    //create the request
    request = new ListMetricsRequest();
    //request.setNextToken(nextToken)
    try {
        returnedMetrics = cloudWatchClient.listMetrics().getMetrics();
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //my own disgusting O(mnp) filter. This is REALLY CRAP!
    //remove all that does not fit into the dimension
    //for some reason, there isn't a way to provide dimensions using ListMetricsRequest in Java
    //you can do it in the C# API though :P
    List<Dimension> returnedDimensions;
    boolean added;
    for (Metric metric : returnedMetrics) {
        returnedDimensions = metric.getDimensions();
        added = false;
        for (Dimension returnedDimension : returnedDimensions) {
            //check if any of the dimensions passed in to the model are equal to this.
            for (Dimension dimension : dimensions) {
                if (returnedDimension.getValue().equals(dimension.getValue())) {
                    measureNames.add(metric.getMeasureName());
                    added = true;
                    break;
                }
            }

            if (added) {
                break;
            }
        }
    }

    return measureNames;
}

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

License:Open Source License

/** 
 * Perform the actual work of retrieving the metrics
 *//*from ww  w.  j a v a 2s. c  om*/
public Object retrieveMetrics(Dimension... dimensions) {
    //the cloudwatch client to use
    AmazonCloudWatchClient cloudWatchClient = null;
    //the request to send to cloudwatch
    GetMetricStatisticsRequest request;
    //the metric stats result.
    GetMetricStatisticsResult result;

    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create a cloudwatch client
    try {
        cloudWatchClient = new AmazonCloudWatchClient(credentials);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //prepare request
    request = new GetMetricStatisticsRequest();
    request.setStartTime(new Date(cloudWatchInput.getStartTime()));
    request.setEndTime(new Date(cloudWatchInput.getEndTime()));
    request.setPeriod(cloudWatchInput.getPeriod());
    request.setMeasureName(cloudWatchInput.getMeasureName());
    request.setNamespace(cloudWatchInput.getNamespace());
    request.setStatistics(cloudWatchInput.getStatistics());
    request.setDimensions(Arrays.asList(dimensions));
    //tell the cloudwatch client where to look!
    cloudWatchClient.setEndpoint(AWSConstants.getCloudWatchEndpoint(cloudWatchInput.getRegion()));

    //get the monitoring result!
    try {
        result = cloudWatchClient.getMetricStatistics(request);
    } catch (AmazonServiceException amazonServiceException) {
        //if an error response is returned by AmazonIdentityManagement indicating either a 
        //problem with the data in the request, or a server side issue.
        Log.e(this.getClass().getName(), "Exception:" + amazonServiceException.getMessage());
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        //If any internal errors are encountered inside the client while attempting to make 
        //the request or handle the response. For example if a network connection is not 
        //available. 
        Log.e(this.getClass().getName(), "Exception:" + amazonClientException.getMessage());
        return amazonClientException;
    }

    //get the data and print it out.
    List<Datapoint> data = result.getDatapoints();
    for (Datapoint datum : data) {
        Log.v(TAG, "Datum:" + datum.getAverage());
    }

    //sort the data in ascending order of timestamps
    Collections.sort(data, new CloudWatchDataSorter());

    //return the sorted data
    return data;
}

From source file:org.onebusaway.aws.cloudwatch.impl.CloudwatchServiceImpl.java

License:Apache License

public void setup() {
    String accessKey = _configurationService.getConfigurationValueAsString("aws.accessKey", "");
    String secretKey = _configurationService.getConfigurationValueAsString("aws.secretKey", "");

    endPoint = _configurationService.getConfigurationValueAsString("aws.endPoint",
            "monitoring.us-east-1.amazonaws.com");
    environmentName = _configurationService.getConfigurationValueAsString("oba.env", "dev");

    AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(
            new BasicAWSCredentials(accessKey, secretKey));
    cloudWatch.setEndpoint(endPoint);
    this.cloudWatch = cloudWatch;
}