Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.amazonaws.samples;
- import java.awt.BorderLayout;
- import java.awt.Dimension;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.List;
- import javax.swing.BorderFactory;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JComboBox;
- import javax.swing.JFileChooser;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JProgressBar;
- import javax.swing.JTextArea;
- import javax.swing.JTextField;
- import com.amazonaws.AmazonClientException;
- import com.amazonaws.AmazonServiceException;
- import com.amazonaws.SdkClientException;
- import com.amazonaws.auth.AWSCredentials;
- import com.amazonaws.auth.AWSStaticCredentialsProvider;
- import com.amazonaws.auth.profile.ProfileCredentialsProvider;
- import com.amazonaws.event.ProgressEvent;
- import com.amazonaws.event.ProgressListener;
- import com.amazonaws.samples.S3TransferProgressSample.ButtonListener;
- import com.amazonaws.services.s3.AmazonS3;
- import com.amazonaws.services.s3.AmazonS3ClientBuilder;
- import com.amazonaws.services.s3.model.Bucket;
- import com.amazonaws.services.s3.model.ListObjectsV2Request;
- import com.amazonaws.services.s3.model.ListObjectsV2Result;
- import com.amazonaws.services.s3.model.ObjectListing;
- import com.amazonaws.services.s3.model.PutObjectRequest;
- import com.amazonaws.services.s3.model.S3Object;
- import com.amazonaws.services.s3.model.S3ObjectInputStream;
- import com.amazonaws.services.s3.model.S3ObjectSummary;
- import com.amazonaws.services.s3.transfer.TransferManager;
- import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
- import com.amazonaws.services.s3.transfer.Upload;
- public class lab2v2 {
- private static AWSCredentials credentials;
- private static TransferManager tx;
- private static AmazonS3 s3;
- private static String bucketName;
- private JPanel leftPanel, rightPanel, row1Panel, row2Panel, row3Panel, row21Panel, row22Panel, row23Panel, row24Panel, row25Panel, mainPanel;
- private JProgressBar progressBar;
- private JFrame frame;
- private Upload upload;
- private JButton clearObjectListBtn, createBucketBtn, listBucketsBtn, listObjectsBtn, uploadBtn, deleteBtn, dowloadBtn, clearBucketListTA;
- private JLabel regionLabel, bucketLabel, bucket2Label;
- private JTextField regionNameTF, bucketNameTF, bucket2NameTF, fileToDeleteTF, fileToDownloadTF;
- private JTextArea bucketList, objectList;
- private JComboBox<String> regionsCB;
- private static String OS = System.getProperty("os.name").toLowerCase();
- private static String desktop_path = "";
- private static long uploadDur;
- private String[] regions = new String[] {
- "eu-central-1",
- "eu-west-1",
- "eu-west-2",
- "eu-west-3",
- "us-east-1",
- "us-east-2",
- "us-west-1",
- "us-west-2",
- "ap-northeast-1",
- "ap-northeast-2",
- "ap-southeast-1",
- "ap-southeast-2",
- "ca-central-1"};
- public static boolean isWindows() {
- return (OS.indexOf("win") >= 0);
- }
- public static boolean isMac() {
- return (OS.indexOf("mac") >= 0);
- }
- public static boolean isUnix() {
- return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
- }
- public static void main(String[] args) throws Exception {
- desktop_path = System.getProperty("user.home") + "/Desktop";
- System.out.println(desktop_path);
- if (isWindows()) {
- System.out.println("This is Windows");
- } else if (isMac()) {
- System.out.println("This is Mac");
- } else if (isUnix()) {
- System.out.println("This is Unix or Linux");
- } else {
- System.out.println("Your OS is not support!!");
- }
- try {
- credentials = new ProfileCredentialsProvider("default").getCredentials();
- }
- catch(Exception e){
- throw new AmazonClientException(
- "Cannot load the credentials from the credential profiles file. " +
- "Please make sure that your credentials file is at the correct " +
- "location (/Users/meru/.aws/credentials), and is in valid format.",
- e);
- }
- s3 = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion("eu-west-2")
- .build();
- tx = TransferManagerBuilder.standard()
- .withS3Client(s3)
- .build();
- bucketName = "s3-upload-sdk-sample-fas-mn";
- new lab2v2();
- }
- public lab2v2() throws Exception {
- frame = new JFrame("Amazon S3 File CRUD");
- //left side
- regionLabel = new JLabel("Region ");
- regionLabel.setPreferredSize(new Dimension(200, 30));
- regionsCB = new JComboBox<>(regions);
- regionsCB.setPreferredSize(new Dimension(200, 30));
- listBucketsBtn = new JButton("List buckets");
- listBucketsBtn.setPreferredSize(new Dimension(200, 30));
- listBucketsBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- bucketList.append("\nGlobal bucket list:\n");
- try {
- for (Bucket bucket : s3.listBuckets()) {
- bucketList.append(" - " + bucket.getName()+ "\n");
- }
- bucketList.append("\n");
- } catch (Exception ace) {
- bucketList.append("ERROR LISTING BUCKETS\n"+ ace.getMessage()+"\n");
- System.out.println("Error Message: " + ace.getMessage());
- }
- }
- });
- bucketLabel = new JLabel(" Bucket name");
- bucketLabel.setPreferredSize(new Dimension(200, 30));
- bucketNameTF = new JTextField();
- bucketNameTF.setPreferredSize(new Dimension(200, 30));
- createBucketBtn = new JButton("Create");
- createBucketBtn.setPreferredSize(new Dimension(200, 30));
- createBucketBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String regionSelected = regionsCB.getSelectedItem().toString();
- AmazonS3 s3local = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(regionSelected)
- .build();
- try {
- bucketName = bucketNameTF.getText();
- if (bucketName.equals("")) {
- JOptionPane.showMessageDialog(frame,
- "Bucketname is invalid or empty",
- "Error creating bucket", JOptionPane.ERROR_MESSAGE);
- } else {
- bucketList.append("Creating bucket " + bucketName + "\n");
- s3local.createBucket(bucketName);
- }
- }
- catch (Exception ace) {
- JOptionPane.showMessageDialog(frame,
- ace.getMessage(),
- "Error creating bucket...", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- clearBucketListTA = new JButton("CLR");
- clearBucketListTA.setPreferredSize(new Dimension(100, 30));
- clearBucketListTA.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- bucketList.setText("");
- }
- });
- bucketList = new JTextArea();
- bucketList.setPreferredSize(new Dimension(600, 700));
- //right side -----------------------------------------
- objectList = new JTextArea();
- objectList.setPreferredSize(new Dimension(600, 650));
- bucket2Label = new JLabel("Bucket name");
- bucket2Label.setPreferredSize(new Dimension(200, 30));
- bucket2NameTF = new JTextField();
- bucket2NameTF.setPreferredSize(new Dimension(200, 30));
- listObjectsBtn = new JButton("List objects");
- listObjectsBtn.setPreferredSize(new Dimension(200, 30));
- listObjectsBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- if (!bucket2NameTF.getText().toString().isEmpty()) {
- String clientRegion = regionsCB.getSelectedItem().toString();
- String bucketName = bucket2NameTF.getText().toString();
- objectList.setText("");
- try {
- AmazonS3 s3Initial = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(clientRegion)
- .build();
- String location = s3Initial.getBucketLocation(bucketName);
- AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(location)
- .build();
- // maxKeys is set to 2 to demonstrate the use of
- // ListObjectsV2Result.getNextContinuationToken()
- ListObjectsV2Request req = new ListObjectsV2Request().withBucketName(bucketName).withMaxKeys(2);
- ListObjectsV2Result result;
- do {
- result = s3Client.listObjectsV2(req);
- for (S3ObjectSummary objectSummary : result.getObjectSummaries()) {
- objectList.append(" - "+objectSummary.getKey()+" (size: "+objectSummary.getSize()+")\n");
- }
- // If there are more than maxKeys keys in the bucket, get a continuation token
- // and list the next objects.
- String token = result.getNextContinuationToken();
- System.out.println("Next Continuation Token: " + token);
- req.setContinuationToken(token);
- } while (result.isTruncated());
- }
- catch(Exception e) {
- // The call was transmitted successfully, but Amazon S3 couldn't process
- // it, so it returned an error response.
- objectList.append(e.getMessage());
- //e.printStackTrace();
- }
- } else {
- JOptionPane.showMessageDialog(frame,
- "Bucketname is invalid or empty!",
- "Error fetching bucket contents.", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- clearObjectListBtn = new JButton("CLR");
- clearObjectListBtn.setPreferredSize(new Dimension(200, 30));
- clearObjectListBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- objectList.setText("");
- }
- });
- uploadBtn = new JButton("Choose & Upload...");
- uploadBtn.addActionListener(new ButtonListener());
- uploadBtn.setPreferredSize(new Dimension(200, 30));
- progressBar = new JProgressBar(0, 100);
- progressBar.setStringPainted(true);
- progressBar.setPreferredSize(new Dimension(200, 30));
- fileToDownloadTF = new JTextField();
- fileToDownloadTF.setPreferredSize(new Dimension(200, 30));
- dowloadBtn = new JButton("Download");
- dowloadBtn.setPreferredSize(new Dimension(200, 30));
- dowloadBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- if (!fileToDownloadTF.getText().isEmpty() && !bucket2NameTF.getText().isEmpty()) {
- String clientRegion = regionsCB.getSelectedItem().toString();
- String bucketName = bucket2NameTF.getText().toString();
- AmazonS3 s3Initial = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(clientRegion)
- .build();
- String location = s3Initial.getBucketLocation(bucketName);
- AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(location)
- .build();
- String key_name = fileToDownloadTF.getText().toString();
- long duration = 0;
- System.out.format("Downloading %s from S3 bucket %s...\n", key_name, bucketName);
- try {
- long startTime = System.nanoTime();
- //////////MEASURE TIME//////////
- S3Object o = s3Client.getObject(bucketName, key_name);
- S3ObjectInputStream s3is = o.getObjectContent();
- String[] parts = key_name.split("/");
- if (key_name.contains("/")) {
- key_name = parts[parts.length-1];
- }
- FileOutputStream fos = new FileOutputStream(new File(desktop_path+"/"+key_name));
- byte[] read_buf = new byte[1024];
- int read_len = 0;
- while ((read_len = s3is.read(read_buf)) > 0) {
- fos.write(read_buf, 0, read_len);
- }
- ////////////////////////////////
- long endTime = System.nanoTime();
- duration = (endTime - startTime); //divide by 1000000 to get millisecond
- objectList.append("\nFetching "+key_name+" from bucket "+bucketName+" in "+location+" took: " + duration/1000000 + "ms");
- s3is.close();
- fos.close();
- } catch (Exception e) {
- JOptionPane.showMessageDialog(frame,
- "ERROR: "+e.getMessage(),
- "Error downloading File", JOptionPane.ERROR_MESSAGE);
- return;
- }
- } else {
- JOptionPane.showMessageDialog(frame,
- "Filename is invalid or empty",
- "Error downloading File", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- fileToDeleteTF = new JTextField();
- fileToDeleteTF.setPreferredSize(new Dimension(200, 30));
- deleteBtn = new JButton("Delete");
- deleteBtn.setPreferredSize(new Dimension(200, 30));
- deleteBtn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- if (!fileToDeleteTF.getText().isEmpty() && !bucket2NameTF.getText().isEmpty()) {
- String clientRegion = regionsCB.getSelectedItem().toString();
- String bucketName = bucket2NameTF.getText().toString();
- String key_name = fileToDeleteTF.getText().toString();
- AmazonS3 s3Initial = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(clientRegion)
- .build();
- String location = s3Initial.getBucketLocation(bucketName);
- AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(location)
- .build();
- try {
- s3Client.deleteObject(bucketName, key_name);
- } catch (AmazonServiceException e) {
- System.err.println(e.getErrorMessage());
- System.exit(1);
- }
- JOptionPane.showMessageDialog(frame,
- "File deleted successfully!",
- "Finished", JOptionPane.INFORMATION_MESSAGE);
- } else {
- JOptionPane.showMessageDialog(frame,
- "Filename is invalid or empty",
- "Error deleting File", JOptionPane.ERROR_MESSAGE);
- }
- }
- });
- frame.setContentPane(createContentPane());
- frame.pack();
- frame.setVisible(true);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- class ButtonListener implements ActionListener {
- public void actionPerformed(ActionEvent ae) {
- String clientRegion = regionsCB.getSelectedItem().toString();
- String bucketName2 = bucket2NameTF.getText().toString();
- AmazonS3 s3Initial = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(clientRegion)
- .build();
- String location = s3Initial.getBucketLocation(bucketName2);
- AmazonS3 s3client = AmazonS3ClientBuilder.standard()
- .withCredentials(new AWSStaticCredentialsProvider(credentials))
- .withRegion(location)
- .build();
- TransferManager txclient = TransferManagerBuilder.standard()
- .withS3Client(s3client)
- .build();
- JFileChooser fileChooser = new JFileChooser();
- int showOpenDialog = fileChooser.showOpenDialog(frame);
- if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;
- File fileToUpload = fileChooser.getSelectedFile();
- createAmazonS3Bucket();
- long startTime = System.nanoTime();
- ProgressListener progressListener = new ProgressListener() {
- public void progressChanged(ProgressEvent progressEvent) {
- if (upload == null) return;
- progressBar.setValue((int)upload.getProgress().getPercentTransferred());
- switch (progressEvent.getEventCode()) {
- case ProgressEvent.COMPLETED_EVENT_CODE:
- progressBar.setValue(100);
- long endTime = System.nanoTime();
- uploadDur = (endTime - startTime); //divide by 1000000 to get millisecond
- objectList.append("\nSending "+fileToUpload.getName()+" to bucket"+bucketName2+" in "+location+" took "+uploadDur/1000000+"ms");
- break;
- case ProgressEvent.FAILED_EVENT_CODE:
- try {
- AmazonClientException e = upload.waitForException();
- JOptionPane.showMessageDialog(frame,
- "Unable to upload file to Amazon S3: " + e.getMessage(),
- "Error Uploading File", JOptionPane.ERROR_MESSAGE);
- } catch (InterruptedException e) {}
- break;
- }
- }
- };
- PutObjectRequest request = new PutObjectRequest(
- bucketName2,
- fileToUpload.getName(),
- fileToUpload).withGeneralProgressListener(progressListener);
- upload = txclient.upload(request);
- }
- }
- private void createAmazonS3Bucket() {
- try {
- if (tx.getAmazonS3Client().doesBucketExist(bucketName) == false) {
- tx.getAmazonS3Client().createBucket(bucketName);
- }
- } catch (AmazonClientException ace) {
- JOptionPane.showMessageDialog(frame, "Unable to create a new Amazon S3 bucket: " + ace.getMessage(),
- "Error Creating Bucket", JOptionPane.ERROR_MESSAGE);
- }
- }
- private JPanel createContentPane() {
- leftPanel = new JPanel();
- BoxLayout boxlayoutY = new BoxLayout(leftPanel, BoxLayout.Y_AXIS);
- leftPanel.setLayout(boxlayoutY);
- row1Panel = new JPanel();
- BoxLayout boxlayoutX = new BoxLayout(row1Panel, BoxLayout.X_AXIS);
- row1Panel.setLayout(boxlayoutX);
- row1Panel.add(regionLabel);
- row1Panel.add(bucketLabel);
- row2Panel = new JPanel();
- BoxLayout boxlayoutX2 = new BoxLayout(row2Panel, BoxLayout.X_AXIS);
- row2Panel.setLayout(boxlayoutX2);
- row2Panel.add(regionsCB);
- row2Panel.add(bucketNameTF);
- row3Panel = new JPanel();
- BoxLayout boxlayoutX3 = new BoxLayout(row3Panel, BoxLayout.X_AXIS);
- row3Panel.setLayout(boxlayoutX3);
- row3Panel.add(listBucketsBtn);
- row3Panel.add(createBucketBtn);
- row3Panel.add(clearBucketListTA);
- leftPanel.add(row1Panel);
- leftPanel.add(row2Panel);
- leftPanel.add(row3Panel);
- leftPanel.add(bucketList);
- leftPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
- leftPanel.setPreferredSize(new Dimension(650, 800));
- rightPanel = new JPanel();
- BoxLayout boxlayoutY2 = new BoxLayout(rightPanel, BoxLayout.Y_AXIS);
- rightPanel.setLayout(boxlayoutY2);
- row21Panel = new JPanel();
- BoxLayout boxlayoutX21 = new BoxLayout(row21Panel, BoxLayout.X_AXIS);
- row21Panel.setLayout(boxlayoutX21);
- row21Panel.add(bucket2NameTF);
- row21Panel.add(listObjectsBtn);
- row21Panel.add(clearObjectListBtn);
- row22Panel = new JPanel();
- BoxLayout boxlayoutX22 = new BoxLayout(row22Panel, BoxLayout.X_AXIS);
- row22Panel.setLayout(boxlayoutX22);
- row22Panel.add(uploadBtn);
- row22Panel.add(progressBar);
- row23Panel = new JPanel();
- BoxLayout boxlayoutX23 = new BoxLayout(row23Panel, BoxLayout.X_AXIS);
- row23Panel.setLayout(boxlayoutX23);
- row23Panel.add(fileToDownloadTF);
- row23Panel.add(dowloadBtn);
- row24Panel = new JPanel();
- BoxLayout boxlayoutX24 = new BoxLayout(row24Panel, BoxLayout.X_AXIS);
- row24Panel.setLayout(boxlayoutX24);
- row24Panel.add(fileToDownloadTF);
- row24Panel.add(dowloadBtn);
- row25Panel = new JPanel();
- BoxLayout boxlayoutX25 = new BoxLayout(row25Panel, BoxLayout.X_AXIS);
- row25Panel.setLayout(boxlayoutX25);
- row25Panel.add(fileToDeleteTF);
- row25Panel.add(deleteBtn);
- rightPanel.add(bucket2Label);
- rightPanel.add(row21Panel);
- rightPanel.add(objectList);
- rightPanel.add(row22Panel);
- rightPanel.add(row23Panel);
- rightPanel.add(row24Panel);
- rightPanel.add(row25Panel);
- rightPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
- rightPanel.setPreferredSize(new Dimension(650, 800));
- mainPanel = new JPanel();
- BoxLayout boxlayoutXmain = new BoxLayout(mainPanel, BoxLayout.X_AXIS);
- mainPanel.setLayout(boxlayoutXmain);
- mainPanel.add(leftPanel);
- mainPanel.add(rightPanel);
- // JPanel borderPanel = new JPanel();
- // borderPanel.setLayout(new BorderLayout());
- // borderPanel.add(leftPanel, BorderLayout.EAST);
- mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
- return mainPanel;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement