Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author alex */ import java.util.ArrayList; import java.util.List; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.RegionUtils; import com.amazonaws.regions.Regions; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest; import com.amazonaws.services.ec2.model.CreateTagsRequest; import com.amazonaws.services.ec2.model.DescribeImagesResult; import com.amazonaws.services.ec2.model.DescribeInstanceStatusRequest; import com.amazonaws.services.ec2.model.DescribeInstanceStatusResult; import com.amazonaws.services.ec2.model.DescribeInstancesRequest; import com.amazonaws.services.ec2.model.DescribeInstancesResult; import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest; import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult; import com.amazonaws.services.ec2.model.Image; import com.amazonaws.services.ec2.model.Instance; import com.amazonaws.services.ec2.model.InstancePrivateIpAddress; import com.amazonaws.services.ec2.model.InstanceState; import com.amazonaws.services.ec2.model.InstanceStatus; import com.amazonaws.services.ec2.model.LaunchSpecification; import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest; import com.amazonaws.services.ec2.model.RequestSpotInstancesResult; import com.amazonaws.services.ec2.model.Reservation; import com.amazonaws.services.ec2.model.RunInstancesRequest; import com.amazonaws.services.ec2.model.RunInstancesResult; import com.amazonaws.services.ec2.model.SpotInstanceRequest; import com.amazonaws.services.ec2.model.StartInstancesRequest; import com.amazonaws.services.ec2.model.StopInstancesRequest; import com.amazonaws.services.ec2.model.Tag; import java.io.IOException; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author alex */ public class AWS extends javax.swing.JFrame { static AmazonEC2Client ec2client; static String ID; static DescribeInstancesResult describeInstancesRequest; static List<Reservation> reservations; static Set<Instance> instances; /** * Creates new form main */ public AWS() { AWSCredentials credentials = new ProfileCredentialsProvider().getCredentials(); String endPoint; Region region; endPoint = "https://ec2.eu-west-1.amazonaws.com"; region = Region.getRegion(Regions.EU_WEST_1); ec2client = new AmazonEC2Client(credentials); ec2client.setEndpoint(endPoint); ec2client.setRegion(region); initComponents(); } public void fetchInstanceInfo(String ID) { String instanceIDs = ID; DescribeInstancesRequest request = new DescribeInstancesRequest().withInstanceIds(instanceIDs); DescribeInstancesResult result = ec2client.describeInstances(request); List<Reservation> list = result.getReservations(); list.stream().map((res) -> res.getInstances()).forEach((instanceList) -> { instanceList.stream().map((instance) -> { jTextArea1.setText("ID : " + instance.getInstanceId() + "\n"); jTextArea1.append("Public IP : " + instance.getPublicIpAddress() + "\n"); jTextArea1.append("Private IP : " + instance.getPrivateIpAddress() + "\n"); return instance; }).map((instance) -> { jTextArea1.append("Public DNS : " + instance.getPublicDnsName() + "\n"); jTextArea1.append("Private DNS : " + instance.getPrivateDnsName() + "\n"); return instance; }).map((instance) -> { jTextArea1.append("State : " + instance.getState().getName() + "\n"); return instance; }).forEach((instance) -> { jTextArea1.append("TAGS : " + instance.getTags().get(0).getValue() + "\n"); }); }); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFrame1 = new javax.swing.JFrame(); jFrame2 = new javax.swing.JFrame(); jFrame3 = new javax.swing.JFrame(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup(jFrame1Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE)); jFrame1Layout.setVerticalGroup(jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE)); javax.swing.GroupLayout jFrame2Layout = new javax.swing.GroupLayout(jFrame2.getContentPane()); jFrame2.getContentPane().setLayout(jFrame2Layout); jFrame2Layout.setHorizontalGroup(jFrame2Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE)); jFrame2Layout.setVerticalGroup(jFrame2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE)); javax.swing.GroupLayout jFrame3Layout = new javax.swing.GroupLayout(jFrame3.getContentPane()); jFrame3.getContentPane().setLayout(jFrame3Layout); jFrame3Layout.setHorizontalGroup(jFrame3Layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 400, Short.MAX_VALUE)); jFrame3Layout.setVerticalGroup(jFrame3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE)); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setResizable(false); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jLabel1.setText("ID Instance"); jTextArea1.setEditable(false); jTextArea1.setBackground(new java.awt.Color(51, 51, 51)); jTextArea1.setColumns(20); jTextArea1.setFont(new java.awt.Font("Candara", 1, 12)); // NOI18N jTextArea1.setForeground(new java.awt.Color(0, 255, 51)); jTextArea1.setRows(5); jTextArea1.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { jTextArea1KeyPressed(evt); } }); jScrollPane1.setViewportView(jTextArea1); jButton1.setText("Get Information"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Start"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Shutdown"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("New Instance"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED).addComponent( jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addGap(21, 21, 21).addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 496, Short.MAX_VALUE) .addGap(10, 10, 10))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18).addComponent(jButton1).addGap(18, 18, 18).addComponent(jButton2) .addGap(18, 18, 18).addComponent(jButton3).addGap(22, 22, 22).addComponent(jButton4) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout .createSequentialGroup().addContainerGap().addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: AWS.ID = jTextField1.getText(); fetchInstanceInfo(AWS.ID); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed List<String> instancesToStart = new ArrayList<>(); AWS.ID = jTextField1.getText(); instancesToStart.add(AWS.ID); StartInstancesRequest startIR = new StartInstancesRequest(instancesToStart); ec2client.startInstances(startIR); jTextArea1.setText(AWS.ID + " is starting up."); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: List<String> instancesToStop = new ArrayList<>(); AWS.ID = jTextField1.getText(); //shutdown instance instancesToStop.add(AWS.ID); StopInstancesRequest stoptr = new StopInstancesRequest(instancesToStop); ec2client.stopInstances(stoptr); jTextArea1.setText(AWS.ID + " is shutting down."); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: // Group handealing List<String> groupID = new ArrayList<String>(); String Temp_Group = "sg-aa5efdcf"; groupID.add(Temp_Group);//wait to out our instance into this group System.out.println("#5 Create an Instance"); String imageId = "ami-08be1f7f";// int minInstanceCount = 1; // create 1 instance int maxInstanceCount = 1; RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.setInstanceType("t2.micro"); rir.setKeyName("14_LP1_KEY_D7001D_aledem-4");// give the instance the key we just created // rir.setSecurityGroups(groupName);// set the instance in the group we just created rir.setSecurityGroupIds(groupID); rir.setSubnetId("subnet-47ca2d1e"); RunInstancesResult result = ec2client.runInstances(rir); /***********to make sure the instance's state is "running instead of "pending",**********/ /***********we wait for a while **********/ System.out.println("waiting"); try { Thread.currentThread().sleep(60000); } catch (InterruptedException ex) { Logger.getLogger(AWS.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("OK"); List<Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); String createdInstanceIp = ins.getPublicDnsName(); System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID } System.out.println("#6 Create a 'tag' for the new instance."); List<String> resources = new LinkedList<>(); List<Tag> tags = new LinkedList<>(); Tag nameTag = new Tag("Name", "FromCoordinator"); resources.add(createdInstanceId); tags.add(nameTag); CreateTagsRequest ctr = new CreateTagsRequest(resources, tags); ec2client.createTags(ctr); fetchInstanceInfo(createdInstanceId); }//GEN-LAST:event_jButton4ActionPerformed private void jTextArea1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextArea1KeyPressed // TODO add your handling code here: }//GEN-LAST:event_jTextArea1KeyPressed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AWS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AWS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AWS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AWS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AWS().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JFrame jFrame1; private javax.swing.JFrame jFrame2; private javax.swing.JFrame jFrame3; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }