Example usage for com.amazonaws.services.ec2.model Instance getPrivateDnsName

List of usage examples for com.amazonaws.services.ec2.model Instance getPrivateDnsName

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model Instance getPrivateDnsName.

Prototype


public String getPrivateDnsName() 

Source Link

Document

(IPv4 only) The private DNS hostname name assigned to the instance.

Usage

From source file:com.automata.cloudcore.xmlbindings.RunningInstancesItemType.java

License:Open Source License

public RunningInstancesItemType(Instance instance) {
    this.instanceId = instance.getInstanceId();
    InstanceStateType instanceStateType = new InstanceStateType();
    instanceStateType.setName(instance.getInstanceLifecycle());
    //instanceStateType.setCode();
    this.instanceState = instanceStateType;
    this.privateDnsName = instance.getPrivateDnsName();
    this.imageId = instance.getImageId();
    this.dnsName = instance.getPublicDnsName();
    //this.reason   = instance.get
    this.keyName = instance.getKeyName();
    if (instance.getStateTransitionReason() != null)
        this.reason = instance.getStateTransitionReason().toString();
    this.amiLaunchIndex = instance.getAmiLaunchIndex().toString();
    //this.productCodes = instance.getProductCodes();
    this.instanceType = instance.getInstanceType();
    //this.launchTime = instance.getLaunchTime();
    //this.placement = instance.getPlacement();
    this.kernelId = instance.getKernelId();
    this.ramdiskId = instance.getRamdiskId();
    this.platform = instance.getPlatform();

    InstanceMonitoringStateType instanceMonitoringStateType;
    instanceMonitoringStateType = new InstanceMonitoringStateType();
    instanceMonitoringStateType.setState(instance.getMonitoring().toString());
    this.monitoring = instanceMonitoringStateType;

    this.subnetId = instance.getSubnetId();
    this.vpcId = instance.getVpcId();
    this.privateIpAddress = instance.getPrivateIpAddress();
    this.ipAddress = instance.getPublicIpAddress();
    this.sourceDestCheck = instance.getSourceDestCheck();
    //this.groupSet = 

    if (instance.getStateReason() != null) {
        StateReasonType stateReasonType = new StateReasonType();
        stateReasonType.setMessage(instance.getStateReason().getMessage());
        this.stateReason = stateReasonType;
    }//from  www.j a va2s. c o m
    this.architecture = instance.getArchitecture();
    this.rootDeviceType = instance.getRootDeviceType();
    this.rootDeviceName = instance.getRootDeviceName();

    /*BlockDeviceMappingsType blockDeviceMappingsType = new BlockDeviceMappingsType();
    List<BlockDeviceMapping> blockDeviceMappingList = new ArrayList<BlockDeviceMapping>();
    BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
    for (){
               
    }
            
    blockDeviceMappingsType = 
    this.blockDeviceMapping = instance.getBlockDeviceMappings();*/
    this.instanceLifecycle = instance.getInstanceLifecycle();
    this.spotInstanceRequestId = instance.getSpotInstanceRequestId();

    if (instance.getLicense() != null) {
        InstanceLicenseResponseType instanceLicenseResponseType;
        instanceLicenseResponseType = new InstanceLicenseResponseType();
        instanceLicenseResponseType.setPool(instance.getLicense().getPool());
        this.license = instanceLicenseResponseType;
    }

    this.virtualizationType = instance.getVirtualizationType();
    this.clientToken = instance.getClientToken();

    /*ResourceTagSetType resourceTagSetType;
    ResourceTagSetItemType resourceTagSetItemType;
    List<ResourceTagSetItemType> resourceTagSetItemTypeList;
            
    resourceTagSetItemTypeList = new ArrayList<ResourceTagSetItemType>();
            
    resourceTagSetType = new ResourceTagSetType();
    resourceTagSetType.getItem()
    this.tagSet = instance.getTags();
    this.hypervisor = instance.get*/
}

From source file:com.axemblr.provisionr.amazon.activities.PublishListOfMachines.java

License:Apache License

@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws Exception {
    @SuppressWarnings("unchecked")
    List<String> instanceIds = (List<String>) execution.getVariable(ProcessVariables.INSTANCE_IDS);
    checkNotNull(instanceIds, "%s not found as a process variable", ProcessVariables.INSTANCE_IDS);

    LOG.info(">> Describing instances {}", instanceIds);
    DescribeInstancesResult result = client
            .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceIds));
    checkArgument(result.getReservations().size() == 1, "found more than one reservation");

    Reservation reservation = result.getReservations().get(0);
    LOG.info("<< Got one reservation with {} running instances", reservation.getInstances().size());

    List<Machine> machines = Lists.transform(reservation.getInstances(), new Function<Instance, Machine>() {
        @Override// ww w . ja v a2 s  .  c  om
        public Machine apply(Instance instance) {
            return Machine.builder().externalId(instance.getInstanceId())
                    .publicDnsName(instance.getPublicDnsName()).publicIp(instance.getPublicIpAddress())
                    .privateDnsName(instance.getPrivateDnsName()).privateIp(instance.getPrivateIpAddress())
                    .createMachine();
        }
    });

    /* Create a new ArrayList to force evaluation for lazy collections */
    execution.setVariable(CoreProcessVariables.MACHINES, Lists.newArrayList(machines));
}

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

License:Apache License

private String getPrivateHostName(String instanceID, String accessKeyId, String secretKey,
        String instanceRegion) {//from ww w  . j a v a2s. c om
    String privateHostName = null;
    BasicAWSCredentials cred = new BasicAWSCredentials(accessKeyId, secretKey);
    AmazonEC2Client ec2Client = new AmazonEC2Client(cred);
    try {
        ec2Client.setRegion(Region.getRegion(Regions.fromName(instanceRegion)));
        ArrayList<String> instanceIds = new ArrayList<String>();
        instanceIds.add(instanceID);
        DescribeInstancesRequest req = new DescribeInstancesRequest();
        req.setInstanceIds(instanceIds);
        DescribeInstancesResult result = ec2Client.describeInstances(req);
        Instance instance = result.getReservations().get(0).getInstances().get(0);
        privateHostName = instance.getPrivateDnsName();
    } catch (AmazonServiceException amazonServiceException) {
        logger.info("Error while fecthing instance info from aws " + amazonServiceException.getMessage());
    } catch (Exception exception) {
        logger.info("Error while fecthing instance info from aws " + exception.getMessage());
    }
    return privateHostName;

}

From source file:com.clouck.model.aws.ec2.Ec2Instance.java

@Override
@SuppressWarnings("rawtypes")
protected boolean isEqual(AbstractResource newResource) {
    Instance oldInstance = this.getResource();
    Ec2Instance newEc2Instance = (Ec2Instance) newResource;
    Instance newInstance = newEc2Instance.getResource();

    if (notEqual(oldInstance.getInstanceId(), newInstance.getInstanceId()))
        return false;
    if (notEqual(oldInstance.getImageId(), newInstance.getImageId()))
        return false;
    if (notEqual(oldInstance.getState(), newInstance.getState()))
        return false;
    if (notEqual(oldInstance.getPrivateDnsName(), newInstance.getPrivateDnsName()))
        return false;
    if (notEqual(oldInstance.getPublicDnsName(), newInstance.getPublicDnsName()))
        return false;
    if (notEqual(oldInstance.getStateTransitionReason(), newInstance.getStateTransitionReason()))
        return false;
    if (notEqual(oldInstance.getKeyName(), newInstance.getKeyName()))
        return false;
    if (notEqual(oldInstance.getAmiLaunchIndex(), newInstance.getAmiLaunchIndex()))
        return false;
    if (notEqualCollection(oldInstance.getProductCodes(), newInstance.getProductCodes()))
        return false;
    if (notEqual(oldInstance.getInstanceType(), newInstance.getInstanceType()))
        return false;
    if (notEqual(oldInstance.getLaunchTime(), newInstance.getLaunchTime()))
        return false;
    if (notEqual(oldInstance.getPlacement(), newInstance.getPlacement()))
        return false;
    if (notEqual(oldInstance.getKernelId(), newInstance.getKernelId()))
        return false;
    if (notEqual(oldInstance.getRamdiskId(), newInstance.getRamdiskId()))
        return false;
    if (notEqual(oldInstance.getPlatform(), newInstance.getPlatform()))
        return false;
    if (notEqual(oldInstance.getMonitoring(), newInstance.getMonitoring()))
        return false;
    if (notEqual(oldInstance.getSubnetId(), newInstance.getSubnetId()))
        return false;
    if (notEqual(oldInstance.getVpcId(), newInstance.getVpcId()))
        return false;
    if (notEqual(oldInstance.getPrivateIpAddress(), newInstance.getPrivateIpAddress()))
        return false;
    if (notEqual(oldInstance.getPublicIpAddress(), newInstance.getPublicIpAddress()))
        return false;
    if (notEqual(oldInstance.getStateReason(), newInstance.getStateReason()))
        return false;
    if (notEqual(oldInstance.getArchitecture(), newInstance.getArchitecture()))
        return false;
    if (notEqual(oldInstance.getRootDeviceType(), newInstance.getRootDeviceType()))
        return false;
    if (notEqual(oldInstance.getRootDeviceName(), newInstance.getRootDeviceName()))
        return false;
    if (notEqualCollection(oldInstance.getBlockDeviceMappings(), newInstance.getBlockDeviceMappings()))
        return false;
    if (notEqual(oldInstance.getVirtualizationType(), newInstance.getVirtualizationType()))
        return false;
    if (notEqual(oldInstance.getInstanceLifecycle(), newInstance.getInstanceLifecycle()))
        return false;
    if (notEqual(oldInstance.getSpotInstanceRequestId(), newInstance.getSpotInstanceRequestId()))
        return false;
    if (notEqual(oldInstance.getLicense(), newInstance.getLicense()))
        return false;
    if (notEqual(oldInstance.getClientToken(), newInstance.getClientToken()))
        return false;
    if (notEqualCollection(oldInstance.getTags(), newInstance.getTags()))
        return false;
    if (notEqualCollection(oldInstance.getSecurityGroups(), newInstance.getSecurityGroups()))
        return false;
    if (notEqual(oldInstance.getSourceDestCheck(), newInstance.getSourceDestCheck()))
        return false;
    if (notEqual(oldInstance.getHypervisor(), newInstance.getHypervisor()))
        return false;
    if (notEqualNetworkInterfaces(oldInstance.getNetworkInterfaces(), newInstance.getNetworkInterfaces()))
        return false;
    if (notEqual(oldInstance.getIamInstanceProfile(), newInstance.getIamInstanceProfile()))
        return false;
    if (notEqual(oldInstance.getEbsOptimized(), newInstance.getEbsOptimized()))
        return false;
    if (notEqual(this.getTerminationProtection(), newEc2Instance.getTerminationProtection()))
        return false;
    if (notEqual(this.getShutdownBehavior(), newEc2Instance.getShutdownBehavior()))
        return false;
    if (notEqual(this.getUserData(), newEc2Instance.getUserData()))
        return false;

    return true;//from  w  w  w.j  a  v  a 2 s .c o  m
}

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  ww  .j a  v a  2 s  . com*/

    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.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.EC2InstanceDetail.java

License:Open Source License

private void buildUI(DescribeInstancesResult detail) {

    JTabbedPane tabs = new JTabbedPane();
    tabs.add("Instance", primaryScrollPane);
    tabs.add("Tags", tagsScrollPane);

    this.add(tabs, BorderLayout.CENTER);

    List<Reservation> reservations = detail.getReservations();
    if (!reservations.isEmpty()) {

        Reservation reservation = reservations.get(0);
        List<Instance> instances = reservation.getInstances();
        if (!instances.isEmpty()) {

            Instance instance = instances.get(0);

            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "AMI Launch Index", instance.getAmiLaunchIndex() });
            }/*from   w  w  w  .  jav  a2  s .  c  o  m*/
            if (instance.getArchitecture() != null) {
                primaryTableModel.addRow(new Object[] { "Architecture", instance.getArchitecture() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Block Mapping Device", "" });
            }
            if (instance.getClientToken() != null) {
                primaryTableModel.addRow(new Object[] { "Client Token", instance.getClientToken() });
            }
            primaryTableModel.addRow(new Object[] { "EBS Optimised", instance.isEbsOptimized() });
            if (instance.getHypervisor() != null) {
                primaryTableModel.addRow(new Object[] { "Hypervisor", instance.getHypervisor() });
            }
            if (instance.getIamInstanceProfile() != null) {
                primaryTableModel.addRow(
                        new Object[] { "Instance Profile", instance.getIamInstanceProfile().toString() });
            }
            if (instance.getImageId() != null) {
                primaryTableModel.addRow(new Object[] { "Image Id", instance.getImageId() });
            }
            if (instance.getInstanceId() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Id", instance.getInstanceId() });
            }
            if (instance.getInstanceLifecycle() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Lifecyle", instance.getInstanceLifecycle() });
            }
            if (instance.getInstanceType() != null) {
                primaryTableModel.addRow(new Object[] { "Instance Type", instance.getInstanceType() });
            }
            if (instance.getKernelId() != null) {
                primaryTableModel.addRow(new Object[] { "Kernel Id", instance.getKernelId() });
            }
            if (instance.getKeyName() != null) {
                primaryTableModel.addRow(new Object[] { "Key Name", instance.getKeyName() });
            }
            if (instance.getLaunchTime() != null) {
                primaryTableModel.addRow(new Object[] { "Launch Time", instance.getLaunchTime() });
            }
            if (instance.getMonitoring() != null) {
                primaryTableModel.addRow(new Object[] { "Monitoring", instance.getMonitoring().toString() });
            }
            if (instance.getPlacement() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Placement", instance.getPlacement().getAvailabilityZone() });
            }
            if (instance.getPlatform() != null) {
                primaryTableModel.addRow(new Object[] { "Platform", instance.getPlatform() });
            }
            if (instance.getPrivateDnsName() != null) {
                primaryTableModel.addRow(new Object[] { "Private DNS Name", instance.getPrivateDnsName() });
            }
            if (instance.getPrivateIpAddress() != null) {
                primaryTableModel.addRow(new Object[] { "Private IP Address", instance.getPrivateIpAddress() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Product Codes", "" });
            }
            if (instance.getPublicDnsName() != null) {
                primaryTableModel.addRow(new Object[] { "Public DNS Name", instance.getPublicDnsName() });
            }
            if (instance.getPublicIpAddress() != null) {
                primaryTableModel.addRow(new Object[] { "Public IP Address", instance.getPublicIpAddress() });
            }
            if (instance.getRamdiskId() != null) {
                primaryTableModel.addRow(new Object[] { "Ram Disk Id", instance.getRamdiskId() });
            }
            if (instance.getRootDeviceName() != null) {
                primaryTableModel.addRow(new Object[] { "Root Device Name", instance.getRootDeviceName() });
            }
            if (instance.getRootDeviceType() != null) {
                primaryTableModel.addRow(new Object[] { "Root Device Type", instance.getRootDeviceType() });
            }
            if (instance.getAmiLaunchIndex() != null) {
                primaryTableModel.addRow(new Object[] { "Security Groups", "" });
            }
            if (instance.getSourceDestCheck() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Source Destination Check", instance.getSourceDestCheck() });
            }
            if (instance.getSpotInstanceRequestId() != null) {
                primaryTableModel.addRow(
                        new Object[] { "Spot Instance Request Id", instance.getSpotInstanceRequestId() });
            }
            if (instance.getSriovNetSupport() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Sriov network Support", instance.getSriovNetSupport() });
            }
            if (instance.getState() != null) {
                primaryTableModel.addRow(new Object[] { "State", instance.getState().getName() });
            }
            if (instance.getStateReason() != null) {
                primaryTableModel
                        .addRow(new Object[] { "State Reason", instance.getStateReason().getMessage() });
            }
            if (instance.getSubnetId() != null) {
                primaryTableModel.addRow(new Object[] { "Subnet Id", instance.getSubnetId() });
            }
            if (instance.getVirtualizationType() != null) {
                primaryTableModel
                        .addRow(new Object[] { "Virtualisation Type", instance.getVirtualizationType() });
            }
            if (instance.getVpcId() != null) {
                primaryTableModel.addRow(new Object[] { "Vpc Id", instance.getVpcId() });
            }

            List<Tag> tags = instance.getTags();
            for (Tag tag : tags) {
                tagsTableModel.addRow(new Object[] { tag.getKey(), tag.getValue() });
            }
        }
    }
}

From source file:com.intuit.tank.vmManager.environment.amazon.AmazonDataConverter.java

License:Open Source License

/**
 * @param data/* w  w  w.  ja  v a2  s  .c  o m*/
 * @param instance
 * @param region
 * @return
 */
public VMInformation instanceToVmInformation(Reservation data, Instance instance, VMRegion region) {
    VMInformation info = new VMInformation();
    info.setProvider(VMProvider.Amazon);
    info.setRequestId(data.getRequesterId());
    info.setImageId(instance.getImageId());
    info.setInstanceId(instance.getInstanceId());
    info.setKeyName(instance.getKeyName());
    // info.setLaunchTime();
    info.setRegion(region);
    info.setPlatform(instance.getPlatform());
    info.setPrivateDNS(instance.getPrivateDnsName());
    info.setPublicDNS(instance.getPublicDnsName());
    info.setState(instance.getState().getName());
    info.setSize(instance.getInstanceType());
    return info;
}

From source file:com.keybox.manage.db.SystemDB.java

License:Apache License

/**
  * HelpMethode to Transform EC2Instanz in HostSystem 
  * //from ww  w.  j  a  va  2  s.  c o  m
  * @param instance EC2Instanz
  * @param ec2Region EC2Region
  * @param awsCrde AWS Credential
  * @return hostSystem
  */
private static HostSystem transformerEC2InstanzToHostSystem(Instance instance, String ec2Region) {
    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.setApplicationKey(PrivateKeyDB.getEC2KeyByNmRegion(instance.getKeyName(), ec2Region));
    hostSystem.setEc2Region(ec2Region);
    hostSystem.setStatusCd(instance.getState().getName().toUpperCase());
    hostSystem.setUser(AppConfig.getProperty("defaultEC2User"));
    for (Tag tag : instance.getTags()) {
        if ("Name".equals(tag.getKey())) {
            hostSystem.setDisplayNm(tag.getValue());
        }
    }
    return hostSystem;
}

From source file:com.kpbird.aws.Main.java

private void createEC2OnDemandInstance() {
    try {// w  w  w .  j  av  a 2s . co  m

        // request for new on demand instance
        RunInstancesRequest rir = new RunInstancesRequest();
        rir.withImageId(imageId);
        rir.withInstanceType(instanceType);
        rir.withMinCount(1);
        rir.withMaxCount(1);
        rir.withKeyName(keyName);
        rir.withMonitoring(true);
        rir.withSecurityGroups(groupName);

        RunInstancesResult riresult = ec2client.runInstances(rir);
        log.Info(riresult.getReservation().getReservationId());

        /// Find newly created instance id
        String instanceId = null;
        DescribeInstancesResult result = ec2client.describeInstances();
        Iterator<Reservation> i = result.getReservations().iterator();
        while (i.hasNext()) {
            Reservation r = i.next();
            List<Instance> instances = r.getInstances();
            for (Instance ii : instances) {
                log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                        + ii.getPrivateDnsName());
                if (ii.getState().getName().equals("pending")) {
                    instanceId = ii.getInstanceId();
                }
            }
        }

        log.Info("New Instance ID :" + instanceId);
        /// Waiting for Instance Running////
        boolean isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting ***");
            Thread.sleep(1000);
            DescribeInstancesResult r = ec2client.describeInstances();
            Iterator<Reservation> ir = r.getReservations().iterator();
            while (ir.hasNext()) {
                Reservation rr = ir.next();
                List<Instance> instances = rr.getInstances();
                for (Instance ii : instances) {
                    log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                            + ii.getPrivateDnsName());
                    if (ii.getState().getName().equals("running") && ii.getInstanceId().equals(instanceId)) {
                        log.Info(ii.getPublicDnsName());
                        isWaiting = false;
                    }
                }
            }
        }

        /// Creating Tag for New Instance ////
        log.Info("Creating Tags for New Instance");
        CreateTagsRequest crt = new CreateTagsRequest();
        ArrayList<Tag> arrTag = new ArrayList<Tag>();
        arrTag.add(new Tag().withKey("Name").withValue(instanceName));
        crt.setTags(arrTag);

        ArrayList<String> arrInstances = new ArrayList<String>();
        arrInstances.add(instanceId);
        crt.setResources(arrInstances);
        ec2client.createTags(crt);

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}

From source file:com.kpbird.aws.Main.java

private void createEC2SpotInstance() {
    try {/*from  w  ww .ja  v a  2 s . co m*/
        /// Creating Spot Instance ////

        // Initializes a Spot Instance Request
        RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
        // Request 1 x t1.micro instance with a bid price of $0.03.
        requestRequest.setSpotPrice(spotPrice);
        requestRequest.setInstanceCount(Integer.valueOf(1));
        LaunchSpecification launchSpecification = new LaunchSpecification();
        launchSpecification.setImageId(imageId);
        launchSpecification.setInstanceType(instanceType);
        launchSpecification.setMonitoringEnabled(true);

        // Add the security group to the request.
        ArrayList<String> securityGroups = new ArrayList<String>();
        securityGroups.add(groupName);
        launchSpecification.setSecurityGroups(securityGroups);

        launchSpecification.setKeyName(keyName);

        // Add the launch specifications to the request.
        requestRequest.setLaunchSpecification(launchSpecification);

        // Call the RequestSpotInstance API.
        RequestSpotInstancesResult requestResult = ec2client.requestSpotInstances(requestRequest);

        List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstanceRequests();

        // Setup an arraylist to collect all of the request ids we want to
        // watch hit the running state.
        ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();

        // Add all of the request ids to the hashset, so we can determine when they hit the
        // active state.
        for (SpotInstanceRequest requestResponse : requestResponses) {
            System.out.println("Created Spot Request: " + requestResponse.getSpotInstanceRequestId());
            spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
            log.Info(requestResponse.getInstanceId() + "\t" + requestResponse.getState());
        }

        String instanceId = null;
        boolean isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting for Spot Instance Request ***");
            Thread.sleep(5000);
            DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
            describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);

            DescribeSpotInstanceRequestsResult describeResult = ec2client
                    .describeSpotInstanceRequests(describeRequest);
            List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
            for (SpotInstanceRequest describeResponse : describeResponses) {
                log.Info(describeResponse.getInstanceId() + "\t" + describeResponse.getState() + "\t"
                        + describeResponse.getSpotInstanceRequestId() + "\t"
                        + describeResponse.getStatus().getCode() + "\t"
                        + describeResponse.getStatus().getMessage());
                if (describeResponse.getState().equals("active")) {
                    isWaiting = false;
                    instanceId = describeResponse.getInstanceId();
                    break;
                }
            }

        }
        isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting for Instance Running ***");
            Thread.sleep(1000);
            DescribeInstancesResult r = ec2client.describeInstances();
            Iterator<Reservation> ir = r.getReservations().iterator();
            while (ir.hasNext()) {
                Reservation rr = ir.next();
                List<Instance> instances = rr.getInstances();
                for (Instance ii : instances) {
                    log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                            + ii.getPrivateDnsName());
                    if (ii.getState().getName().equals("running") && ii.getInstanceId().equals(instanceId)) {
                        log.Info(ii.getPublicDnsName());
                        String publicDNS = ii.getPublicDnsName();
                        log.Info("Public DNS :" + publicDNS);
                        isWaiting = false;
                    }
                }
            }
        }

        /// Creating Tag for New Instance ////
        log.Info("Creating Tags for New Instance");
        CreateTagsRequest crt = new CreateTagsRequest();
        ArrayList<Tag> arrTag = new ArrayList<Tag>();
        arrTag.add(new Tag().withKey("Name").withValue(instanceName));
        crt.setTags(arrTag);

        ArrayList<String> arrInstances = new ArrayList<String>();
        arrInstances.add(instanceId);
        crt.setResources(arrInstances);
        ec2client.createTags(crt);

    } catch (Exception e) {
        e.printStackTrace();
    }
}