Example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

List of usage examples for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth BasicAWSCredentials BasicAWSCredentials.

Prototype

public BasicAWSCredentials(String accessKey, String secretKey) 

Source Link

Document

Constructs a new BasicAWSCredentials object, with the specified AWS access key and AWS secret key.

Usage

From source file:com.brianmcmichael.sagu.SimpleGlacierUploader.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {

    String accessString = getAccessField();
    String secretString = getSecretField();
    String vaultString = getVaultField();
    int regionInt = getServerRegion();

    if (e.getSource() == newVaultButton && checkAWSFields()) {
        AmazonGlacierClient newVaultClient = makeClient(accessString, secretString, regionInt);
        AddVaultFrame avf = new AddVaultFrame(newVaultClient, regionInt);
        avf.setVisible(true);//w  ww .ja va2 s. c  o  m
    }
    if (e.getSource() == vaultSelector) {
        if (vaultSelector.getSelectedItem() != null) {
            if (vaultSelector.getSelectedIndex() == 0) {
                vaultField.setText("");
            } else {
                vaultField.setText(vaultSelector.getSelectedItem().toString());
            }
        }
    }
    if (e.getSource() == loginButton) {
        repopulateVaults(accessString, secretString);
    }
    if (e.getSource() == exitApplicationMnu) {
        System.exit(0);
    }
    if (e.getSource() == updateMnu || e.getSource() == checkUpdateButton) {
        JHyperlinkLabel.OpenURI(URL_STRING);
    }
    if (e.getSource() == saveFileMnu) {
        FileDialog fd = new FileDialog(new Frame(), "Save...", FileDialog.SAVE);
        fd.setFile("Glacier.txt");
        fd.setDirectory(curDir);
        fd.setLocation(50, 50);
        fd.setVisible(true);
        String filePath = "" + fd.getDirectory() + System.getProperty("file.separator") + fd.getFile();

        File outFile = new File(filePath);

        if (!outFile.equals("") && !outFile.equals("null")) {

            try {
                FileReader fr = new FileReader(getLogFilenamePath(0));
                BufferedReader br = new BufferedReader(fr);

                FileWriter saveFile = new FileWriter(outFile.toString());

                int count = 0;
                boolean moreLines = true;

                String ln1;
                String ln2;
                String ln3;

                while (moreLines) {
                    ln1 = br.readLine();
                    ln2 = br.readLine();
                    ln3 = br.readLine();

                    if (ln1 == null) {
                        ln1 = "";
                    }
                    if (ln2 == null) {
                        ln2 = "";
                    }
                    if (ln3 == null) {
                        ln3 = "";
                    }

                    saveFile.write(ln1);
                    saveFile.write("\r\n");
                    saveFile.write(ln2);
                    saveFile.write("\r\n");
                    saveFile.write(ln3);
                    saveFile.write("\r\n");

                    count++;

                    if (ln3.equals("")) {
                        moreLines = false;
                        br.close();
                        saveFile.close();
                        JOptionPane.showMessageDialog(null,
                                "Successfully exported " + count + " archive records to " + outFile.toString(),
                                "Export", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            } catch (FileNotFoundException e1) {
                JOptionPane.showMessageDialog(null, "Unable to locate Glacier.log", "Error",
                        JOptionPane.ERROR_MESSAGE);
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    if (e.getSource() == viewLog || e.getSource() == logButton) {
        File f = SimpleGlacierUploader.getLogFilenamePath(getLogFileType());
        if (f.exists()) {
            JHyperlinkLabel.OpenURI("" + f.toURI());
        } else {
            JOptionPane.showMessageDialog(null, "Log file " + f.getName() + " does not exist.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
    if (e.getSource() == deleteArchiveMnu) {
        if (checkAllFields()) {
            AmazonGlacierClient newDeleteClient = makeClient(accessString, secretString, regionInt);
            DeleteArchiveFrame daf = new DeleteArchiveFrame(newDeleteClient, vaultString, regionInt);
            daf.setVisible(true);
        }
    }
    if (e.getSource() == inventoryRequestButton) {
        if (checkAllFields()) {
            AmazonGlacierClient newInventoryClient = makeClient(accessString, secretString, regionInt);
            InventoryRequest ir = new InventoryRequest(newInventoryClient, vaultString, regionInt);
            ir.setVisible(true);
        }
    }
    if (e.getSource() == downloadRequestButton || e.getSource() == downloadFileMnu) {
        if (checkAllFields()) {
            AmazonGlacierClient newDownloadClient = makeClient(accessString, secretString, regionInt);
            BasicAWSCredentials credentials = new BasicAWSCredentials(accessString, secretString);
            AmazonDownloadRequest adr = new AmazonDownloadRequest(newDownloadClient, vaultString, regionInt,
                    credentials);
            adr.setVisible(true);
        }
    }

    if (e.getSource() == aboutMnu) {
        JOptionPane.showMessageDialog(null, ABOUT_WINDOW_STRING, "About", JOptionPane.INFORMATION_MESSAGE);
    }

    if (e.getSource() == clearButton) {
        ddText.setText("");
        uploadButton.setText("Select Files");
        multiFiles = null;
    }

    if (e.getSource() == locationChoice) {
        repopulateVaults(accessString, secretString);
    }

    if (e.getSource() == selectFileButton) {
        int returnVal = fc.showOpenDialog(SimpleGlacierUploader.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (fc.getSelectedFile().isFile()) {
                File[] thisFile = new File[1];
                thisFile[0] = fc.getSelectedFile();
                try {
                    ddText.append(thisFile[0].getCanonicalPath() + "\n");
                } catch (java.io.IOException f) {
                }
                if (multiFiles != null) {
                    multiFiles = concatFileArray(multiFiles, thisFile);
                } else {
                    multiFiles = thisFile;
                }
            } else {
                JOptionPane.showMessageDialog(null, NO_DIRECTORIES_ERROR, "Error", JOptionPane.ERROR_MESSAGE);
            }
        }

    }

    if (e.getSource() == uploadButton) {
        if ((checkAllFields()) && (checkForFile())) {

            SaveCurrentProperties(accessString, secretString, vaultString, locationChoice.getSelectedIndex());

            SwingWorker uploadWorker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    String accessString = getAccessField();
                    String secretString = getSecretField();
                    String vaultName = getVaultField();
                    File[] uploadFileBatch = multiFiles;

                    // work out exactly how much we are going to upload
                    // so we can support a second total upload progress bar
                    long totalSize = 0;
                    long uploadedSize = 0;
                    for (File f : uploadFileBatch) {
                        totalSize += f.length();
                    }

                    int locInt = locationChoice.getSelectedIndex();
                    multiFiles = null;
                    clearFile();
                    UploadWindow uw = new UploadWindow();

                    if (uploadFileBatch.length > 0) {

                        ArrayList<String> uploadList = new ArrayList<String>();

                        for (int i = 0; i < uploadFileBatch.length; i++) {
                            // Save Current Settings to properties

                            try {
                                Thread.sleep(100L);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            ClientConfiguration config = new ClientConfiguration();
                            config.setSocketTimeout(SOCKET_TIMEOUT);
                            config.setMaxErrorRetry(MAX_RETRIES);

                            BasicAWSCredentials credentials = new BasicAWSCredentials(accessString,
                                    secretString);
                            client = new AmazonGlacierClient(credentials, config);
                            final Endpoint endpoint = Endpoint.getByIndex(locInt);
                            client.setEndpoint(endpoint.getGlacierEndpoint());
                            String locationUpped = endpoint.name();
                            String thisFile = uploadFileBatch[i].getCanonicalPath();
                            String cleanFile = regexClean(thisFile);

                            try {

                                ArchiveTransferManager atm = new ArchiveTransferManager(client, credentials);

                                String fileLength = Long.toString(uploadFileBatch[i].length());

                                uw.setTitle("(" + (i + 1) + "/" + uploadFileBatch.length + ")" + " Uploading: "
                                        + thisFile);

                                UploadResult result = atm.upload(vaultName, cleanFile, uploadFileBatch[i]);

                                uw.addToLog("Done: " + thisFile + "\n");

                                uploadedSize += uploadFileBatch[i].length();

                                int percentage = (int) (((double) uploadedSize / totalSize) * 100);

                                uw.updateProgress(percentage);

                                Writer plainOutputLog = null;
                                Writer plainOutputTxt = null;
                                Writer plainOutputCsv = null;
                                Writer plainOutputYaml = null;

                                // write to file
                                if (logCheckMenuItem.isSelected()) {
                                    String treeHash = TreeHashGenerator.calculateTreeHash(uploadFileBatch[i]);

                                    try {
                                        plainOutputLog = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(0), true));
                                        plainOutputTxt = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(1), true));
                                        plainOutputCsv = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(2), true));
                                        plainOutputYaml = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(3), true));

                                    } catch (IOException ex) {
                                        JOptionPane.showMessageDialog(null, LOG_CREATION_ERROR, "IO Error",
                                                JOptionPane.ERROR_MESSAGE);
                                        uw.dispose();
                                        System.exit(1);
                                    }

                                    try {

                                        Date d = new Date();

                                        String thisResult = result.getArchiveId();

                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.write(" | ArchiveID: " + thisResult + " ");
                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.write(" | File: " + thisFile + " ");
                                        plainOutputLog.write(" | Bytes: " + fileLength + " ");
                                        plainOutputLog.write(" | Vault: " + vaultName + " ");
                                        plainOutputLog.write(" | Location: " + locationUpped + " ");
                                        plainOutputLog.write(" | Date: " + d.toString() + " ");
                                        plainOutputLog.write(" | Hash: " + treeHash + " ");
                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.close();

                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.write(" | ArchiveID: " + thisResult + " ");
                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.write(" | File: " + thisFile + " ");
                                        plainOutputTxt.write(" | Bytes: " + fileLength + " ");
                                        plainOutputTxt.write(" | Vault: " + vaultName + " ");
                                        plainOutputTxt.write(" | Location: " + locationUpped + " ");
                                        plainOutputTxt.write(" | Date: " + d.toString() + " ");
                                        plainOutputTxt.write(" | Hash: " + treeHash + " ");
                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.close();

                                        plainOutputCsv.write("" + thisResult + ",");
                                        plainOutputCsv.write("" + thisFile + ",");
                                        plainOutputCsv.write("" + fileLength + ",");
                                        plainOutputCsv.write("" + vaultName + ",");
                                        plainOutputCsv.write("" + locationUpped + ",");
                                        plainOutputCsv.write("" + d.toString() + ",");
                                        plainOutputCsv.write("" + treeHash + ",");
                                        plainOutputCsv.write(System.getProperty("line.separator"));
                                        plainOutputCsv.close();

                                        plainOutputYaml.write(System.getProperty("line.separator"));
                                        plainOutputYaml.write("-  ArchiveID: \"" + thisResult + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   File:      \"" + thisFile + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   Bytes:     \"" + fileLength + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   Vault:     \"" + vaultName + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   Location:  \"" + locationUpped + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   Date:      \"" + d.toString() + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.write("   Hash:      \"" + treeHash + "\""
                                                + System.getProperty("line.separator"));
                                        plainOutputYaml.close();

                                        uploadList.add("Successfully uploaded " + thisFile + " to vault "
                                                + vaultName + " at " + locationUpped + ". Bytes: " + fileLength
                                                + ". ArchiveID Logged.\n");
                                    }

                                    catch (IOException c) {
                                        JOptionPane.showMessageDialog(null, LOG_WRITE_ERROR, "IO Error",
                                                JOptionPane.ERROR_MESSAGE);
                                        uw.dispose();
                                        System.exit(1);
                                    }

                                } else {
                                    JOptionPane.showMessageDialog(null, "Upload Complete!\nArchive ID: "
                                            + result.getArchiveId()
                                            + "\nIt may take some time for Amazon to update the inventory.",
                                            "Uploaded", JOptionPane.INFORMATION_MESSAGE);
                                    multiFiles = null;
                                    uw.dispose();
                                }

                                clearFile();

                            } catch (Exception h) {
                                if (logCheckMenuItem.isSelected()) {
                                    writeToErrorLog(h, thisFile);
                                }
                                JOptionPane.showMessageDialog(null, "" + h, "Error", JOptionPane.ERROR_MESSAGE);
                                uw.dispose();

                            }

                        }
                        StringBuilder sb = new StringBuilder();
                        for (int j = 0; j < uploadFileBatch.length; j++) {
                            sb.append(uploadList.get(j));
                        }
                        uw.dispose();

                        // Move the actual results string to a JTextArea
                        JTextArea uploadCompleteMsg = new JTextArea("Upload Complete! \n" + sb);
                        uploadCompleteMsg.setLineWrap(true);
                        uploadCompleteMsg.setWrapStyleWord(true);
                        uploadCompleteMsg.setEditable(false);

                        // Put the JTextArea in a JScollPane and present that in the JOptionPane
                        JScrollPane uploadCompleteScroll = new JScrollPane(uploadCompleteMsg);
                        uploadCompleteScroll.setPreferredSize(new Dimension(500, 400));
                        JOptionPane.showMessageDialog(null, uploadCompleteScroll, "Uploaded",
                                JOptionPane.INFORMATION_MESSAGE);
                        // Close the JProgressBar
                        multiFiles = null;
                        clearFile();
                    } else {
                        JOptionPane.showMessageDialog(null, "This wasn't supposed to happen.", "Bug!",
                                JOptionPane.ERROR_MESSAGE);
                        uw.dispose();

                    }

                    return null;
                }

                private void writeToErrorLog(Exception h, String thisFile) {
                    String thisError = h.toString();

                    Writer errorOutputLog = null;
                    try {
                        errorOutputLog = new BufferedWriter(new FileWriter(getLogFilenamePath(4), true));
                    } catch (Exception badLogCreate) {
                        JOptionPane.showMessageDialog(null, LOG_CREATION_ERROR, "IO Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }
                    try {
                        Date d = new Date();

                        errorOutputLog.write(System.getProperty("line.separator"));
                        errorOutputLog.write("" + d.toString() + ": \"" + thisFile + "\" *ERROR* " + thisError);
                        errorOutputLog.write(System.getProperty("line.separator"));

                    } catch (Exception badLogWrite) {
                        JOptionPane.showMessageDialog(null, LOG_WRITE_ERROR, "IO Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }
                }
            };
            uploadWorker.execute();
        }
    }
}

From source file:com.brianmcmichael.SimpleGlacierUploader.SimpleGlacierUploader.java

License:Open Source License

public AmazonGlacierClient makeClient(String accessorString, String secretiveString, int region) {
    // AmazonGlacierClient client;
    BasicAWSCredentials credentials = new BasicAWSCredentials(accessorString, secretiveString);
    client = new AmazonGlacierClient(credentials);
    // int locInt = locationChoice.getSelectedIndex();
    Endpoints ep = new Endpoints(region);
    // String endpointUrl = ep.Endpoint(region);
    client.setEndpoint(ep.Endpoint());

    return client;
}

From source file:com.brianmcmichael.SimpleGlacierUploader.SimpleGlacierUploader.java

License:Open Source License

@Override
public void actionPerformed(ActionEvent e) {

    String accessString = getAccessField();
    String secretString = getSecretField();
    String vaultString = getVaultField();
    int regionInt = getServerRegion();

    if (e.getSource() == newVaultButton && checkAWSFields()) {
        AmazonGlacierClient newVaultClient = new AmazonGlacierClient();
        newVaultClient = makeClient(accessString, secretString, regionInt);
        AddVaultFrame avf = new AddVaultFrame(newVaultClient, regionInt);
        avf.setVisible(true);/*w ww.  j av a  2  s.  c o m*/

    }
    if (e.getSource() == vaultSelector) {
        if (vaultSelector.getSelectedItem() != null) {
            if (vaultSelector.getSelectedIndex() == 0) {
                vaultField.setText("");
            } else {
                vaultField.setText(vaultSelector.getSelectedItem().toString());
            }
        } else {
        }
    }
    if (e.getSource() == loginButton) {
        repopulateVaults(accessString, secretString, regionInt);
    }
    if (e.getSource() == exitApplicationMnu) {
        System.exit(0);
    }
    if (e.getSource() == updateMnu || e.getSource() == checkUpdateButton) {
        JHyperlinkLabel.OpenURI(URL_STRING);
    }
    if (e.getSource() == saveFileMnu) {
        FileDialog fd = new FileDialog(new Frame(), "Save...", FileDialog.SAVE);
        fd.setFile("Glacier.txt");
        fd.setDirectory(curDir);
        fd.setLocation(50, 50);
        fd.setVisible(true);
        // fd.show();
        String filePath = "" + fd.getDirectory() + System.getProperty("file.separator") + fd.getFile();

        File outFile = new File(filePath);

        if ((outFile.equals("") == false) && (outFile.equals("null") == false)
                && ((outFile == null) == false)) {

            try {
                FileReader fr = new FileReader(getLogFilenamePath(0));
                BufferedReader br = new BufferedReader(fr);

                FileWriter saveFile = new FileWriter(outFile.toString());

                int count = 0;
                boolean moreLines = true;

                String ln1 = "";
                String ln2 = "";
                String ln3 = "";

                while (moreLines == true) {
                    ln1 = br.readLine();
                    ln2 = br.readLine();
                    ln3 = br.readLine();

                    if (ln1 == null) {
                        ln1 = "";
                    }
                    if (ln2 == null) {
                        ln2 = "";
                    }
                    if (ln3 == null) {
                        ln3 = "";
                    }

                    saveFile.write(ln1);
                    saveFile.write("\r\n");
                    saveFile.write(ln2);
                    saveFile.write("\r\n");
                    saveFile.write(ln3);
                    saveFile.write("\r\n");

                    count++;

                    if (ln3.equals("")) {
                        moreLines = false;
                        br.close();
                        saveFile.close();
                        JOptionPane.showMessageDialog(null,
                                "Successfully exported " + count + " archive records to " + outFile.toString(),
                                "Export", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            } catch (FileNotFoundException e1) {
                JOptionPane.showMessageDialog(null, "Unable to locate Glacier.log", "Error",
                        JOptionPane.ERROR_MESSAGE);
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    if (e.getSource() == viewLog || e.getSource() == logButton) {
        JHyperlinkLabel.OpenURI("" + SimpleGlacierUploader.getLogFilenamePath(getLogFileType()).toURI());
    }
    if (e.getSource() == deleteArchiveMnu) {
        if (checkAllFields()) {
            AmazonGlacierClient newDeleteClient = new AmazonGlacierClient();
            newDeleteClient = makeClient(accessString, secretString, regionInt);
            DeleteArchiveFrame daf = new DeleteArchiveFrame(newDeleteClient, vaultString, regionInt);
            daf.setVisible(true);
        }
    }
    if (e.getSource() == inventoryRequestButton) {
        if (checkAllFields()) {
            AmazonGlacierClient newInventoryClient = new AmazonGlacierClient();
            newInventoryClient = makeClient(accessString, secretString, regionInt);
            InventoryRequest ir = new InventoryRequest(newInventoryClient, vaultString, regionInt);
            ir.setVisible(true);
        }
    }
    if (e.getSource() == downloadRequestButton || e.getSource() == downloadFileMnu) {
        if (checkAllFields()) {
            AmazonGlacierClient newDownloadClient = new AmazonGlacierClient();
            newDownloadClient = makeClient(accessString, secretString, regionInt);
            BasicAWSCredentials credentials = new BasicAWSCredentials(accessString, secretString);
            AmazonDownloadRequest adr = new AmazonDownloadRequest(newDownloadClient, vaultString, regionInt,
                    credentials);
            adr.setVisible(true);
        }
    }

    if (e.getSource() == aboutMnu) {
        JOptionPane.showMessageDialog(null, ABOUT_WINDOW_STRING, "About", JOptionPane.INFORMATION_MESSAGE);
    }

    if (e.getSource() == clearButton) {
        ddText.setText("");
        uploadButton.setText("Select Files");
        multiFiles = null;
    }

    if (e.getSource() == locationChoice) {
        repopulateVaults(accessString, secretString, regionInt);
    }

    if (e.getSource() == selectFileButton) {
        int returnVal = fc.showOpenDialog(SimpleGlacierUploader.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (fc.getSelectedFile().isFile()) {
                /*
                 * Removed for v. 0.72 if (fc.getSelectedFile().length() >
                 * max_file_size == true) {
                 * JOptionPane.showMessageDialog(null,
                 * FILE_TOO_BIG_ERROR,"Error",JOptionPane.ERROR_MESSAGE);
                 * try { //ddText.setForeground(rc); ddText.append(
                 * "Unable to upload: " +
                 * fc.getSelectedFile().getCanonicalPath() + "\n" ); } //
                 * end try catch( java.io.IOException g ) {} } else {
                 */
                File[] thisFile = new File[1];
                thisFile[0] = fc.getSelectedFile();
                try {
                    ddText.append(thisFile[0].getCanonicalPath() + "\n");
                } // end try
                catch (java.io.IOException f) {
                }
                if (multiFiles != null) {
                    multiFiles = concatFileArray(multiFiles, thisFile);
                } else {
                    multiFiles = thisFile;
                }

                // }
            } else {
                JOptionPane.showMessageDialog(null, NO_DIRECTORIES_ERROR, "Error", JOptionPane.ERROR_MESSAGE);
            }
        } else {
        }

    }

    if (e.getSource() == uploadButton) {
        if ((checkAllFields()) && (checkForFile())) {

            SaveCurrentProperties(accessString, secretString, vaultString, locationChoice.getSelectedIndex());

            SwingWorker uploadWorker = new SwingWorker() {

                @Override
                protected Object doInBackground() throws Exception {
                    String accessString = getAccessField();
                    String secretString = getSecretField();
                    // String vaultString = getVaultField();
                    String vaultName = getVaultField();
                    File[] uploadFileBatch = multiFiles;

                    // work out exactly how much we are going to upload
                    // so we can support a second total upload progress bar
                    long totalSize = 0;
                    long uploadedSize = 0;
                    for (File f : uploadFileBatch) {
                        totalSize += f.length();
                    }

                    int locInt = locationChoice.getSelectedIndex();
                    multiFiles = null;
                    clearFile();
                    UploadWindow uw = new UploadWindow();

                    if (uploadFileBatch.length > 0) {

                        ArrayList<String> uploadList = new ArrayList<String>();

                        for (int i = 0; i < uploadFileBatch.length; i++) {
                            // Save Current Settings to properties

                            try {
                                Thread.sleep(100L);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            ClientConfiguration config = new ClientConfiguration();
                            config.setSocketTimeout(SOCKET_TIMEOUT);
                            config.setMaxErrorRetry(MAX_RETRIES);

                            BasicAWSCredentials credentials = new BasicAWSCredentials(accessString,
                                    secretString);
                            client = new AmazonGlacierClient(credentials, config);
                            Endpoints ep = new Endpoints(locInt);
                            // String endpointUrl = ep.Endpoint(locInt);
                            client.setEndpoint(ep.Endpoint());
                            String locationUpped = ep.Location();
                            String thisFile = uploadFileBatch[i].getCanonicalPath();
                            String cleanFile = regexClean(thisFile);

                            // char emptyChar = 0xFFFA;
                            // String thisCleanFile =
                            // thisFile.valueOf(emptyChar).replaceAll("\\p{C}",
                            // "?");

                            try {

                                ArchiveTransferManager atm = new ArchiveTransferManager(client, credentials);

                                String fileLength = Long.toString(uploadFileBatch[i].length());

                                uw.setTitle("(" + (i + 1) + "/" + uploadFileBatch.length + ")" + " Uploading: "
                                        + thisFile);

                                UploadResult result = atm.upload(vaultName, cleanFile, uploadFileBatch[i]);

                                uw.addToLog("Done: " + thisFile + "\n");

                                uploadedSize += uploadFileBatch[i].length();

                                int percentage = (int) (((double) uploadedSize / totalSize) * 100);

                                uw.updateProgress(percentage);

                                Writer plainOutputLog = null;
                                Writer plainOutputTxt = null;
                                Writer plainOutputCsv = null;

                                // write to file
                                if (logCheckMenuItem.isSelected()) {
                                    String treeHash = TreeHashGenerator.calculateTreeHash(uploadFileBatch[i]);

                                    try {
                                        plainOutputLog = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(0), true));
                                        plainOutputTxt = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(1), true));
                                        plainOutputCsv = new BufferedWriter(
                                                new FileWriter(getLogFilenamePath(2), true));

                                    } catch (IOException ex) {
                                        JOptionPane.showMessageDialog(null, LOG_CREATION_ERROR, "IO Error",
                                                JOptionPane.ERROR_MESSAGE);
                                        uw.dispose();
                                        System.exit(1);
                                    }

                                    try {

                                        Date d = new Date();

                                        String thisResult = result.getArchiveId();

                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.write(" | ArchiveID: " + thisResult + " ");
                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.write(" | File: " + thisFile + " ");
                                        plainOutputLog.write(" | Bytes: " + fileLength + " ");
                                        plainOutputLog.write(" | Vault: " + vaultName + " ");
                                        plainOutputLog.write(" | Location: " + locationUpped + " ");
                                        plainOutputLog.write(" | Date: " + d.toString() + " ");
                                        plainOutputLog.write(" | Hash: " + treeHash + " ");
                                        plainOutputLog.write(System.getProperty("line.separator"));
                                        plainOutputLog.close();

                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.write(" | ArchiveID: " + thisResult + " ");
                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.write(" | File: " + thisFile + " ");
                                        plainOutputTxt.write(" | Bytes: " + fileLength + " ");
                                        plainOutputTxt.write(" | Vault: " + vaultName + " ");
                                        plainOutputTxt.write(" | Location: " + locationUpped + " ");
                                        plainOutputTxt.write(" | Date: " + d.toString() + " ");
                                        plainOutputTxt.write(" | Hash: " + treeHash + " ");
                                        plainOutputTxt.write(System.getProperty("line.separator"));
                                        plainOutputTxt.close();

                                        plainOutputCsv.write("" + thisResult + ",");
                                        plainOutputCsv.write("" + thisFile + ",");
                                        plainOutputCsv.write("" + fileLength + ",");
                                        plainOutputCsv.write("" + vaultName + ",");
                                        plainOutputCsv.write("" + locationUpped + ",");
                                        plainOutputCsv.write("" + d.toString() + ",");
                                        plainOutputCsv.write("" + treeHash + ",");
                                        plainOutputCsv.write(System.getProperty("line.separator"));
                                        plainOutputCsv.close();

                                        uploadList.add("Successfully uploaded " + thisFile + " to vault "
                                                + vaultName + " at " + locationUpped + ". Bytes: " + fileLength
                                                + ". ArchiveID Logged.\n");
                                    }

                                    // v0.4 logging code
                                    // output.writeUTF("ArchiveID: " +
                                    // thisResult + " ");
                                    // output.writeUTF(" | File: " +
                                    // thisFile + " ");
                                    // output.writeUTF(" | Vault: "
                                    // +vaultName + " ");
                                    // output.writeUTF(" | Location: " +
                                    // locationUpped + " ");
                                    // output.writeUTF(" | Date: "+d.toString()+"\n\n");
                                    catch (IOException c) {
                                        JOptionPane.showMessageDialog(null, LOG_WRITE_ERROR, "IO Error",
                                                JOptionPane.ERROR_MESSAGE);
                                        uw.dispose();
                                        System.exit(1);
                                    }

                                } else {
                                    JOptionPane.showMessageDialog(null, "Upload Complete!\nArchive ID: "
                                            + result.getArchiveId()
                                            + "\nIt may take some time for Amazon to update the inventory.",
                                            "Uploaded", JOptionPane.INFORMATION_MESSAGE);
                                    multiFiles = null;
                                    uw.dispose();
                                }

                                clearFile();

                            } catch (Exception h) {
                                if (logCheckMenuItem.isSelected()) {
                                    writeToErrorLog(h, thisFile);
                                }
                                JOptionPane.showMessageDialog(null, "" + h, "Error", JOptionPane.ERROR_MESSAGE);
                                uw.dispose();

                            }

                        }
                        StringBuilder sb = new StringBuilder();
                        for (int j = 0; j < uploadFileBatch.length; j++) {
                            sb.append(uploadList.get(j));
                        }
                        uw.dispose();

                        JOptionPane.showMessageDialog(null, "Upload Complete! \n" + sb, "Uploaded",
                                JOptionPane.INFORMATION_MESSAGE);
                        // Close the JProgressBar
                        multiFiles = null;
                        clearFile();
                    } else {
                        JOptionPane.showMessageDialog(null, "This wasn't supposed to happen.", "Bug!",
                                JOptionPane.ERROR_MESSAGE);
                        uw.dispose();

                    }

                    return null;
                }

                private void writeToErrorLog(Exception h, String thisFile) {
                    String thisError = h.toString();

                    Writer errorOutputLog = null;
                    try {
                        errorOutputLog = new BufferedWriter(new FileWriter(getLogFilenamePath(3), true));
                    } catch (Exception badLogCreate) {
                        JOptionPane.showMessageDialog(null, LOG_CREATION_ERROR, "IO Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }
                    try {
                        Date d = new Date();

                        errorOutputLog.write(System.getProperty("line.separator"));
                        errorOutputLog.write("" + d.toString() + ": \"" + thisFile + "\" *ERROR* " + thisError);
                        errorOutputLog.write(System.getProperty("line.separator"));

                    } catch (Exception badLogWrite) {
                        JOptionPane.showMessageDialog(null, LOG_WRITE_ERROR, "IO Error",
                                JOptionPane.ERROR_MESSAGE);
                        System.exit(1);
                    }
                }

            };
            uploadWorker.execute();

        }

    } else {
    }
}

From source file:com.brighttag.agathon.aws.AwsModule.java

License:Apache License

@Provides
@Exposed/*w  w  w  . j a v a2s.  c  o  m*/
@Singleton
AWSCredentials provideAWSCredentials(@Named(ACCESS_KEY_PROPERTY) String accessKey,
        @Named(SECRET_KEY_PROPERTY) String secretKey) {
    return new BasicAWSCredentials(accessKey, secretKey);
}

From source file:com.capitalone.dashboard.collector.AWSCloudCollectorTask.java

License:Apache License

/**
 * The collection action. This is the task which will run on a schedule to
 * gather data from the feature content source system and update the
 * repository with retrieved data.//  ww  w . j  a va 2 s  . c o m
 */
public void collect(AWSCloudCollector collector) {
    logger.info("Starting Cloud collection...");

    ClientConfiguration clientConfig = new ClientConfiguration().withProxyHost("proxy.kdc.capitalone.com")
            .withProxyPort(8099).withPreemptiveBasicProxyAuth(true).withProxyUsername("xxx")
            .withProxyPassword("xxxxxxx");

    String accessKey = "xxx";
    String secretKey = "xxx";

    AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);
    AmazonEC2Client ec2Client = new AmazonEC2Client(creds, clientConfig);
    AmazonCloudWatchClient cwClient = new AmazonCloudWatchClient(creds, clientConfig);
    DescribeInstancesResult result = ec2Client.describeInstances();

    //create list of instances
    List<Instance> instanceList = new ArrayList<Instance>();
    List<Reservation> reservations = result.getReservations();
    for (Reservation currRes : reservations) {
        List<Instance> currInstanceList = currRes.getInstances();
        instanceList.addAll(currInstanceList);
    }

    //purge the repo of old instance data
    if (awsRawDataRepository.count() > 0)
        awsRawDataRepository.deleteAll();

    //for every instance determine all metrics
    logger.info("Collecting Raw Data...");
    for (Instance currInstance : instanceList) {
        CloudRawData object = cloudClient.getMetrics(currInstance, cwClient, accessKey);
        awsRawDataRepository.save(object);
    }

    //purge the repo of old account data
    if (cloudAccountRepository.count() > 0)
        cloudAccountRepository.deleteAll();

    logger.info("Agregating Data...");
    CloudAggregatedData aggregatedData = new CloudAggregatedData();
    aggregatedData.setAgeWarning(awsRawDataRepository.runAgeWarning("cof-sandbox-dev").size());
    aggregatedData.setAgeExpired(awsRawDataRepository.runAgeExpired("cof-sandbox-dev").size());
    aggregatedData.setAgeGood(awsRawDataRepository.runAgeGood("cof-sandbox-dev").size());
    aggregatedData.setCpuHigh(awsRawDataRepository.runCpuUtilizationHigh("cof-sandbox-dev").size());
    aggregatedData.setCpuMid(awsRawDataRepository.runCpuUtilizationMid("cof-sandbox-dev").size());
    aggregatedData.setCpuLow(awsRawDataRepository.runCpuUtilizationLow("cof-sandbox-dev").size());
    aggregatedData.setNonEncryptedCount(awsRawDataRepository.runNonEncrypted("cof-sandbox-dev").size());
    aggregatedData.setNonTaggedCount(awsRawDataRepository.runNonTagged("cof-sandbox-dev").size());
    aggregatedData.setStoppedCount(awsRawDataRepository.runStopped("cof-sandbox-dev").size());
    aggregatedData.setAccountName("cof-sandbox-dev");
    aggregatedData.setTotalInstanceCount(awsRawDataRepository.runAllInstanceCount("cof-sandbox-dev").size());

    cloudAccountRepository.save(aggregatedData);
    logger.info("Finished Cloud collection.");

}

From source file:com.cfelde.aws.ddb.management.TableThroughput.java

License:Open Source License

public static void main(String... args) {
    loadPartitionState();/*from   ww  w.j a  va2s  .c  om*/

    // TODO: All these parameters should be loaded from a config file!
    String accessKey = "YOUR ACCESS KEY";
    String secretKey = "YOUR SECRET KEY";

    AmazonCloudWatch client = new AmazonCloudWatchClient(new BasicAWSCredentials(accessKey, secretKey));
    AmazonDynamoDBClient ddb = new AmazonDynamoDBClient(new BasicAWSCredentials(accessKey, secretKey));

    client.setEndpoint("https://monitoring.eu-west-1.amazonaws.com");
    ddb.setEndpoint("https://dynamodb.eu-west-1.amazonaws.com");

    // Do one per table you want to manage
    initTableThroughput(client, ddb, "table1", 2, 100, 2, 100);
    initTableThroughput(client, ddb, "table2", 2, 100, 2, 100);

    executor.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            storePartitionState();
        }
    }, 16, 61, TimeUnit.MINUTES);
}

From source file:com.choicemaker.xmlencryption.AwsKmsCredentialSet.java

License:Open Source License

/**
 * Creates an instance of AWSCredentials from
 * {@link AwsKmsProperties#PN_ACCESSKEY access-} and
 * {@link AwsKmsProperties#PN_SECRETKEY secret-}key properties defined by
 * the specified set of properties.// w ww.  j  av a2  s  .c om
 * 
 * @param a
 *            non-null, non-blank set of properties
 * @return a non-null instance of AWSCredentials
 * @throws IllegalArgumentException
 *             if {@link AwsKmsProperties#PN_ACCESSKEY access-} and
 *             {@link AwsKmsProperties#PN_SECRETKEY secret-}key properties
 *             are not defined in the specified set of properties.
 */
public static AWSCredentials createAWSCredentials(Properties p) {
    Precondition.assertNonNullArgument("null properties", p);
    String accessKey = AwsKmsProperties.getAccessKey(p);
    if (!StringUtils.nonEmptyString(accessKey)) {
        String msg = "Missing property '" + AwsKmsProperties.PN_ACCESSKEY + "'";
        throw new IllegalArgumentException(msg);
    }
    String secretKey = AwsKmsProperties.getSecretKey(p);
    if (!StringUtils.nonEmptyString(secretKey)) {
        String msg = "Missing property '" + AwsKmsProperties.PN_SECRETKEY + "'";
        throw new IllegalArgumentException(msg);
    }
    AWSCredentials retVal = new BasicAWSCredentials(accessKey, secretKey);
    return retVal;
}

From source file:com.cirrus.server.osgi.service.amazon.s3.AmazonS3StorageService.java

License:Apache License

@Override
public void authenticate(final AccessKeyPasswordAuthenticator trustedToken) {
    final String accessKey = trustedToken.getAccessKey();
    final String accessSecret = trustedToken.getAccessPassword();
    final AWSCredentials credentials = new BasicAWSCredentials(accessKey, accessSecret);
    this.amazonS3Client = new AmazonS3Client(credentials);
    this.createBucketIfNotExist();
}

From source file:com.cleanenergyexperts.aws.cf.CloudFormationMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    getLog().info("Bucket Name: " + bucketName);
    //getLog().info("Cloud Formation Stack Name: " + stackName);

    if (artifactFile == null || !artifactFile.isFile()) {
        throw new MojoExecutionException("Cannot find artifact file to upload");
    }/*from   w ww.  ja  va2  s .c  o  m*/
    String artifactKey = artifactFile.getName();
    getLog().info("Artifact Name: " + artifactKey);

    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonCloudFormationClient cfClient = new AmazonCloudFormationClient(awsCredentials);
    cfClient.setEndpoint(getCloudFormationEndPoint());
    AmazonS3Client s3Client = new AmazonS3Client(awsCredentials);

    // Upload Artifact to S3
    try {
        getLog().info("Uploading artifact to S3...");
        s3Client.putObject(bucketName, artifactKey, artifactFile);
    } catch (AmazonServiceException e) {
        throw new MojoExecutionException("[SERVICE] Could Not Upload File to S3", e);
    } catch (AmazonClientException e) {
        throw new MojoExecutionException("[CLIENT] Could Not Upload File to S3", e);
    }

    // Update each stack with the new artifact file
    for (String stackName : stackNames) {
        getLog().info("Cloud Formation Stack Name: " + stackName);
        String templateBody = getTemplateBody(cfClient, stackName);
        Stack stack = getStack(cfClient, stackName);

        // If passed additional parameters, update them
        List<Parameter> parameters = stack.getParameters();
        if (stackParameters != null && !stackParameters.isEmpty()) {
            List<Parameter> tmpParams = new ArrayList<Parameter>();

            // Add Existing Parameters we haven't locally overwritten
            for (Parameter oldParam : parameters) {
                String oldKey = oldParam.getParameterKey();
                if (!stackParameters.containsKey(oldKey)) {
                    tmpParams.add(oldParam);
                }
            }

            // Add Overwrite parameters
            for (String key : stackParameters.keySet()) {
                Parameter newParam = new Parameter();
                newParam.setParameterKey(key);
                newParam.setParameterValue(stackParameters.get(key));
                tmpParams.add(newParam);
            }
            parameters = tmpParams;
        }

        // Update the Stack
        UpdateStackRequest updateStackRequest = new UpdateStackRequest();
        updateStackRequest.setStackName(stackName);
        updateStackRequest.setTemplateBody(templateBody);
        updateStackRequest.setParameters(parameters);
        updateStackRequest.setCapabilities(stack.getCapabilities());
        try {
            getLog().info("Updating Cloud Formation Stack...");
            cfClient.updateStack(updateStackRequest);
        } catch (AmazonServiceException e) {
            throw new MojoExecutionException("[SERVICE] Could Not Update Cloud Formation Stack", e);
        } catch (AmazonClientException e) {
            throw new MojoExecutionException("[CLIENT] Could Not Update Cloud Formation Stack", e);
        }
        getLog().info("Cloud Formation Stack " + stackName + "is now updating...");
    }

    getLog().info("All stacks have been updated. Complete.");
}

From source file:com.cleanenergyexperts.aws.cf.CloudFormationMojo.java

License:Apache License

protected AWSCredentials getAWSCredentials() throws MojoExecutionException {
    /*if (settings != null && serverId != null) {
       Server server = settings.getServer(serverId);
       if (server != null) {/*  w  w w .j a  v a 2  s .co m*/
     accessKey = server.getUsername().trim();
     secretKey = server.getPassword().trim();
     // TODO: Decrypt https://bitbucket.org/aldrinleal/beanstalker/src/d72b183f832cd81c670ca1e4ae764868cdfd16b9/beanstalker-common/src/main/java/br/com/ingenieux/mojo/aws/AbstractAWSMojo.java?at=default
       }
    }*/
    if (accessKey == null || secretKey == null || accessKey.isEmpty() || secretKey.isEmpty()) {
        throw new MojoExecutionException("Missing either accessKey and secretKey.");
    }
    return new BasicAWSCredentials(accessKey, secretKey);
}