index int64 0 0 | repo_id stringlengths 26 205 | file_path stringlengths 51 246 | content stringlengths 8 433k | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SelectionTable.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.ec2.AmazonEC2;
/**
* A generic table supporting basic operations (column creation, context menu
* creation, etc) suitable to use as a base for more complex tables.
*/
public abstract class SelectionTable extends Composite {
/** The internal table viewer control */
protected TreeViewer viewer;
/** An optional listener to notify before and after loading AMIs */
protected SelectionTableListener selectionTableListener;
/** The shared user account info */
private AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
/** True if this selection table allows multiple items to be selected */
private final boolean allowMultipleSelections;
/** True if this table should be virtual because of data sizes */
private final boolean virtualTable;
/** An optional comparator to control sorting by columns */
protected SelectionTableComparator comparator;
/** An optional account ID to use in EC2 requests, otherwise the default will be used */
protected String accountIdOverride;
/**
* Specifying an EC2 region override will cause the EC2 client for this
* selection table to always use this overridden endpoint, instead of using
* the user's currently selected endpoint from the system preferences.
*/
protected Region ec2RegionOverride;
/**
* Creates a new selection table with the specified parent.
*
* @param parent
* The composite object to contain this new selection table.
*/
public SelectionTable(Composite parent) {
this(parent, false, false);
}
/**
* Creates a new selection table with the specified parent.
*
* @param parent
* The composite object to contain this new selection table.
* @param allowMultipleSelections
* True if this new selection table should allow multiple rows to
* be selected at once, otherwise false if only one row should be
* selectable at a time.
* @param virtualTable
* True if this new selection table should use the SWT VIRTUAL
* style, indicating that it will supply a lazy content provider.
*/
public SelectionTable(Composite parent, boolean allowMultipleSelections, boolean virtualTable) {
super(parent, SWT.NONE);
this.allowMultipleSelections = allowMultipleSelections;
this.virtualTable = virtualTable;
createControl();
}
/**
* Adds a selection listener to this selection table.
*
* @param listener The selection listener to add to this table.
*/
public void addSelectionListener(SelectionListener listener) {
viewer.getTree().addSelectionListener(listener);
}
/**
* Clears the selection in this selection table.
*/
public void clearSelection() {
viewer.getTree().setSelection(new TreeItem[0]);
}
/**
* Sets the optional SelectionTableListener that will be notified before
* and after data is loaded. Loading data can be a long operation, so
* providing a listener allows another class to receive events as the
* loading status changes so it can update itself appropriately.
*
* @param listener
* The listener to notify before and after loading data.
*/
public void setListener(SelectionTableListener listener) {
this.selectionTableListener = listener;
}
/**
* Sets the optional EC2 region override for this selection table. Setting
* this value will cause the EC2 client returned by the getClient method to
* *always* use this EC2 region, and will completely ignore the EC2 region
* selected in the system preferences.
*
* @param region
* The EC2 region to use instead of defaulting to the currently
* selected EC2 region in the system preferences.
*/
public void setEc2RegionOverride(Region region) {
this.ec2RegionOverride = region;
}
/**
* Sets the optional EC2 account ID override for this selection table.
* Setting this will cause the EC2 client to authenticate requests with the
* specified account, otherwise the default account is used.
*
* @param accountId
* The account ID to use for making requests in this selection
* table.
*/
public void setAccountIdOverride(String accountId) {
this.accountIdOverride = accountId;
}
/**
* Returns the viewer used in this table.
*/
protected Viewer getViewer() {
return viewer;
}
/**
* Returns a ready-to-use EC2 client using the currently selected AWS
* account.
*
* @return A fully configured AWS EC2 client.
*/
protected AmazonEC2 getAwsEc2Client() {
if (accountIdOverride != null) return getAwsEc2Client(accountIdOverride);
else return getAwsEc2Client(null);
}
/**
* Returns a ready-to-use EC2 client for the account ID given.
*
* TODO: move the account ID into a member variable, deprecate this method
*/
protected AmazonEC2 getAwsEc2Client(String accountId) {
if ( ec2RegionOverride != null ) {
return AwsToolkitCore.getClientFactory(accountId).getEC2ClientByEndpoint(ec2RegionOverride.getServiceEndpoint(ServiceAbbreviations.EC2));
}
Region defaultRegion = RegionUtils.getCurrentRegion();
String regionEndpoint = defaultRegion.getServiceEndpoints().get(ServiceAbbreviations.EC2);
return AwsToolkitCore.getClientFactory(accountId).getEC2ClientByEndpoint(regionEndpoint);
}
/**
* Returns the current selection in this table.
*
* @return The current selection in this table.
*/
protected Object getSelection() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
return selection.getFirstElement();
}
/**
* Packs the columns in this selection table.
*/
protected void packColumns() {
if (viewer == null) return;
Tree table = viewer.getTree();
for (TreeColumn col : table.getColumns()) {
col.pack();
}
}
/**
* Creates a new column with the specified text and weight.
*
* @param columnText
* The text for the column header.
* @param weight
* The weight of the new column, relative to the other columns.
*
* @return The new TableColum that was created.
*/
protected TreeColumn newColumn(String columnText, int weight) {
Tree table = viewer.getTree();
TreeColumn column = new TreeColumn(table, SWT.NONE);
column.setText(columnText);
TreeColumnLayout tableColumnLayout = (TreeColumnLayout)getLayout();
tableColumnLayout.setColumnData(column, new ColumnWeightData(weight));
return column;
}
/**
* Creates and configures the actual tree control.
*/
protected void createControl() {
TreeColumnLayout treeColumnLayout = new TreeColumnLayout();
setLayout(treeColumnLayout);
int style = SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER;
if (allowMultipleSelections) {
style |= SWT.MULTI;
} else {
style |= SWT.SINGLE;
}
if (virtualTable) {
style |= SWT.VIRTUAL;
}
viewer = new TreeViewer(this, style);
if (virtualTable) viewer.setUseHashlookup(true);
Tree tree = viewer.getTree();
tree.setLinesVisible(true);
tree.setHeaderVisible(true);
createColumns();
makeActions();
hookContextMenu();
}
/**
* Subclasses must implement this to set up the table's columns.
*/
protected abstract void createColumns();
/**
* Subclasses must implement this to create any needed actions.
*/
protected abstract void makeActions();
/**
* Subclasses must implement this to provide any context menu contributions.
*
* @param manager
* The manager for the table's context menu.
*/
protected abstract void fillContextMenu(IMenuManager manager);
/**
* Hooks a context (popup) menu for the table control.
*/
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager("#PopupMenu");
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new AcountValidatingMenuListener());
Menu menu = menuMgr.createContextMenu(viewer.getControl());
viewer.getControl().setMenu(menu);
menuMgr.createContextMenu(this);
}
/**
* Sets the comparator used to control sorting by columns in this selection
* table and adds a selection listener to each column in this table that will
* update the sorting information on the comparator.
*
* @param comparator
* The comparator used to control sorting by columns in this
* selection table.
*/
protected void setComparator(SelectionTableComparator comparator) {
this.comparator = comparator;
viewer.setComparator(comparator);
viewer.getTree().setSortColumn(viewer.getTree().getColumn(comparator.getColumn()));
viewer.getTree().setSortDirection(comparator.getDirection());
int i = 0;
for (TreeColumn column : viewer.getTree().getColumns()) {
column.addSelectionListener(new SelectionTableColumnClickListener(i++, viewer, comparator));
}
}
/**
* A MenuListener that checks to see if the user's AWS account information has
* been entered. If it hasn't, the user will be directed to the plugin
* preferences so they can enter it and start using the tools.
*/
private final class AcountValidatingMenuListener implements IMenuListener {
/* (non-Javadoc)
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
@Override
public void menuAboutToShow(IMenuManager manager) {
if (accountInfo != null && accountInfo.isValid()) {
fillContextMenu(manager);
return;
}
manager.add(new SetupAwsAccountAction());
}
}
/**
* A simple interface that objects can implement if they want to register
* themselves as a listener for data loading events in this SelectionTable.
*/
public interface SelectionTableListener {
/**
* This method is called to notify the listener that this selection
* table is currently reloading its data.
*/
public void loadingData();
/**
* This method is called to notify the listener that this selection
* table has finished loading all data. This doesn't necessarily mean
* that they were loaded successfully, just that this selection table is
* no longer querying for data.
* Will also pass along the number of records that got loaded
*/
public void finishedLoadingData(int recordCount);
}
}
| 7,200 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/Ec2OverviewSection.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.AwsUrls;
import com.amazonaws.eclipse.core.ui.overview.OverviewSection;
import com.amazonaws.eclipse.ec2.ui.launchwizard.LaunchWizard;
/**
* Amazon EC2 OverviewSection implementation that provides overview content for
* the EC2 Management functionality in the AWS Toolkit for Eclipse (links to
* docs, shortcuts for creating new EC2 Tomcat clusters, etc.)
*/
public class Ec2OverviewSection extends OverviewSection implements OverviewSection.V2 {
private static final String EC2_ECLIPSE_SCREENCAST_URL =
"http://d1un85p0f2qstc.cloudfront.net/eclipse/ec2/index.html" + "?" + AwsUrls.TRACKING_PARAMS;
/* (non-Javadoc)
* @see com.amazonaws.eclipse.core.ui.overview.OverviewSection#createControls(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createControls(Composite parent) {
Composite tasksSection = toolkit.newSubSection(parent, "Tasks");
toolkit.newListItem(tasksSection, "Launch Amazon EC2 instances",
null, openEc2LaunchWizard);
Composite resourcesSection = toolkit.newSubSection(parent, "Additional Resources");
this.toolkit.newListItem(resourcesSection,
"Video: Overview of Amazon EC2 Management in Eclipse",
EC2_ECLIPSE_SCREENCAST_URL, null);
}
/** Action to open the AWS EC2 launch wizard */
private IAction openEc2LaunchWizard = new Action() {
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new LaunchWizard("Overview"));
dialog.open();
}
};
}
| 7,201 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/StatusBar.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.ui.PreferenceLinkListener;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.SelectionTable.SelectionTableListener;
/**
* Common status bar for AWS views. It allows error messages to be displayed as
* well as provides feedback on when data is loading and what region is
* currently selected.
*/
public class StatusBar extends SwappableComposite implements SelectionTableListener, IPropertyChangeListener {
/** Label displaying data loading image indicator */
private Label progressImageLabel;
/** Label displaying data loading progress text */
private Label loadingLabel;
/** The image to display when data is being loaded */
private final Image progressImage;
/** Link displaying the currently selected EC2 region */
private Link regionLink;
/** Link displaying this status bar's error message */
private Link errorLink;
/** The error message this status bar is to display */
private String errorMessage;
/** Indicates that this */
private boolean isLoading;
/** The users AWS account info, so that we can update the error message based on its validity */
private final AccountInfo accountInfo;
/** Label for number of records that gets displayed */
private Label recordLabel;
/** Default value of record count */
private int recordCount = -1;
/** String for displaying Number of Records */
private String recordLabelText;
/** GridLayout for the Status Bar contents */
private GridLayout statusBarGridLayout;
/**
* Constructs a new StatusBar with the specified parent.
*/
public StatusBar(Composite parent) {
super(parent, SWT.NONE);
statusBarGridLayout = new GridLayout(2, false);
this.setLayout(statusBarGridLayout);
progressImage = Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh").createImage();
accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
AwsToolkitCore.getDefault().getPreferenceStore().addPropertyChangeListener(this);
updateStatusBar();
validateAccountInfo();
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
if (progressImage != null) {
progressImage.dispose();
}
AwsToolkitCore.getDefault().getPreferenceStore().removePropertyChangeListener(this);
super.dispose();
}
/*
* AmiSelectionTableListener Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.amis.AmiSelectionTable.AmiSelectionTableListener#finishedLoadingAmis()
*/
@Override
public void finishedLoadingData(int recordCount) {
this.recordCount = recordCount;
isLoading = false;
updateStatusBar();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.amis.AmiSelectionTable.AmiSelectionTableListener#loadingAmis()
*/
@Override
public void loadingData() {
isLoading = true;
updateStatusBar();
}
/*
* IPropertyChangeListener Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent event) {
validateAccountInfo();
}
/*
* Private Interface
*/
/**
* Updates the StatusBar based on the current status to decide what
* information to display. Error messages always preempt anything else so
* are shown no matter what other status is set. If no error messages are
* set and no data is loading, then the current region will be display as a
* clickable Link.
*/
private void updateStatusBar() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if ( !isDisposed() ) {
if ( errorMessage != null ) {
clearRegionLink();
clearLoadingMessageLabel();
displayErrorLink();
} else if ( isLoading ) {
clearErrorLink();
clearRegionLink();
displayLoadingMessageLabel();
} else {
clearErrorLink();
clearLoadingMessageLabel();
displayRegionLink();
}
layout();
getParent().layout();
}
}
});
}
/**
* Validates the current AWS account settings and appropriately updates the
* status bar.
*/
private void validateAccountInfo() {
if (accountInfo.isValid()) {
this.errorMessage = null;
} else {
errorMessage = "<a href=\"" + AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID + "\">" +
"AWS account not configured correctly</a>";
}
updateStatusBar();
}
/**
* Removes the error message link from this status bar.
*/
private void clearErrorLink() {
// Bail out if it's not there
if (errorLink == null) return;
errorLink.dispose();
errorLink = null;
}
/**
* Displays the error message link in this status bar.
*/
private void displayErrorLink() {
if (errorLink == null) {
errorLink = new Link(this, SWT.NONE);
errorLink.setText(errorMessage);
errorLink.addListener(SWT.Selection, new PreferenceLinkListener());
errorLink.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
}
/**
* Displays the loading message label in this status bar.
*/
private void displayLoadingMessageLabel() {
if (loadingLabel == null) {
statusBarGridLayout.horizontalSpacing = 5;
GridData gridData = new GridData();
progressImageLabel = new Label(this, SWT.NONE);
progressImageLabel.setImage(progressImage);
progressImageLabel.setLayoutData(gridData);
loadingLabel = new Label(this, SWT.NONE);
loadingLabel.setText("Loading...");
}
}
/**
* Removes the loading message label from this status bar.
*/
private void clearLoadingMessageLabel() {
if (loadingLabel != null) {
loadingLabel.dispose();
loadingLabel = null;
}
if (progressImageLabel != null) {
progressImageLabel.dispose();
progressImageLabel = null;
}
}
/**
* Displays the current region link in this status bar.
*/
private void displayRegionLink() {
// Bail out if the region link is already created
if (regionLink != null) {
//Update the AMI label with the current record count
//recordCount is in reset state implies either it was not computed or some error took place
if(recordCount > -1)
recordLabel.setText(recordLabelText + recordCount);
return;
}
Region defaultRegion = RegionUtils.getCurrentRegion();
String regionName = defaultRegion.getName();
statusBarGridLayout.horizontalSpacing = 30;
regionLink = new Link(this, SWT.NONE);
regionLink.setText("Region: <a href=\"" + Ec2Plugin.REGION_PREFERENCE_PAGE_ID + "\">" + regionName + "</a>");
regionLink.addListener(SWT.Selection, new PreferenceLinkListener());
recordLabel = new Label(this, SWT.NONE);
// recordCount is in reset state implies either it was not computed or some error took place
if (recordCount > -1)
recordLabel.setText(recordLabelText + recordCount);
recordLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
}
/**
* Removes the current region link from this status bar.
*/
private void clearRegionLink() {
// Bail out if it's not there
if (regionLink == null) return;
regionLink.dispose();
regionLink = null;
recordLabel.dispose();
recordLabel = null;
}
/**
* Sets the text that gets displayed for number of records. This should be potentially be
* set in the corresponding view.
*
* @param recordLabelText The string that needs to be displayed (Eg. Number of AMIs, Number of Instances, etc)
*/
public void setRecordLabel(String recordLabelText) {
this.recordLabelText = recordLabelText;
}
}
| 7,202 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SelectionTableComparator.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
/**
* Extension of ViewerComparator that knows which column it is sorting on, which
* direction, etc. Subclasses must implement the actual comparison logic.
*/
public abstract class SelectionTableComparator extends ViewerComparator {
/** The column on which this comparator is currently sorting */
protected int sortColumn;
/** The direction in which this comparator is currently sorting */
protected int sortDirection = SWT.UP;
/**
* Creates a new SelectionTableComparator set up to sort on the
* specified default sort column.
*
* @param defaultColumn
* The default column on which to sort.
*/
public SelectionTableComparator(int defaultColumn) {
sortColumn = defaultColumn;
}
/**
* Reverses the direction that this comparator is currently sorting.
*/
public void reverseDirection() {
sortDirection = (sortDirection == SWT.UP) ? SWT.DOWN : SWT.UP;
}
/**
* Returns the column currently being sorted on.
*
* @return The column currently being sorted on.
*/
public int getColumn() {
return sortColumn;
}
/**
* Returns the direction this comparator is currently sorting (SWT.UP or
* SWT.DOWN).
*
* @return The direction this comparator is currently sorting (SWT.UP or
* SWT.DOWN).
*/
public int getDirection() {
return sortDirection;
}
/**
* Sets the column on which this comparator sorts.
*
* @param sortColumn
* The column on which this comparator sorts.
*/
public void setColumn(int sortColumn) {
this.sortColumn = sortColumn;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
int comparison = compareIgnoringDirection(viewer, e1, e2);
return (sortDirection == SWT.UP) ? comparison : -comparison;
}
/**
* Returns a negative, zero, or positive number depending on whether the
* first element is less than, equal to, or greater than the second
* element. Subclasses must implement this method to do their actually
* comparison logic, but don't need to worry about the direction of this
* comparator since the compare(Viewer, Object, Object) method will take
* that into account before it returns the value produced by this
* method.
*
* @param viewer
* The viewer containing the data being compared.
* @param o1
* The first object being compared.
* @param o2
* The second object being compared.
*
* @return a negative number if the first element is less than the
* second element; the value <code>0</code> if the first element
* is equal to the second element; and a positive number if the
* first element is greater than the second element.
*/
protected abstract int compareIgnoringDirection(Viewer viewer, Object o1, Object o2);
}
| 7,203 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SelectionTableColumnClickListener.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.TreeColumn;
/**
* SelectionListener for SelectionTable columns to control sorting for the
* associated comparator.
*/
public class SelectionTableColumnClickListener extends SelectionAdapter {
/** The index of the column associated with this listener */
private final int columnIndex;
/** The comparator controlling sorting on the associated table */
private final SelectionTableComparator comparator;
/** The viewer associated with this column click listener */
private final TreeViewer viewer;
/**
* Creates a new SelectionTableColumnClickListener associated with the
* specified column and comparator.
*
* @param columnIndex
* The index of the column associated with this listener.
* @param comparator
* The comparator that controls sorting on the associated
* selection table.
*/
public SelectionTableColumnClickListener(int columnIndex, TreeViewer viewer, SelectionTableComparator comparator) {
this.columnIndex = columnIndex;
this.viewer = viewer;
this.comparator = comparator;
}
/* (non-Javadoc)
* @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
@Override
public void widgetSelected(SelectionEvent e) {
TreeColumn treeColumn = (TreeColumn)e.getSource();
viewer.getTree().setSortColumn(treeColumn);
// If we're already sorting in this column and the user
// clicks on it, we want to reverse the sort direction.
if (comparator.getColumn() == columnIndex) {
comparator.reverseDirection();
}
comparator.setColumn(columnIndex);
viewer.getTree().setSortDirection(comparator.getDirection());
viewer.refresh();
}
}
| 7,204 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/HelpLinkListener.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.PlatformUI;
/**
* Implementation of Listener that opens the help documentation referenced by
* the text in the event object.
*/
public class HelpLinkListener implements Listener {
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
@Override
public void handleEvent(Event event) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(event.text);
}
}
| 7,205 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SetupExternalToolsAction.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.dialogs.PreferencesUtil;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
/**
* Action subclass for configuring external tool preferences.
*/
public class SetupExternalToolsAction extends Action {
/** The id of the preference page to display */
private static final String EXTERNAL_TOOLS_PREFERENCE_PAGE_ID =
"com.amazonaws.eclipse.ec2.preferences.ExternalToolsPreferencePage";
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(
null, EXTERNAL_TOOLS_PREFERENCE_PAGE_ID, new String[] {EXTERNAL_TOOLS_PREFERENCE_PAGE_ID}, null);
dialog.open();
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("configure");
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Configure your external tools";
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Configure your external tools";
}
}
| 7,206 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SwappableComposite.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
/**
* A SwappableComposite allows only one of its children to be displayed at
* once. When one child is displayed, all the others are hidden.
*/
public class SwappableComposite extends Composite {
/**
* Creates a new SwappableComposite with the specified parent and SWT
* style.
*
* @param parent
* The parent of this composite.
* @param style
* The SWT style for this composite.
*/
public SwappableComposite(Composite parent, int style) {
super (parent, style);
}
/**
* Displays the specified composite and hides all other child
* composites.
*
* @param composite
* The child Composite to display.
*/
public void setActiveComposite(Control composite) {
if (composite == null) return;
for (Control control : getChildren()) {
if (composite.equals(control)) {
control.setVisible(true);
control.setBounds(getClientArea());
control.getParent().layout();
} else {
control.setVisible(false);
}
}
}
}
| 7,207 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/SetupAwsAccountAction.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.dialogs.PreferencesUtil;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
/**
* Action subclass for configuring AWS account information.
*/
public class SetupAwsAccountAction extends Action {
/** The id of the preference page to display */
private static final String EC2_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage";
private static final String KEYPAIR_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.ec2.preferences.KeyPairsPreferencePage";
private static final String REGION_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.core.ui.preferences.RegionsPreferencePage";
private static final String EXTERNALTOOL_PREFERENCE_PAGE_ID = "com.amazonaws.eclipse.ec2.preferences.ExternalToolsPreferencePage";
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(
null, EC2_PREFERENCE_PAGE_ID, new String[] {EC2_PREFERENCE_PAGE_ID, EXTERNALTOOL_PREFERENCE_PAGE_ID, KEYPAIR_PREFERENCE_PAGE_ID, REGION_PREFERENCE_PAGE_ID}, null);
dialog.open();
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("configure");
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Configure your AWS account info";
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Configure your AWS account information";
}
}
| 7,208 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ShellCommandErrorDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.ec2.ShellCommandException;
import com.amazonaws.eclipse.ec2.ShellCommandResults;
/**
* Dialog for showing the details of a failed attempt at executing a command,
* including support for possible retries, and directing users to more help.
*/
public class ShellCommandErrorDialog extends MessageDialog {
private final ShellCommandException sce;
private Text outputText;
private Text errorOutputText;
private List<Button> attemptRadioButtons = new LinkedList<>();
/**
* Creates a new ShellCommandErrorDialog, ready to be opened and display
* information the specified ShellCommandException.
*
* @param sce
* The ShellCommandException to display.
*/
public ShellCommandErrorDialog(ShellCommandException sce) {
super(Display.getDefault().getShells()[0],
"Error Executing Command",
null,
sce.getMessage(),
MessageDialog.ERROR,
new String[] {"Ok"},
1);
this.sce = sce;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setLayout(new GridLayout(1, false));
if (sce.getNumberOfAttempts() > 1) {
createAttemptSelectionArea(composite);
attemptRadioButtons.get(0).setSelection(true);
}
createCommandOutputArea(composite);
createHelpLinkArea(composite);
update();
return composite;
}
/*
* Private Interface
*/
/**
* Creates a new UI section displaying a link where users can go for more
* help.
*
* @param composite
* The parent composite for this new section.
*/
private void createHelpLinkArea(Composite composite) {
Link link = new Link(composite, SWT.WRAP);
link.setText("Need help? " +
"<a href=\"http://aws.amazon.com/eclipse/\">http://aws.amazon.com/eclipse/</a>");
WebLinkListener webLinkListener = new WebLinkListener();
link.addListener(SWT.Selection, webLinkListener);
}
/**
* Creates a new UI section displaying the details of the selected attempt
* to execute a command.
*
* @param composite
* The parent composite for this new section.
*/
private void createCommandOutputArea(Composite composite) {
Composite outputComposite = new Composite(composite, SWT.NONE);
outputComposite.setLayout(new GridLayout(1, false));
outputComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Group outputGroup = new Group(outputComposite, SWT.None);
outputGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
outputGroup.setLayout(new GridLayout(2, false));
outputGroup.setText("Command Output:");
newLabel(outputGroup, "Output:");
outputText = newText(outputGroup, "");
newLabel(outputGroup, "Errors:");
errorOutputText = newText(outputGroup, "");
}
/**
* Creates a new UI section displaying a list of attempts that a user can
* select to see more information.
*
* @param composite
* The parent composite for this new section.
*/
private void createAttemptSelectionArea(Composite composite) {
Composite attemptsComposite = new Composite(composite, SWT.NONE);
attemptsComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
attemptsComposite.setLayout(new GridLayout(1, true));
Group attemptsGroup = new Group(attemptsComposite, SWT.None);
attemptsGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
attemptsGroup.setLayout(new GridLayout(1, false));
Label l = new Label(attemptsGroup, SWT.WRAP);
l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
l.setText("Select an attempt to see the output from it:");
SelectionListener listener = new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
@Override
public void widgetSelected(SelectionEvent e) {
update();
}
};
attemptRadioButtons = new LinkedList<>();
for (ShellCommandResults results : sce.getShellCommandResults()) {
Button button = new Button(attemptsGroup, SWT.RADIO);
button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
attemptRadioButtons.add(button);
button.addSelectionListener(listener);
button.setText("Attempt " + attemptRadioButtons.size()
+ " (exit code: " + results.exitCode + ")");
button.setData(results);
}
}
/**
* Returns the ShellCommandResults associated with the selected command
* execution attempt.
*
* @return The ShellCommandResults associated with the selected attempt.
*/
private ShellCommandResults getSelectedAttempt() {
for (Button button : attemptRadioButtons) {
if (button.getSelection()) {
return (ShellCommandResults)button.getData();
}
}
return sce.getShellCommandResults().get(0);
}
/**
* Updates the command output section so that the correct output is
* displayed based on what command execution attempt is selected.
*/
private void update() {
ShellCommandResults results = getSelectedAttempt();
outputText.setText(results.output);
errorOutputText.setText(results.errorOutput);
}
/**
* Utility method for creating a Text widget.
*/
private Text newText(Composite composite, String s) {
Text text = new Text(composite, SWT.READ_ONLY | SWT.BORDER | SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
text.setText(s);
GridData data = new GridData(GridData.FILL_BOTH);
data.minimumHeight = 80;
data.heightHint = 100;
data.minimumWidth = 100;
data.widthHint = 250;
text.setLayoutData(data);
return text;
}
/**
* Utility method for creating a Label widget.
*/
private Label newLabel(Composite outputComposite, String text) {
Label label = new Label(outputComposite, SWT.NONE);
label.setText(text);
GridData data = new GridData();
data.verticalAlignment = SWT.TOP;
label.setLayoutData(data);
return label;
}
}
| 7,209 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/SecurityGroupTableProvider.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import java.util.List;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.model.SecurityGroup;
/**
* Label and content provider for the security group selection table.
*/
class SecurityGroupTableProvider extends LabelProvider
implements ITreeContentProvider, ITableLabelProvider {
List<SecurityGroup> securityGroups;
/*
* IStructuredContentProvider
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
if (!(newInput instanceof List)) return;
securityGroups = (List<SecurityGroup>)newInput;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.BaseLabelProvider#dispose()
*/
@Override
public void dispose() {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object parent) {
return securityGroups.toArray();
}
/*
* ITableLabelProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object obj, int index) {
if (!(obj instanceof SecurityGroup)) return "???";
SecurityGroup securityGroup = (SecurityGroup)obj;
switch (index) {
case 0:
return securityGroup.getGroupName();
case 1:
return securityGroup.getDescription();
}
return "N/A";
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object obj, int index) {
if (index == 0)
return Ec2Plugin.getDefault().getImageRegistry().get("shield");
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
*/
@Override
public Image getImage(Object obj) {
return null;
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
| 7,210 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/SecurityGroupView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import com.amazonaws.eclipse.core.AccountAndRegionChangeListener;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.ui.StatusBar;
/**
* View to display security groups and their permission.
*/
public class SecurityGroupView extends ViewPart implements IRefreshable {
private SecurityGroupSelectionComposite securityGroupSelectionComposite;
private PermissionsComposite permissionsComposite;
/**
* Listener for AWS account and region preference changes that require this
* view to be refreshed.
*/
AccountAndRegionChangeListener accountAndRegionChangeListener = new AccountAndRegionChangeListener() {
@Override
public void onAccountOrRegionChange() {
SecurityGroupView.this.refreshData();
}
};
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(1, false);
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.verticalSpacing = 2;
parent.setLayout(layout);
StatusBar statusBar = new StatusBar(parent);
statusBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
securityGroupSelectionComposite = new SecurityGroupSelectionComposite(sashForm);
permissionsComposite = new PermissionsComposite(sashForm);
securityGroupSelectionComposite.setListener(statusBar);
/*
* The security group table and the permissions table need to communicate with
* each other when certain events happen. It'd be a little nicer to have them
* isolated from each other with some sort of event/listener, but for now we
* can simply have them be aware of each other.
*/
securityGroupSelectionComposite.setPermissionsComposite(permissionsComposite);
permissionsComposite.setSecurityGroupComposite(securityGroupSelectionComposite);
sashForm.setWeights(new int[] {50, 50});
securityGroupSelectionComposite.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
permissionsComposite.refreshPermissions();
}
});
contributeToActionBars();
}
@Override
public void init(IViewSite aSite, IMemento aMemento) throws PartInitException {
super.init(aSite, aMemento);
AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().addDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().addDefaultRegionChangeListener(accountAndRegionChangeListener);
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
public void dispose() {
AwsToolkitCore.getDefault().getAccountManager().removeAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().removeDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(accountAndRegionChangeListener);
super.dispose();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(securityGroupSelectionComposite.getRefreshSecurityGroupsAction());
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
@Override
public void setFocus() {}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
if (securityGroupSelectionComposite != null) {
securityGroupSelectionComposite.getRefreshSecurityGroupsAction().run();
}
}
}
| 7,211 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/CreateSecurityGroupDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to collect information on creating a new security group.
*/
public class CreateSecurityGroupDialog extends Dialog {
/** The Text control for the security group name */
private Text groupNameText;
/** String to save the security group name after the controls are disposed */
private String groupName;
/** The Text control for the security group description */
private Text descriptionText;
/** String to save the security group description after the controls are disposed */
private String groupDescription;
/**
* Creates a new security group creation dialog ready to be displayed.
*
* @param parentShell The parent shell for this dialog.
*/
public CreateSecurityGroupDialog(Shell parentShell) {
super(parentShell);
}
/*
* Dialog Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = createComposite(parent);
createLabel("Security Group Name:", composite, 2);
groupNameText = createTextBox(composite, 2);
createLabel("Description:", composite, 2);
descriptionText = createTextBox(composite, 2);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
groupName = groupNameText.getText();
groupDescription = descriptionText.getText();
super.okPressed();
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createButtonBar(Composite parent) {
Control control = super.createButtonBar(parent);
updateOkButton();
return control;
}
/*
* Public Interface
*/
/**
* Returns the security group name that the user entered.
*
* @return The security group name that the user entered.
*/
public String getSecurityGroupName() {
return groupName;
}
/**
* Returns the security group description that the user entered.
*
* @return The security group description that the user entered.
*/
public String getSecurityGroupDescription() {
return groupDescription;
}
/*
* Private Interface
*/
private Label createLabel(String text, Composite parent, int columnSpan) {
Label label = new Label(parent, SWT.NONE);
label.setText(text);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_END;
gridData.horizontalSpan = columnSpan;
gridData.verticalIndent = 2;
label.setLayoutData(gridData);
return label;
}
private Text createTextBox(Composite parent, int columnSpan) {
Text text = new Text(parent, SWT.BORDER);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = columnSpan;
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
text.setLayoutData(gridData);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateOkButton();
}
});
return text;
}
private Composite createComposite(Composite parent) {
Composite composite = new Composite(parent, SWT.BORDER);
GridLayout gridLayout = new GridLayout(2, false);
gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
gridLayout.verticalSpacing = convertVerticalDLUsToPixels(1);
gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
/**
* Validates the user input and enables or disables the Ok button as necessary.
*/
private void updateOkButton() {
boolean b = true;
if (descriptionText == null || descriptionText.getText().length() == 0) {
b = false;
}
if (groupNameText == null || groupNameText.getText().length() == 0) {
b = false;
}
Button okButton = getButton(IDialogConstants.OK_ID);
if (okButton != null) {
okButton.setEnabled(b);
}
}
}
| 7,212 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/PermissionsComposite.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsRequest;
import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult;
import com.amazonaws.services.ec2.model.IpPermission;
import com.amazonaws.services.ec2.model.RevokeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.SecurityGroup;
import com.amazonaws.services.ec2.model.UserIdGroupPair;
/**
* Selection table for users to select individual permissions in a security
* group.
*/
public class PermissionsComposite extends SelectionTable {
private PermissionsTableProvider permissionsTableProvider = new PermissionsTableProvider();
private Action addPermissionAction;
private Action removePermissionAction;
private SecurityGroupSelectionComposite securityGroupSelectionComposite;
/**
* Comparator to sort permissions.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
class IpPermissionComparator extends ViewerComparator {
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof IpPermission && e2 instanceof IpPermission)) {
return 0;
}
IpPermission ipPermission1 = (IpPermission)e1;
IpPermission ipPermission2 = (IpPermission)e2;
int comparision = ipPermission1.getIpProtocol().compareTo(ipPermission2.getIpProtocol());
if (comparision == 0) {
comparision = ipPermission1.getFromPort() - ipPermission2.getFromPort();
}
return comparision;
}
}
/**
* Content and label provider for security group permission details.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
private class PermissionsTableProvider extends LabelProvider implements ITreeContentProvider, ITableLabelProvider {
private List<IpPermission> ipPermissions;
/*
* IStructuredContentProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
if (ipPermissions == null) {
return null;
}
return ipPermissions.toArray();
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof List) {
ipPermissions = (List<IpPermission>)newInput;
}
}
/*
* ITableLableProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object element, int columnIndex) {
if (!(element instanceof IpPermission)) {
return "???";
}
IpPermission ipPermission = (IpPermission)element;
switch (columnIndex) {
case 0:
return ipPermission.getIpProtocol();
case 1:
return formatPortRange(ipPermission);
case 2:
return formatUidGroupPairs(ipPermission);
case 3:
return formatIpRanges(ipPermission);
}
return "?";
}
private String formatIpRanges(IpPermission ipPermission) {
StringBuilder builder = new StringBuilder();
for (String s : ipPermission.getIpRanges()) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(s);
}
return builder.toString();
}
private String formatUidGroupPairs(IpPermission ipPermission) {
StringBuilder builder = new StringBuilder();
for (UserIdGroupPair s : ipPermission.getUserIdGroupPairs()) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(s.getUserId() + ":" + (s.getGroupName() == null ? s.getGroupId() : s.getGroupName()));
}
return builder.toString();
}
private String formatPortRange(IpPermission ipPermission) {
Integer fromPort = ipPermission.getFromPort();
Integer toPort = ipPermission.getToPort();
if (fromPort == null || toPort == null) {
return "";
} else if (fromPort.intValue() == toPort.intValue()) {
return Integer.toString(fromPort);
} else {
return fromPort + " - " + toPort;
}
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
/**
* Creates a new PermissionsComposite with the specified parent.
*
* @param parent the parent of this new Composite.
*/
public PermissionsComposite(Composite parent) {
super(parent);
viewer.setContentProvider(permissionsTableProvider);
viewer.setLabelProvider(permissionsTableProvider);
viewer.setComparator(new IpPermissionComparator());
}
/**
* Refreshes the data in the permissions table
*/
public void refreshPermissions() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
SecurityGroup selectedSecurityGroup = securityGroupSelectionComposite.getSelectedSecurityGroup();
if (selectedSecurityGroup == null) {
setInput(new ArrayList<IpPermission>());
return;
}
String groupId = selectedSecurityGroup.getGroupId();
new RefreshPermissionsThread(groupId).start();
}
});
}
/**
* Sets the security group selection table that controls which security
* group's permissions are shown in this selection table.
*
* @param securityGroupSelectionComposite
* The security group selection table that controls which
* security group's permissions are shown in this selection
* table.
*/
public void setSecurityGroupComposite(
SecurityGroupSelectionComposite securityGroupSelectionComposite) {
this.securityGroupSelectionComposite = securityGroupSelectionComposite;
}
/**
* Returns the currently selected permission.
*
* @return The currently selected permission.
*/
public IpPermission getSelectedIpPermission() {
Object obj = this.getSelection();
return (IpPermission)obj;
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
if (securityGroupSelectionComposite.getSelectedSecurityGroup() == null) {
addPermissionAction.setEnabled(false);
} else {
addPermissionAction.setEnabled(true);
}
if (this.getSelection() == null) {
removePermissionAction.setEnabled(false);
} else {
removePermissionAction.setEnabled(true);
}
manager.add(addPermissionAction);
manager.add(removePermissionAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
addPermissionAction = new AwsAction(AwsToolkitMetricType.EXPLORER_EC2_ADD_PERMISSIONS_TO_SECURITY_GROUP) {
@Override
public void doRun() {
String securityGroup = securityGroupSelectionComposite.getSelectedSecurityGroup().getGroupName();
EditSecurityGroupPermissionEntryDialog dialog = new EditSecurityGroupPermissionEntryDialog(Display.getCurrent().getActiveShell(), securityGroup);
if (dialog.open() != IDialogConstants.OK_ID) {
actionCanceled();
} else {
new AuthorizePermissionsThread(securityGroup, dialog).start();
actionSucceeded();
}
actionFinished();
}
};
addPermissionAction.setText("Add Permissions...");
addPermissionAction.setToolTipText("Add new permissions to the selected security group");
addPermissionAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("add"));
removePermissionAction = new AwsAction(AwsToolkitMetricType.EXPLORER_EC2_REMOVE_PERMISSIONS_FROM_SECURITY_GROUP) {
@Override
public void doRun() {
String securityGroup = securityGroupSelectionComposite.getSelectedSecurityGroup().getGroupName();
new RevokePermissionsThread(securityGroup, getSelectedIpPermission()).start();
actionFinished();
}
};
removePermissionAction.setText("Remove Permissions");
removePermissionAction.setToolTipText("Remove the selected permission from the selected security group");
removePermissionAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Protocol", 10);
newColumn("Port", 10);
newColumn("User:Group", 10);
newColumn("Source CIDR", 70);
}
/**
* Sets the input for this permissions composite, ensuring that the widgets
* are updated in the UI thread.
*
* @param ipPermissions
* The list of permissions to display in this permissions
* composite.
*/
private void setInput(final List<IpPermission> ipPermissions) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(ipPermissions);
packColumns();
}
});
}
/*
* Private Threads for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to list all permissions in an
* EC2 security group.
*/
private class RefreshPermissionsThread extends Thread {
private final String groupId;
/**
* Creates a new RefreshPermissionsThread ready to be started to query
* the permissions in the specified EC2 security group and update the
* permissions list widget.
*
* @param groupId
* The EC2 security group whose permissions are to be
* refreshed.
*/
public RefreshPermissionsThread(String groupId) {
this.groupId = groupId;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
DescribeSecurityGroupsRequest request = new DescribeSecurityGroupsRequest()
.withGroupIds(groupId);
DescribeSecurityGroupsResult response = getAwsEc2Client().describeSecurityGroups(request);
List<SecurityGroup> securityGroups = response.getSecurityGroups();
if (securityGroups.isEmpty()) return;
setInput(securityGroups.get(0).getIpPermissions());
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to refresh security group permissions: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
/**
* Thread for making an EC2 service call to authorize new permissions in an
* EC2 security group.
*/
private class AuthorizePermissionsThread extends Thread {
private final EditSecurityGroupPermissionEntryDialog dialog;
private final String securityGroup;
/**
* Creates a new AuthorizePermissionsThread ready to be run to add the
* permissions detailed in the specified permission entry dialog to the
* specified security group.
*
* @param securityGroup
* The security group in which to authorize the new
* permissions.
* @param dialog
* The permission entry dialog containing the user input on
* what permissions to authorize.
*/
public AuthorizePermissionsThread(String securityGroup, EditSecurityGroupPermissionEntryDialog dialog) {
this.securityGroup = securityGroup;
this.dialog = dialog;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
if (dialog.isUserGroupPermission()) {
String groupName = dialog.getUserGroupPermissionComposite().getSecurityGroup();
String userId = dialog.getUserGroupPermissionComposite().getUserId();
AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest();
request.setGroupName(securityGroup);
request.setSourceSecurityGroupName(groupName);
request.setSourceSecurityGroupOwnerId(userId);
getAwsEc2Client().authorizeSecurityGroupIngress(request);
} else {
String protocol = dialog.getPortRangePermissionComposite().getProtocol();
int fromPort = dialog.getPortRangePermissionComposite().getFromPort();
int toPort = dialog.getPortRangePermissionComposite().getToPort();
String networkMask = dialog.getPortRangePermissionComposite().getNetwork();
AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest();
request.setGroupName(securityGroup);
request.setIpProtocol(protocol);
request.setFromPort(fromPort);
request.setToPort(toPort);
request.setCidrIp(networkMask);
getAwsEc2Client().authorizeSecurityGroupIngress(request);
}
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to add permission to group: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.LOG);
}
refreshPermissions();
}
}
/**
* Thread for making an EC2 service call to revoke specified permissions in
* an EC2 security group.
*/
private class RevokePermissionsThread extends Thread {
private final IpPermission ipPermission;
private final String securityGroup;
/**
* Creates a new RevokePermissionsThread ready to be run to remove the
* specified permissions from the specified EC2 security group.
*
* @param securityGroup
* The group from which to revoke permissions.
* @param permission
* The permissions to revoke.
*/
public RevokePermissionsThread(String securityGroup, IpPermission permission) {
this.securityGroup = securityGroup;
this.ipPermission = permission;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 client = getAwsEc2Client();
if (ipPermission.getUserIdGroupPairs().isEmpty()) {
for (String ipRange : ipPermission.getIpRanges()) {
RevokeSecurityGroupIngressRequest request = new RevokeSecurityGroupIngressRequest();
request.setGroupName(securityGroup);
request.setIpProtocol(ipPermission.getIpProtocol());
request.setFromPort(ipPermission.getFromPort());
request.setToPort(ipPermission.getToPort());
request.setCidrIp(ipRange);
client.revokeSecurityGroupIngress(request);
}
} else {
for (UserIdGroupPair pair : ipPermission.getUserIdGroupPairs()) {
RevokeSecurityGroupIngressRequest request = new RevokeSecurityGroupIngressRequest();
request.setGroupName(securityGroup);
request.setSourceSecurityGroupName(pair.getGroupName());
request.setSourceSecurityGroupOwnerId(pair.getUserId());
getAwsEc2Client().revokeSecurityGroupIngress(request);
}
}
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to remove security group permissions: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.LOG);
}
refreshPermissions();
}
}
}
| 7,213 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/SecurityGroupSelectionComposite.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.DeleteSecurityGroupRequest;
import com.amazonaws.services.ec2.model.SecurityGroup;
/**
* Selection table containing a list of security groups.
*/
public class SecurityGroupSelectionComposite extends SelectionTable {
private Action createSecurityGroupAction;
private Action deleteSecurityGroupAction;
private Action refreshSecurityGroupsAction;
private SecurityGroupTableProvider securityGroupTableProvider = new SecurityGroupTableProvider();
private PermissionsComposite permissionsComposite;
/**
* Creates a new security group selection table parented by the specified
* composite.
*
* @param parent
* The parent of this new selection table.
*/
public SecurityGroupSelectionComposite(Composite parent) {
super(parent);
viewer.setContentProvider(securityGroupTableProvider);
viewer.setLabelProvider(securityGroupTableProvider);
viewer.setComparator(new SecurityGroupComparator());
refreshSecurityGroups();
}
/**
* Sets the optional security group permissions selection table that can be
* linked with this security group selection table.
*
* @param permissionsComposite
* The security group permissions selection table that is linked
* with this security group selection table.
*/
public void setPermissionsComposite(PermissionsComposite permissionsComposite) {
this.permissionsComposite = permissionsComposite;
}
/**
* Returns the currently selected security group.
*
* @return The currently selected security group.
*/
public SecurityGroup getSelectedSecurityGroup() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
return (SecurityGroup)selection.getFirstElement();
}
/*
* Action Accessors
*/
public Action getRefreshSecurityGroupsAction() {
return refreshSecurityGroupsAction;
}
public Action getCreateSecurityGroupAction() {
return createSecurityGroupAction;
}
public Action getDeleteSecurityGroupAction() {
return deleteSecurityGroupAction;
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Name", 20);
newColumn("Description", 80);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
deleteSecurityGroupAction.setEnabled(getSelectedSecurityGroup() != null);
manager.add(refreshSecurityGroupsAction);
manager.add(new Separator());
manager.add(createSecurityGroupAction);
manager.add(deleteSecurityGroupAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
createSecurityGroupAction = new AwsAction(AwsToolkitMetricType.EXPLORER_EC2_NEW_SECURITY_GROUP) {
@Override
public void doRun() {
final CreateSecurityGroupDialog dialog = new CreateSecurityGroupDialog(Display.getCurrent().getActiveShell());
if (dialog.open() != Dialog.OK) {
actionCanceled();
} else {
new CreateSecurityGroupThread(dialog.getSecurityGroupName(), dialog.getSecurityGroupDescription()).start();
actionSucceeded();
}
actionFinished();
}
};
createSecurityGroupAction.setText("New Group...");
createSecurityGroupAction.setToolTipText("Create a new security group");
createSecurityGroupAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("add"));
deleteSecurityGroupAction = new AwsAction(AwsToolkitMetricType.EXPLORER_EC2_DELETE_SECURITY_GROUP) {
@Override
public void doRun() {
new DeleteSecurityGroupThread(getSelectedSecurityGroup()).start();
actionFinished();
}
};
deleteSecurityGroupAction.setText("Delete Group");
deleteSecurityGroupAction.setToolTipText("Delete security group");
deleteSecurityGroupAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
refreshSecurityGroupsAction = new AwsAction(AwsToolkitMetricType.EXPLORER_EC2_REFRESH_SECURITY_GROUP) {
@Override
public void doRun() {
refreshSecurityGroups();
actionFinished();
}
};
refreshSecurityGroupsAction.setText("Refresh");
refreshSecurityGroupsAction.setToolTipText("Refresh security groups");
refreshSecurityGroupsAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
}
/*
* Private Interface
*/
private void refreshSecurityGroups() {
new RefreshSecurityGroupsThread().start();
}
private class SecurityGroupComparator extends ViewerComparator {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof SecurityGroup && e2 instanceof SecurityGroup)) {
return 0;
}
SecurityGroup securityGroup1 = (SecurityGroup)e1;
SecurityGroup securityGroup2 = (SecurityGroup)e2;
return (securityGroup1.getGroupName().compareTo(securityGroup2.getGroupName()));
}
}
/**
* Sets the list of security groups to display in the security group table.
*
* @param securityGroups
* The security groups to display.
*/
private void setInput(final List<SecurityGroup> securityGroups) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
final SecurityGroup previouslySelectedGroup = getSelectedSecurityGroup();
viewer.setInput(securityGroups);
if (previouslySelectedGroup != null) {
for (int index = 0; index < viewer.getTree().getItemCount(); index++) {
TreeItem treeItem = viewer.getTree().getItem(index);
SecurityGroup groupDescription = (SecurityGroup)treeItem.getData();
if (groupDescription.getGroupName().equals(previouslySelectedGroup.getGroupName())) {
viewer.getTree().select(treeItem);
}
}
}
viewer.getTree().getColumn(0).pack();
viewer.getTree().layout();
layout();
}
});
}
/*
* Private Thread subclasses for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to create a new security group.
*/
private class CreateSecurityGroupThread extends Thread {
/** The requested name of the group */
private final String name;
/** The requested description of the group */
private final String description;
/**
* Creates a new thread ready to be started to create the specified
* security group.
*
* @param name
* The requested name for the new security group.
* @param description
* The requested description for the new security group.
*/
public CreateSecurityGroupThread(final String name, final String description) {
this.name = name;
this.description = description;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = getAwsEc2Client();
CreateSecurityGroupRequest request = new CreateSecurityGroupRequest();
request.setGroupName(name);
request.setDescription(description);
ec2.createSecurityGroup(request);
refreshSecurityGroups();
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to create security group: " + e.getMessage(), e);
StatusManager.getManager().handle(status,
StatusManager.SHOW | StatusManager.LOG);
}
}
}
/**
* Thread for making an EC2 service call to delete a security group.
*/
private class DeleteSecurityGroupThread extends Thread {
/** The security group to delete */
private final SecurityGroup securityGroup;
/**
* Creates a new thread ready to be started and delete the specified
* security group.
*
* @param securityGroup
* The security group to delete.
*/
public DeleteSecurityGroupThread(final SecurityGroup securityGroup) {
this.securityGroup = securityGroup;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = getAwsEc2Client();
DeleteSecurityGroupRequest request = new DeleteSecurityGroupRequest();
request.setGroupName(securityGroup.getGroupName());
ec2.deleteSecurityGroup(request);
refreshSecurityGroups();
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to delete security group: " + e.getMessage(), e);
StatusManager.getManager().handle(status,
StatusManager.SHOW | StatusManager.LOG);
}
}
}
/**
* Thread for making an EC2 serivce call to list all security groups.
*/
private class RefreshSecurityGroupsThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
if (selectionTableListener != null) selectionTableListener.loadingData();
AmazonEC2 ec2 = getAwsEc2Client();
final List<SecurityGroup> securityGroups = ec2.describeSecurityGroups().getSecurityGroups();
setInput(securityGroups);
if (permissionsComposite != null) permissionsComposite.refreshPermissions();
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to refresh security groups: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
} finally {
if (selectionTableListener != null) selectionTableListener.finishedLoadingData(-1);
}
}
}
}
| 7,214 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/securitygroups/EditSecurityGroupPermissionEntryDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.securitygroups;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.ec2.ui.SwappableComposite;
/**
* Dialog to collect user input on a security group permission entry.
*/
public class EditSecurityGroupPermissionEntryDialog extends Dialog {
private final String securityGroupName;
private SwappableComposite swappableComposite;
private UserGroupPermissionComposite userGroupComposite;
private PortRangePermissionComposite portRangeComposite;
private Button userGroupPermissionButton;
private Button portRangePermissionButton;
private boolean isUserGroupPermission;
public EditSecurityGroupPermissionEntryDialog(Shell parentShell, String securityGroupName) {
super(parentShell);
this.securityGroupName = securityGroupName;
}
public UserGroupPermissionComposite getUserGroupPermissionComposite() {
return userGroupComposite;
}
public PortRangePermissionComposite getPortRangePermissionComposite() {
return portRangeComposite;
}
public boolean isUserGroupPermission() {
return isUserGroupPermission;
}
/*
* Dialog Interface
*/
/*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createButtonBar(Composite parent) {
Control control = super.createButtonBar(parent);
updateOkButton();
return control;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = createComposite(parent);
createLabel("Assign permissions by:", composite, 1);
portRangePermissionButton = createRadioButton("Protocol, port and network", composite, 2);
userGroupPermissionButton = createRadioButton("AWS user and group", composite, 2);
swappableComposite = new SwappableComposite(composite, SWT.NONE);
swappableComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
userGroupComposite = new UserGroupPermissionComposite(swappableComposite);
portRangeComposite = new PortRangePermissionComposite(swappableComposite);
SelectionListener listener = new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
if (e.getSource().equals(userGroupPermissionButton)) {
swappableComposite.setActiveComposite(userGroupComposite);
} else {
swappableComposite.setActiveComposite(portRangeComposite);
}
}
};
userGroupPermissionButton.addSelectionListener(listener);
portRangePermissionButton.addSelectionListener(listener);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#create()
*/
@Override
public void create() {
super.create();
Point p = portRangeComposite.computeSize(SWT.DEFAULT, SWT.DEFAULT);
Rectangle r = userGroupComposite.getParent().getClientArea();
if (r.width > p.x) p.x = r.width;
swappableComposite.setSize(p);
// Start off with the user / group permission style selected
portRangePermissionButton.setSelection(true);
swappableComposite.setActiveComposite(portRangeComposite);
getShell().layout();
getShell().setSize(getShell().computeSize(SWT.DEFAULT,SWT.DEFAULT));
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
userGroupComposite.saveFieldValues();
portRangeComposite.saveFieldValues();
this.isUserGroupPermission = userGroupPermissionButton.getSelection();
super.okPressed();
}
/*
* Private Classes
*/
/**
* Composite with options for defining security group permissions
* by AWS user IDs and groups.
*/
class UserGroupPermissionComposite extends Composite {
private Text securityGroupText;
private Text userIdText;
private String securityGroup;
private String userId;
/**
* Creates a new composite with the specified parent.
*
* @param parent The parent for this composite.
*/
public UserGroupPermissionComposite(Composite parent) {
super(parent, SWT.NONE);
create();
}
public void saveFieldValues() {
securityGroup = securityGroupText.getText();
userId = userIdText.getText();
}
public String getSecurityGroup() {
return securityGroup;
}
public String getUserId() {
return userId;
}
public boolean isComplete() {
if (securityGroupText == null || securityGroupText.getText().length() == 0) return false;
if (userIdText == null || userIdText.getText().length() == 0) return false;
return true;
}
private void create() {
GridLayout gridLayout = new GridLayout(1, true);
gridLayout.marginWidth = 0;
setLayout(gridLayout);
createLabel("AWS User ID:", this, 1);
userIdText = createTextBox(this, 1);
createLabel("AWS Security Group:", this, 1);
securityGroupText = createTextBox(this, 1);
pack();
}
}
/**
* Composite with options for defining security group permissions
* by protocol, port and network mask.
*/
class PortRangePermissionComposite extends Composite {
private Combo protocolCombo;
private Text portText;
private Text networkText;
private String protocol;
private String network;
private int fromPort;
private int toPort;
private final Pattern networkMaskPattern = Pattern.compile("\\d+\\.\\d+\\.\\d+\\.\\d+/\\d+");
/**
* Creates new composite with the specified parent.
*
* @param parent The parent of this composite.
*/
public PortRangePermissionComposite(Composite parent) {
super (parent, SWT.NONE);
create();
}
public String getNetwork() {
return network;
}
public int getFromPort() {
return fromPort;
}
public int getToPort() {
return toPort;
}
public String getProtocol() {
return protocol.toLowerCase();
}
public void saveFieldValues() {
protocol = protocolCombo.getText();
network = networkText.getText();
Integer[] ports = extractPortRange();
if (ports != null) {
fromPort = ports[0];
toPort = ports[1];
}
}
/**
* Parses the user entered port value and extracts a port range returned
* as a two element list of integers. If invalid input is detected null
* is returned.
*
* @return An array of two elements where the first element is the
* starting port in the port range and the second is the ending
* port in the port range. If invalid input was entered null
* will be returned.
*/
private Integer[] extractPortRange() {
if (portText == null) return null;
String portInfo = portText.getText().trim();
int port1, port2;
if (portInfo.contains("-") && !portInfo.startsWith("-")) {
String[] strings = portInfo.split("-");
if (strings.length != 2) return null;
try {
port1 = Integer.parseInt(strings[0].trim());
port2 = Integer.parseInt(strings[1].trim());
} catch (NumberFormatException nfe) {
return null;
}
} else {
try {
port1 = Integer.parseInt(portInfo.trim());
port2 = port1;
} catch (NumberFormatException nfe) {
return null;
}
}
if (port2 < port1) return null;
return new Integer[] {port1, port2};
}
public boolean isComplete() {
if (extractPortRange() == null) return false;
if (networkText == null) return false;
Matcher matcher = networkMaskPattern.matcher(networkText.getText());
if (!matcher.matches()) return false;
return true;
}
private void create() {
GridLayout gridLayout = new GridLayout(1, true);
gridLayout.verticalSpacing = 2;
gridLayout.marginHeight = 2;
gridLayout.marginTop = 2;
gridLayout.marginWidth = 0;
setLayout(gridLayout);
createLabel("Protocol:", this, 1);
protocolCombo = new Combo(this, SWT.NONE | SWT.READ_ONLY);
protocolCombo.add("TCP");
protocolCombo.add("UDP");
protocolCombo.add("ICMP");
protocolCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
protocolCombo.select(0);
createLabel("Port or Port Range:", this, 1);
portText = createTextBox(this, 1);
createLabel("Network Mask:", this, 1);
networkText = createTextBox(this, 1);
networkText.setText("0.0.0.0/0");
pack();
}
}
private Button createRadioButton(String text, Composite parent, int columnSpan) {
Button b = new Button(parent, SWT.RADIO);
b.setText(text);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = columnSpan;
b.setLayoutData(gridData);
b.addSelectionListener(selectionListener);
return b;
}
/*
* Private Methods
*/
private Label createLabel(String text, Composite parent, int columnSpan) {
Label label = new Label(parent, SWT.NONE);
label.setText(text);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_END;
gridData.horizontalSpan = columnSpan;
gridData.verticalIndent = 2;
label.setLayoutData(gridData);
return label;
}
private Text createTextBox(Composite parent, int columnSpan) {
Text text = new Text(parent, SWT.BORDER);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = columnSpan;
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
text.setLayoutData(gridData);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateOkButton();
}
});
text.addSelectionListener(selectionListener);
return text;
}
private SelectionListener selectionListener = new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
updateOkButton();
}
};
private Composite createComposite(Composite parent) {
Composite composite = new Composite(parent, SWT.BORDER);
GridLayout gridLayout = new GridLayout(2, false);
gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
gridLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
gridLayout.marginHeight = 2;
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
private void updateOkButton() {
if (userGroupComposite == null || portRangeComposite == null) return;
boolean b = false;
if (userGroupPermissionButton.getSelection()) {
b = userGroupComposite.isComplete();
} else {
b = portRangeComposite.isComplete();
}
Button okButton = getButton(IDialogConstants.OK_ID);
if (okButton != null) {
okButton.setEnabled(b);
}
}
}
| 7,215 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/elasticip/ElasticIpComposite.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.elasticip;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.services.ec2.model.Address;
import com.amazonaws.services.ec2.model.AllocateAddressRequest;
import com.amazonaws.services.ec2.model.ReleaseAddressRequest;
/**
* Selection table for selecting an Elastic IP.
*/
public class ElasticIpComposite extends SelectionTable {
private Action newAddressAction;
private Action refreshAddressesAction;
private Action releaseAddressAction;
/**
* Creates a new Elastic IP selection table parented by the specified
* composite.
*
* @param parent
* The UI parent of this new selection table.
*/
public ElasticIpComposite(Composite parent) {
super(parent);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
refreshAddressList();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#getSelection()
*/
@Override
public Address getSelection() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
return (Address)selection.getFirstElement();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#addSelectionListener(org.eclipse.swt.events.SelectionListener)
*/
@Override
public void addSelectionListener(SelectionListener listener) {
viewer.getTree().addSelectionListener(listener);
}
public Action getNewAddressAction() {
return newAddressAction;
}
public Action getRefreshAddressesAction() {
return refreshAddressesAction;
}
public Action getReleaseAddressAction() {
return releaseAddressAction;
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
manager.add(refreshAddressesAction);
manager.add(new Separator());
manager.add(newAddressAction);
manager.add(releaseAddressAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
newAddressAction = new Action() {
@Override
public void run() {
new RequestElasticIpThread().start();
}
};
newAddressAction.setText("New Elastic IP");
newAddressAction.setToolTipText("Requests a new Elastic IP address");
newAddressAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("add"));
refreshAddressesAction = new Action() {
@Override
public void run() {
refreshAddressList();
}
};
refreshAddressesAction.setText("Refresh");
refreshAddressesAction.setToolTipText("Refresh the Elastic IP address list");
refreshAddressesAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
releaseAddressAction = new Action() {
@Override
public void run() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
Address addressInfo = (Address) selection.getFirstElement();
new ReleaseElasticIpThread(addressInfo).start();
}
};
releaseAddressAction.setText("Release");
releaseAddressAction.setToolTipText("Release this Elastic IP");
releaseAddressAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Elastic IP", 40);
newColumn("Attached Instance", 60);
}
/*
* Private Interface
*/
private void refreshAddressList() {
new RefreshAddressListThread().start();
}
/*
* Content and Label Providers
*/
private class ViewContentProvider implements ITreeContentProvider {
List<Address> addresses;
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
addresses = (List<Address>)newInput;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object parent) {
if (addresses == null) {
return new Object[0];
}
return addresses.toArray();
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
private class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object obj, int index) {
if (!Address.class.isInstance(obj)) {
return "???";
}
Address addressInfo = (Address)obj;
switch(index) {
case 0:
return addressInfo.getPublicIp();
case 1:
return addressInfo.getInstanceId();
}
return getText(obj);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object obj, int index) {
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
*/
@Override
public Image getImage(Object obj) {
return PlatformUI.getWorkbench().
getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
}
}
/*
* Private Threads for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to list all Elastic IPs for the
* current account.
*/
private class RefreshAddressListThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
final List<Address> addresses = getAwsEc2Client().describeAddresses().getAddresses();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(addresses);
packColumns();
}
});
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to list Elastic IPs: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
/**
* Thread for making an EC2 service call to release an Elastic IP.
*/
private class ReleaseElasticIpThread extends Thread {
/** The Elastic IP to release */
private final Address addressInfo;
/**
* Creates a new thread ready to be started to release the specified
* Elastic IP.
*
* @param addressInfo
* The Elastic IP to release.
*/
public ReleaseElasticIpThread(final Address addressInfo) {
this.addressInfo = addressInfo;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
ReleaseAddressRequest request = new ReleaseAddressRequest();
request.setPublicIp(addressInfo.getPublicIp());
getAwsEc2Client().releaseAddress(request);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to release Elastic IP: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
refreshAddressList();
}
}
/**
* Thread for making an EC2 service call to request a new Elastic IP.
*/
private class RequestElasticIpThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
getAwsEc2Client().allocateAddress(new AllocateAddressRequest());
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to create new Elastic IP: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
refreshAddressList();
}
}
}
| 7,216 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/elasticip/ElasticIpView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.elasticip;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;
/**
* An Eclipse view displaying a table of elastic IPs.
*/
public class ElasticIpView extends ViewPart {
private ElasticIpComposite elasticIPTable;
/**
* This is a callback that will allow us
* to create the viewer and initialize it.
*/
@Override
public void createPartControl(Composite parent) {
elasticIPTable = new ElasticIpComposite(parent);
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalPullDown(bars.getMenuManager());
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalPullDown(IMenuManager manager) {
manager.add(elasticIPTable.getRefreshAddressesAction());
manager.add(new Separator());
manager.add(elasticIPTable.getNewAddressAction());
manager.add(elasticIPTable.getReleaseAddressAction());
}
private void fillLocalToolBar(IToolBarManager manager) {
manager.add(elasticIPTable.getRefreshAddressesAction());
manager.add(elasticIPTable.getNewAddressAction());
manager.add(elasticIPTable.getReleaseAddressAction());
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
elasticIPTable.setFocus();
}
}
| 7,217 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ebs/ElasticBlockStorageView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.ebs;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import com.amazonaws.eclipse.core.AccountAndRegionChangeListener;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.StatusBar;
/**
* View for working with Elastic Block Storage volumes and snapshots.
*/
public class ElasticBlockStorageView extends ViewPart implements IRefreshable {
/** The snapshot selection table */
private SnapshotSelectionTable snapshotSelectionTable;
/** The EBS volume selection table */
private VolumeSelectionTable volumeSelectionTable;
/** The Action object for refreshing this view's data */
private Action refreshAction;
/**
* Listener for AWS account and region preference changes that require this
* view to be refreshed.
*/
AccountAndRegionChangeListener accountAndRegionChangeListener = new AccountAndRegionChangeListener() {
@Override
public void onAccountOrRegionChange() {
ElasticBlockStorageView.this.refreshData();
}
};
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(1, false);
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.verticalSpacing = 2;
parent.setLayout(layout);
StatusBar statusBar = new StatusBar(parent);
statusBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
SashForm sashForm = new SashForm(parent, SWT.VERTICAL);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
volumeSelectionTable = new VolumeSelectionTable(sashForm);
snapshotSelectionTable = new SnapshotSelectionTable(sashForm);
volumeSelectionTable.setSnapshotSelectionTable(snapshotSelectionTable);
volumeSelectionTable.setListener(statusBar);
contributeToActionBars();
}
@Override
public void init(IViewSite aSite, IMemento aMemento) throws PartInitException {
super.init(aSite, aMemento);
AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().addDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().addDefaultRegionChangeListener(accountAndRegionChangeListener);
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
public void dispose() {
AwsToolkitCore.getDefault().getAccountManager().removeAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().removeDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(accountAndRegionChangeListener);
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
@Override
public void setFocus() {
volumeSelectionTable.setFocus();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(IToolBarManager manager) {
refreshAction = new Action() {
@Override
public void run() {
if (volumeSelectionTable != null)
volumeSelectionTable.refreshVolumes();
if (snapshotSelectionTable != null)
snapshotSelectionTable.refreshSnapshots();
}
};
refreshAction.setText("Refresh");
refreshAction.setToolTipText("Refresh EBS volumes and snapshots");
refreshAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
manager.add(refreshAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
if (refreshAction != null)
refreshAction.run();
}
}
| 7,218 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ebs/VolumeSelectionTable.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.ebs;
import java.text.DateFormat;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.TagFormatter;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.ec2.ui.SelectionTableComparator;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateSnapshotRequest;
import com.amazonaws.services.ec2.model.CreateVolumeRequest;
import com.amazonaws.services.ec2.model.DeleteVolumeRequest;
import com.amazonaws.services.ec2.model.DescribeVolumesRequest;
import com.amazonaws.services.ec2.model.DetachVolumeRequest;
import com.amazonaws.services.ec2.model.Volume;
import com.amazonaws.services.ec2.model.VolumeAttachment;
/**
* Selection table subclass for displaying EBS volumes.
*/
public class VolumeSelectionTable extends SelectionTable {
private static final int VOLUME_ID_COLUMN = 0;
private static final int STATUS_COLUMN = 1;
private static final int CREATE_TIME_COLUMN = 2;
private static final int ATTACHED_INSTANCE_COLUMN = 3;
private static final int SIZE_COLUMN = 4;
private static final int ZONE_COLUMN = 5;
private static final int SNAPSHOT_ID_COLUMN = 6;
private static final int TAGS_COLUMN = 7;
/** An Action implementation that releases a volume */
private Action releaseAction;
/** An Action implementation that detaches a volume */
private Action detachAction;
/** An Action implementation that creates a snapshot */
private Action createSnapshotAction;
/** An Action implementation that refreshes the volume list */
private Action refreshAction;
/** An Action implementation that creates a new volume */
private Action createAction;
/**
* An optional reference to a snapshot selection table that should be
* refreshed when new snapshots are created.
*/
private SnapshotSelectionTable snapshotSelectionTable;
/**
* Content provider for the volume selection table.
*/
private static class VolumeContentProvider implements ITreeContentProvider {
List<Volume> volumes;
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
volumes = (List<Volume>)newInput;
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(Object parent) {
if (volumes == null) {
return new Object[0];
}
return volumes.toArray();
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
/**
* Label provider for entries in the volume selection table.
*/
private static class VolumeLabelProvider extends LabelProvider implements ITableLabelProvider {
private final DateFormat dateFormat = DateFormat.getDateTimeInstance();
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object obj, int index) {
Volume volume = (Volume)obj;
if (volume == null) return "";
switch (index) {
case VOLUME_ID_COLUMN:
return volume.getVolumeId();
case STATUS_COLUMN:
return volume.getState();
case CREATE_TIME_COLUMN:
if (volume.getCreateTime() == null) return "";
return dateFormat.format(volume.getCreateTime());
case ATTACHED_INSTANCE_COLUMN:
for (VolumeAttachment attachment : volume.getAttachments()) {
return attachment.getInstanceId();
}
return "";
case SIZE_COLUMN:
return volume.getSize().toString();
case ZONE_COLUMN:
return volume.getAvailabilityZone();
case SNAPSHOT_ID_COLUMN:
return volume.getSnapshotId();
case TAGS_COLUMN:
return TagFormatter.formatTags(volume.getTags());
}
return "???";
}
@Override
public Image getColumnImage(Object obj, int index) {
if (index == 0)
return Ec2Plugin.getDefault().getImageRegistry().get("volume");
return null;
}
@Override
public Image getImage(Object obj) {
return null;
}
}
/**
* Comparator for sorting volumes by creation time.
*/
private static class VolumeComparator extends SelectionTableComparator {
/**
* @param defaultColumn
*/
public VolumeComparator(int defaultColumn) {
super(defaultColumn);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTableComparator#compareIgnoringDirection(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
protected int compareIgnoringDirection(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof Volume && e2 instanceof Volume)) {
return 0;
}
Volume volume1 = (Volume)e1;
Volume volume2 = (Volume)e2;
switch (this.sortColumn) {
case VOLUME_ID_COLUMN:
return volume1.getVolumeId().compareTo(volume2.getVolumeId());
case STATUS_COLUMN:
return volume1.getState().compareTo(volume2.getState());
case CREATE_TIME_COLUMN:
return volume1.getCreateTime().compareTo(volume2.getCreateTime());
case ATTACHED_INSTANCE_COLUMN:
String instanceId1 = "";
String instanceId2 = "";
for (VolumeAttachment att : volume1.getAttachments())
instanceId1 = att.getInstanceId();
for (VolumeAttachment att : volume2.getAttachments())
instanceId2 = att.getInstanceId();
return instanceId1.compareTo(instanceId2);
case SIZE_COLUMN:
return volume1.getSize().compareTo(volume2.getSize());
case ZONE_COLUMN:
return volume1.getAvailabilityZone().compareTo(volume2.getAvailabilityZone());
case SNAPSHOT_ID_COLUMN:
return volume1.getSnapshotId().compareTo(volume2.getSnapshotId());
case TAGS_COLUMN:
return TagFormatter.formatTags(volume1.getTags()).compareTo(TagFormatter.formatTags(volume2.getTags()));
}
return 0;
}
}
/*
* Public Interface
*/
/**
* Instantiates a new volume selection table as a child of the specified
* parent composite.
*
* @param parent
* The parent composite for this new selection table.
*/
public VolumeSelectionTable(Composite parent) {
super(parent);
viewer.setContentProvider(new VolumeContentProvider());
viewer.setLabelProvider(new VolumeLabelProvider());
setComparator(new VolumeComparator(CREATE_TIME_COLUMN));
refreshVolumes();
}
/**
* Refreshes the volumes in this selection table.
*/
public void refreshVolumes() {
if (viewer == null) return;
new RefreshVolumesThread().start();
}
/**
* Sets the optional snapshot selection table that should be refreshed when
* new snapshots are created from volumes.
*
* @param snapshotSelectionComposite
* The snapshot selection table.
*/
public void setSnapshotSelectionTable(SnapshotSelectionTable snapshotSelectionComposite) {
this.snapshotSelectionTable = snapshotSelectionComposite;
}
/**
* Returns the currently selected volume.
*
* @return The currently selected volume.
*/
public Volume getSelectedVolume() {
return (Volume)this.getSelection();
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Volume ID", 10);
newColumn("Status", 10);
newColumn("Create Time", 10);
newColumn("Attached Instance", 10);
newColumn("Size (GB)", 10);
newColumn("Zone", 10);
newColumn("Snapshot ID", 10);
newColumn("Tags", 15);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
Volume selectedVolume = getSelectedVolume();
boolean isVolumeSelected = (selectedVolume != null);
boolean isAvailableVolumeSelected = isVolumeSelected && selectedVolume.getState().equalsIgnoreCase("available");
boolean isAttachedVolumeSelected = isVolumeSelected && !(selectedVolume.getAttachments().isEmpty());
releaseAction.setEnabled(isAvailableVolumeSelected);
detachAction.setEnabled(isAttachedVolumeSelected);
createSnapshotAction.setEnabled(isVolumeSelected);
manager.add(refreshAction);
manager.add(new Separator());
manager.add(createAction);
manager.add(releaseAction);
manager.add(detachAction);
manager.add(new Separator());
manager.add(createSnapshotAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
refreshAction = new Action() {
@Override
public void run() {
refreshVolumes();
}
};
refreshAction.setText("Refresh");
refreshAction.setToolTipText("Refresh the volume list");
refreshAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
createAction = new Action() {
@Override
public void run() {
final CreateNewVolumeDialog dialog = new CreateNewVolumeDialog(Display.getCurrent().getActiveShell());
if (dialog.open() != IDialogConstants.OK_ID) return;
new CreateVolumeThread(dialog.getAvailabilityZone(), dialog.getSize(), dialog.getSnapshotId()).start();
}
};
createAction.setText("New Volume");
createAction.setToolTipText("Create a new EBS volume");
createAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("add"));
releaseAction = new Action() {
@SuppressWarnings("unchecked")
@Override
public void run() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
new ReleaseVolumesThread(selection.toList()).start();
}
};
releaseAction.setText("Release Volume");
releaseAction.setDescription("Release selected volume(s)");
releaseAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
detachAction = new Action() {
@Override
public void run() {
final Volume volume = getSelectedVolume();
new DetachVolumeThread(volume).start();
}
};
detachAction.setText("Detach Volume");
detachAction.setToolTipText("Detach the selected volume from all instances.");
createSnapshotAction = new Action() {
@Override
public void run() {
new CreateSnapshotThread(getSelectedVolume()).start();
}
};
createSnapshotAction.setText("Create Snapshot");
createSnapshotAction.setToolTipText("Creates a new snapshot of this volume.");
createSnapshotAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("snapshot"));
}
/*
* Private Threads for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to refresh the list of EBS volumes.
*/
private class RefreshVolumesThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
if (selectionTableListener != null) selectionTableListener.loadingData();
final AmazonEC2 ec2 = getAwsEc2Client();
final List<Volume> volumes = ec2.describeVolumes(new DescribeVolumesRequest()).getVolumes();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(volumes);
packColumns();
}
});
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to refresh EBS volumes: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
} finally {
if (selectionTableListener != null) selectionTableListener.finishedLoadingData(-1);
}
}
}
/**
* Thread for making an EC2 service call to detach an EBS volume.
*/
private class DetachVolumeThread extends Thread {
/** The volume to detach */
private final Volume volume;
/**
* Creates a new thread ready to be started to detach the specified
* volume.
*
* @param volume
* The EBS volume to detach.
*/
public DetachVolumeThread(final Volume volume) {
this.volume = volume;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
for (VolumeAttachment attachmentInfo : volume.getAttachments()) {
String volumeId = attachmentInfo.getVolumeId();
String instanceId = attachmentInfo.getInstanceId();
String device = attachmentInfo.getDevice();
try {
DetachVolumeRequest request = new DetachVolumeRequest();
request.setVolumeId(volumeId);
request.setInstanceId(instanceId);
request.setDevice(device);
request.setForce(false);
getAwsEc2Client().detachVolume(request);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to detach EBS volume: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
refreshVolumes();
}
}
/**
* Thread for making an EC2 service call to create a new EBS volume.
*/
private class CreateVolumeThread extends Thread {
/** The zone to create the volume in */
private final String zoneName;
/** The snapshot to create the volume from (optional) */
private final String snapshotId;
/** The size of the new volume */
private final int size;
/**
* Creates a new thread ready to be started to create a new EBS volume.
*
* @param zoneName
* The availability zone to create the new volume in.
* @param size
* The size of the new volume.
* @param snapshotId
* An optional snapshot id to create the volume from.
*/
public CreateVolumeThread(String zoneName, int size, String snapshotId) {
this.zoneName = zoneName;
this.size = size;
this.snapshotId = snapshotId;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
CreateVolumeRequest request = new CreateVolumeRequest();
// Only set size if we're not using a snapshot
if (snapshotId == null) request.setSize(size);
request.setSnapshotId(snapshotId);
request.setAvailabilityZone(zoneName);
getAwsEc2Client().createVolume(request);
refreshVolumes();
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to create EBS volume: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
/**
* Thread for making an EC2 service call to release EBS volumes.
*/
private class ReleaseVolumesThread extends Thread {
/** The volumes to release */
private final List<Volume> volumes;
/**
* Creates a new thread ready to be started and release the specified
* volumes.
*
* @param volumes
* The EBS volumes to release.
*/
public ReleaseVolumesThread(final List<Volume> volumes) {
this.volumes = volumes;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = getAwsEc2Client();
for (Volume volume : volumes) {
DeleteVolumeRequest request = new DeleteVolumeRequest();
request.setVolumeId(volume.getVolumeId());
ec2.deleteVolume(request);
}
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to release EBS volume: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
refreshVolumes();
}
}
/**
* Thread to make an EC2 service call to create a new snapshot from an EBS
* volume.
*/
private class CreateSnapshotThread extends Thread {
/** The volume to create a snapshot from */
private final Volume volume;
/**
* Creates a new thread ready to be started to create a snapshot of the
* specified volume.
*
* @param volume
* The volume to create a snapshot of.
*/
public CreateSnapshotThread(final Volume volume) {
this.volume = volume;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
CreateSnapshotRequest request = new CreateSnapshotRequest();
request.setVolumeId(volume.getVolumeId());
getAwsEc2Client().createSnapshot(request);
if (snapshotSelectionTable != null) {
snapshotSelectionTable.refreshSnapshots();
}
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to create snapshot: " + e.getMessage(), e);
StatusManager.getManager().handle(status,
StatusManager.SHOW | StatusManager.LOG);
}
}
}
}
| 7,219 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ebs/SnapshotSelectionTable.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.ebs;
import java.text.DateFormat;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.TagFormatter;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.ec2.ui.SelectionTableComparator;
import com.amazonaws.eclipse.ec2.ui.views.instances.RefreshTimer;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.DeleteSnapshotRequest;
import com.amazonaws.services.ec2.model.Snapshot;
/**
* SelectionTable subclass for selecting EBS snapshots.
*/
public class SnapshotSelectionTable extends SelectionTable implements IRefreshable {
/** The period between refreshes when snapshots are in progress */
private static final int REFRESH_PERIOD_IN_MILLISECONDS = 10 * 1000;
private static final int STATE_COLUMN = 0;
private static final int SNAPSHOT_ID_COLUMN = 1;
private static final int VOLUME_ID_COLUMN = 2;
private static final int START_TIME_COLUMN = 3;
private static final int TAGS_COLUMN = 4;
/** An Action implementation that refreshes the snapshots */
private Action refreshAction;
/** An Action implementation that deletes the selected snapshot */
private Action deleteAction;
/**
* The timer we turn on when snapshots are in progress to refresh
* the snapshot data.
*/
private RefreshTimer refreshTimer;
/**
* Comparator for sorting snapshots by creation time.
*/
class SnapshotComparator extends SelectionTableComparator {
public SnapshotComparator(int defaultColumn) {
super(defaultColumn);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTableComparator#compareIgnoringDirection(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
protected int compareIgnoringDirection(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof Snapshot && e2 instanceof Snapshot)) {
return 0;
}
Snapshot snapshot1 = (Snapshot)e1;
Snapshot snapshot2 = (Snapshot)e2;
switch (this.sortColumn) {
case STATE_COLUMN:
return snapshot1.getState().compareTo(snapshot2.getState());
case SNAPSHOT_ID_COLUMN:
return snapshot1.getSnapshotId().compareTo(snapshot2.getSnapshotId());
case VOLUME_ID_COLUMN:
return snapshot1.getVolumeId().compareTo(snapshot2.getVolumeId());
case START_TIME_COLUMN:
return snapshot1.getStartTime().compareTo(snapshot2.getStartTime());
case TAGS_COLUMN:
return TagFormatter.formatTags(snapshot1.getTags()).compareTo(
TagFormatter.formatTags(snapshot2.getTags()));
}
return 0;
}
}
/**
* Label and content provider for snapshot selection table.
*/
private static class SnapshotTableProvider extends LabelProvider
implements ITreeContentProvider, ITableLabelProvider {
private final DateFormat dateFormat = DateFormat.getDateTimeInstance();
List<Object> snapshots;
/*
* IStructuredContentProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
if (snapshots == null) return null;
return snapshots.toArray();
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof List) {
snapshots = (List<Object>)newInput;
}
}
/*
* ITableLabelProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex == 0)
return Ec2Plugin.getDefault().getImageRegistry().get("snapshot");
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object element, int columnIndex) {
if (!(element instanceof Snapshot)) {
return "???";
}
Snapshot snapshot = (Snapshot)element;
switch (columnIndex) {
case STATE_COLUMN:
if (snapshot.getState().equalsIgnoreCase("pending")) {
if (snapshot.getProgress() != null && snapshot.getProgress().length() > 0) {
return "pending (" + snapshot.getProgress() + ")";
} else {
return "pending";
}
}
return snapshot.getState();
case SNAPSHOT_ID_COLUMN:
return snapshot.getSnapshotId();
case VOLUME_ID_COLUMN:
return snapshot.getVolumeId();
case START_TIME_COLUMN:
if (snapshot.getStartTime() == null) return "";
return dateFormat.format(snapshot.getStartTime());
case TAGS_COLUMN:
return TagFormatter.formatTags(snapshot.getTags());
}
return "???";
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
/**
* Creates a new snapshot selection table with the specified parent.
*
* @param parent
* The parent ui component for the new snapshot selection table.
*/
public SnapshotSelectionTable(Composite parent) {
super(parent);
SnapshotTableProvider snapshotTableProvider = new SnapshotTableProvider();
viewer.setContentProvider(snapshotTableProvider);
viewer.setLabelProvider(snapshotTableProvider);
setComparator(new SnapshotComparator(START_TIME_COLUMN));
refreshSnapshots();
refreshTimer = new RefreshTimer(this, REFRESH_PERIOD_IN_MILLISECONDS);
}
/**
* Returns the currently selected snapshot.
*
* @return The currently selected snapshot.
*/
public Snapshot getSelectedSnapshot() {
return (Snapshot)getSelection();
}
/**
* Refreshes the list of snapshots displayed by this snapshot selection
* table.
*/
public void refreshSnapshots() {
new RefreshSnapshotsThread().start();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
this.refreshSnapshots();
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("State", 10);
newColumn("Snapshot ID", 10);
newColumn("Volume ID", 10);
newColumn("Creation Time", 60);
newColumn("Tags", 15);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
Snapshot selectedSnapshot = getSelectedSnapshot();
boolean isSnapshotSelected = (selectedSnapshot != null);
deleteAction.setEnabled(isSnapshotSelected);
manager.add(refreshAction);
manager.add(new Separator());
manager.add(deleteAction);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
refreshAction = new Action() {
@Override
public void run() {
refreshSnapshots();
}
};
refreshAction.setText("Refresh");
refreshAction.setToolTipText("Refresh the list of snapshots.");
refreshAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
deleteAction = new Action () {
@Override
public void run() {
Snapshot selectedSnapshot = getSelectedSnapshot();
new DeleteSnapshotThread(selectedSnapshot).start();
}
};
deleteAction.setText("Delete Snapshot");
deleteAction.setToolTipText("Delete the selected snapshot.");
deleteAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
}
/*
* Private Interface
*/
/**
* Sets the input of this control to the specified list of snapshots and
* also takes care of any special requirements of in progress snapshots such
* as turning on the refresh timer and displaying progress bars for the
* snapshot progress.
*
* @param snapshots
* The list of snapshots that should be displayed in this
* selection table.
*/
private void setInput(final List<Snapshot> snapshots) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Snapshot previouslySelectedSnapshot = getSelectedSnapshot();
viewer.setInput(snapshots);
packColumns();
if (previouslySelectedSnapshot != null) {
Tree table = viewer.getTree();
for (int i = 0; i < table.getItemCount(); i++) {
Snapshot snapshot = (Snapshot)table.getItem(i).getData();
if (snapshot.getSnapshotId().equals(previouslySelectedSnapshot.getSnapshotId())) {
table.select(table.getItem(i));
}
}
}
resetRefreshTimer(snapshots);
}
});
}
/**
* Turns on or off the refresh timer depending on whether or not any of the
* specified snapshots are currently in progress. If snapshots are in
* progress, the refresh timer is turned on so that the user watch as the
* snapshot progresses, otherwise the refresh timer is turned off.
*
* @param snapshots
* The snapshots being displayed by this control.
*/
private void resetRefreshTimer(List<Snapshot> snapshots) {
for (Snapshot snapshot : snapshots) {
if (snapshot.getState().equalsIgnoreCase("pending")) {
refreshTimer.startTimer();
return;
}
}
refreshTimer.stopTimer();
}
/*
* Private Threads for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to refresh the list of EBS
* snapshots for the current account.
*/
private class RefreshSnapshotsThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = getAwsEc2Client();
final List<Snapshot> snapshots = ec2.describeSnapshots().getSnapshots();
setInput(snapshots);
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to refresh snapshots: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
/**
* Thread for making an EC2 service call to delete a snapshot.
*/
private class DeleteSnapshotThread extends Thread {
/** The snapshot to delete */
private final Snapshot snapshot;
/**
* Creates a new thread ready to be started to delete the specified
* snapshot.
*
* @param snapshot
* The snapshot to delete.
*/
public DeleteSnapshotThread(Snapshot snapshot) {
this.snapshot = snapshot;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
getAwsEc2Client().deleteSnapshot(new DeleteSnapshotRequest()
.withSnapshotId(snapshot.getSnapshotId()));
refreshSnapshots();
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to delete snapshot: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
}
| 7,220 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/ebs/CreateNewVolumeDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.ebs;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Snapshot;
/**
* A dialog that allows a user to enter information for creating a new EBS
* volume.
*/
public class CreateNewVolumeDialog extends Dialog {
/** Shared client factory */
private AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/** Spinner control for specifying how large of a volume to create */
private Spinner sizeSpinner;
/** Combo box to select what availability zone to create a volume in */
private Combo availabilityZoneCombo;
/** The volume size */
private int size;
/** The availability zone to create a volume in */
private String availabilityZone;
/** The radio button for creating a volume by size */
private Button emptyVolumeRadioButton;
/** The radio button for creating a volume from a snapshot */
private Button useSnapshotRadioButton;
/** The snapshot selection table */
private SnapshotSelectionTable snapshotSelectionComposite;
/** The id of the selected snapshot */
private String snapshotId;
/**
* The device the new volume should be attached to. This is only
* set if the the new volume being created is explicitly being created
* to be attached to a specific instance.
*/
private String device;
/**
* The instance to which this new volume is being attached. This is only
* present if the new volume being created is explicitly being created to be
* attached to an instance, and isn't set during the normal
* "Create New Volume" workflow.
*/
private Instance instance = null;
private Combo deviceCombo;
/**
* Creates a new dialog ready to be opened to collect information from the
* user on how to create a new EBS volume.
*
* @param parentShell
* The parent shell for this new dialog window.
*/
public CreateNewVolumeDialog(Shell parentShell) {
super(parentShell);
}
/**
* Creates a new dialog ready to be opened to collect information from the
* user on how to create a new EBS volume which will be attached to the
* specified instance. When creating a new volume explicitly for attaching
* it to a specific instance, certain parts of the dialog are different,
* such as the availability zone being locked down to the zone the specified
* instance is in, and a new Combo box is present that allows the user to
* select what device the new EBS volume should be attached as.
*
* @param parentShell
* The parent shell for this new dialog window.
* @param instance
* The instance that the new EBS volume will be attached to.
*/
public CreateNewVolumeDialog(Shell parentShell, Instance instance) {
this(parentShell);
this.instance = instance;
}
/**
* Returns the selected volume size. This method can only be called after
* the dialog's Ok button has been pressed.
*
* @return The selected volume size.
*/
public int getSize() {
return size;
}
/**
* Returns the selected availability zone. This method can only be called
* after the dialog's Ok button has been pressed.
*
* @return The selected availability zone.
*/
public String getAvailabilityZone() {
return availabilityZone;
}
/**
* Returns the selected device that this new volume should be attached to.
*
* @return The selected device that this new volume should be attached to.
*/
public String getDevice() {
return device;
}
/**
* Returns the selected snapshot id. This method can only be called after
* the dialog's Ok button has been pressed.
*
* @return The selected snapshot id.
*/
public String getSnapshotId() {
return snapshotId;
}
/*
* Dialog Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
GridData gridData;
SelectionListener selectionListener = new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
updateControls();
}
};
/*
* If we aren't creating this new volume explicitly to attach it to
* a specific instance, then we can let the user select an availability
* zone, otherwise we need to lock it down to the availability zone of the
* instance that will be attaching this new volume.
*/
newLabel("Availability Zone:", composite);
if (instance == null) {
availabilityZoneCombo = new Combo(composite, SWT.READ_ONLY);
availabilityZoneCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
populateAvailabilityZoneCombo();
} else {
newLabel(instance.getPlacement().getAvailabilityZone(), composite);
}
/*
* If we are creating this new volume explicitly for attaching it to a
* specified instance, then we also need to let the user select the
* device they want the volume attached as.
*/
if (instance != null) {
newLabel("Device:", composite);
deviceCombo = new Combo(composite, SWT.READ_ONLY);
deviceCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String devicePrefix = "/dev/sd";
for (char c = 'b'; c <= 'z'; c++) {
deviceCombo.add(devicePrefix + c);
}
deviceCombo.setText("/dev/sdh");
}
emptyVolumeRadioButton = new Button(composite, SWT.RADIO);
emptyVolumeRadioButton.setText("Create empty volume by size (GB):");
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 1;
emptyVolumeRadioButton.setLayoutData(gridData);
emptyVolumeRadioButton.addSelectionListener(selectionListener);
sizeSpinner = new Spinner(composite, SWT.NONE);
sizeSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
sizeSpinner.setMinimum(1);
sizeSpinner.setMaximum(1024);
sizeSpinner.setEnabled(false);
useSnapshotRadioButton = new Button(composite, SWT.RADIO);
useSnapshotRadioButton.setText("Or create volume from existing snapshot:");
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
useSnapshotRadioButton.setLayoutData(gridData);
useSnapshotRadioButton.addSelectionListener(selectionListener);
snapshotSelectionComposite = new SnapshotSelectionTable(composite);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.horizontalSpan = 2;
gridData.horizontalIndent = 15;
gridData.heightHint = 150;
snapshotSelectionComposite.setLayoutData(gridData);
snapshotSelectionComposite.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
updateControls();
}
});
return composite;
}
/**
* Populates the availability zone combo box with the available zones.
*/
private void populateAvailabilityZoneCombo() {
if (availabilityZoneCombo == null) return;
try {
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
for (AvailabilityZone zone : ec2.describeAvailabilityZones().getAvailabilityZones()) {
availabilityZoneCombo.add(zone.getZoneName());
}
availabilityZoneCombo.select(0);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to list availability zones");
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#create()
*/
@Override
public void create() {
super.create();
String title = null;
if (instance == null) {
title = "Create New EBS Volume";
} else {
title = "Attach New EBS Volume";
}
getShell().setText(title);
emptyVolumeRadioButton.setSelection(true);
updateControls();
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
size = sizeSpinner.getSelection();
if (availabilityZoneCombo != null) {
availabilityZone = availabilityZoneCombo.getText();
}
if (deviceCombo != null) {
device = deviceCombo.getText();
}
Snapshot selectedSnapshot = snapshotSelectionComposite.getSelectedSnapshot();
if (selectedSnapshot != null) {
snapshotId = selectedSnapshot.getSnapshotId();
}
super.okPressed();
}
/*
* Private Interface
*/
private void updateControls() {
boolean creatingFromSnapshot = useSnapshotRadioButton.getSelection();
Button okButton = getButton(IDialogConstants.OK_ID);
snapshotSelectionComposite.setEnabled(creatingFromSnapshot);
sizeSpinner.setEnabled(!creatingFromSnapshot);
if (creatingFromSnapshot) {
if (okButton != null) {
Snapshot snapshot = snapshotSelectionComposite.getSelectedSnapshot();
okButton.setEnabled(snapshot != null);
}
} else {
snapshotSelectionComposite.clearSelection();
if (okButton != null) okButton.setEnabled(true);
}
}
private Label newLabel(String text, Composite parent) {
Label l = new Label(parent, SWT.NONE);
l.setText(text);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_BEGINNING;
l.setLayoutData(gridData);
return l;
}
}
| 7,221 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/keypair/KeyPairRefreshListener.java | /*
* Copyright 2010-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.keypair;
/**
* Simple interface to notify interested parties that the set of keys
* displayed in a {@link KeyPairSelectionTable} has changed.
*/
public interface KeyPairRefreshListener {
/**
* Notification that the set of key pairs displayed by a
* {@link KeyPairSelectionTable} has been refreshed.
*/
public void keyPairsRefreshed();
}
| 7,222 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/keypair/KeyPairView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.keypair;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;
/**
* An Eclipse view listing all available EC2 Key Pairs.
*/
public class KeyPairView extends ViewPart {
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new GridLayout(1, true));
KeyPairComposite keyPairComposite = new KeyPairComposite(parent);
keyPairComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
contributeToActionBars();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
fillLocalToolBar(bars.getToolBarManager());
}
private void fillLocalToolBar(IToolBarManager manager) {
// TODO:
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
// TODO:
}
}
| 7,223 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/keypair/KeyPairComposite.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.keypair;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ToolBar;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
/**
* Small wrapper around a {@link KeyPairSelectionTable} that adds a toolbar.
*/
public class KeyPairComposite extends Composite {
private KeyPairSelectionTable keyPairSelectionTable;
private ToolBar toolBar;
private ToolBarManager toolBarManager;
private final String accountId;
/**
* Constructs a key pair composite that uses the current AWS account.
*/
public KeyPairComposite(Composite parent) {
this(parent, AwsToolkitCore.getDefault().getCurrentAccountId(), null);
}
/**
* Constructs a key pair composite that uses the account id given.
*/
public KeyPairComposite(Composite parent, String accountId) {
this(parent, accountId, null);
}
/**
* Constructs a key pair composite that uses the both account id and endpoint given.
*/
public KeyPairComposite(Composite parent, String accountId, Region ec2RegionOverride) {
super(parent, SWT.NONE);
this.accountId = accountId;
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 2;
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.marginTop = 1;
setLayout(layout);
toolBarManager = new ToolBarManager();
toolBar = toolBarManager.createControl(this);
toolBar.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
keyPairSelectionTable = new KeyPairSelectionTable(this, this.accountId, ec2RegionOverride);
keyPairSelectionTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
toolBarManager.add(keyPairSelectionTable.refreshAction);
toolBarManager.add(new Separator());
toolBarManager.add(keyPairSelectionTable.createNewKeyPairAction);
toolBarManager.add(keyPairSelectionTable.deleteKeyPairAction);
toolBarManager.add(new Separator());
toolBarManager.add(keyPairSelectionTable.registerKeyPairAction);
toolBarManager.update(true);
}
public void setEc2EndpointOverride(Region region) {
keyPairSelectionTable.setEc2RegionOverride(region);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
keyPairSelectionTable.getViewer().getControl().setEnabled(enabled);
if (enabled) {
keyPairSelectionTable.updateActionsForSelection();
} else {
keyPairSelectionTable.refreshAction.setEnabled(enabled);
keyPairSelectionTable.createNewKeyPairAction.setEnabled(enabled);
keyPairSelectionTable.deleteKeyPairAction.setEnabled(enabled);
keyPairSelectionTable.registerKeyPairAction.setEnabled(enabled);
}
}
public TreeViewer getViewer() {
return keyPairSelectionTable.getViewer();
}
public KeyPairSelectionTable getKeyPairSelectionTable() {
return keyPairSelectionTable;
}
}
| 7,224 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/keypair/CreateKeyPairDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.keypair;
import java.io.File;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
/**
* A dialog for creating a new EC2 Key Pair.
*/
class CreateKeyPairDialog extends Dialog {
private Text keyPairNameText;
private Text privateKeyDirectoryText;
private String keyPairName;
private String privateKeyDirectoryName;
private final String accountId;
protected CreateKeyPairDialog(Shell parentShell, String accountId) {
super(parentShell);
this.accountId = accountId;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#create()
*/
@Override
public void create() {
super.create();
this.getShell().setText("Create New Key Pair");
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createButtonBar(Composite parent) {
Control control = super.createButtonBar(parent);
updateOkButton();
return control;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
ModifyListener listener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateOkButton();
}
};
Composite composite = new Composite(parent, SWT.BORDER);
GridLayout gridLayout = new GridLayout(3, false);
gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
gridLayout.verticalSpacing = 0;
gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridData gridData;
Label label = new Label(composite, SWT.NONE);
label.setText("Key Pair Name:");
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalAlignment = SWT.LEFT;
gridData.verticalAlignment = SWT.CENTER;
gridData.horizontalSpan = 3;
label.setLayoutData(gridData);
keyPairNameText = new Text(composite, SWT.BORDER);
keyPairNameText.addModifyListener(listener);
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 3;
keyPairNameText.setLayoutData(gridData);
label = new Label(composite, SWT.NONE);
label.setText("Private Key Directory:");
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalAlignment = SWT.LEFT;
gridData.verticalAlignment = SWT.CENTER;
gridData.horizontalSpan = 3;
label.setLayoutData(gridData);
privateKeyDirectoryText = new Text(composite, SWT.BORDER);
privateKeyDirectoryText.addModifyListener(listener);
File defaultPrivateKeyDirectory = KeyPairManager.getDefaultPrivateKeyDirectory();
if (defaultPrivateKeyDirectory != null) {
privateKeyDirectoryText.setText(defaultPrivateKeyDirectory.getAbsolutePath());
}
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 2;
gridData.widthHint = 300;
privateKeyDirectoryText.setLayoutData(gridData);
Button button = new Button(composite, SWT.PUSH);
button.setText("Browse...");
button.addSelectionListener(new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
DirectoryDialog dialog = new DirectoryDialog(Display.getCurrent().getActiveShell());
String directoryPath = dialog.open();
privateKeyDirectoryText.setText(directoryPath);
}
});
applyDialogFont(composite);
return composite;
}
private void updateOkButton() {
boolean b = true;
if (keyPairNameText == null || keyPairNameText.getText().length() == 0 || privateKeyDirectoryText == null || privateKeyDirectoryText.getText().length() == 0) {
b = false;
}
Button okButton = getButton(OK);
if (okButton == null) {
return;
}
okButton.setEnabled(b);
}
public String getKeyPairName() {
return keyPairName;
}
public String getPrivateKeyDirectory() {
return privateKeyDirectoryName;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
privateKeyDirectoryName = privateKeyDirectoryText.getText();
keyPairName = keyPairNameText.getText();
super.okPressed();
}
}
| 7,225 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/keypair/KeyPairSelectionTable.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.keypair;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.DeleteKeyPairRequest;
import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
import com.amazonaws.services.ec2.model.KeyPairInfo;
/**
* Table for selecting key pairs.
*/
public class KeyPairSelectionTable extends SelectionTable {
private final Collection<KeyPairRefreshListener> listeners = new LinkedList<>();
@Override
public TreeViewer getViewer() {
return (TreeViewer) super.getViewer();
}
public Action deleteKeyPairAction;
public Action createNewKeyPairAction;
public Action refreshAction;
public Action registerKeyPairAction;
private final String accountId;
private static final KeyPairManager keyPairManager = new KeyPairManager();
private final Image errorImage = Ec2Plugin.getDefault().getImageRegistry().getDescriptor("error").createImage();
private final Image checkImage = Ec2Plugin.getDefault().getImageRegistry().getDescriptor("check").createImage();
public static final String INVALID_KEYPAIR_MESSAGE =
"The selected key pair is missing its private key. " +
"You can associate the private key file with this key pair if you have it, " +
"or you can create a new key pair. ";
/**
* Refreshes the EC2 key pairs displayed.
*/
public void refreshKeyPairs() {
new RefreshKeyPairsThread().start();
}
public synchronized void addRefreshListener(KeyPairRefreshListener listener) {
listeners.add(listener);
}
public synchronized void removeRefreshListener(KeyPairSelectionTable listener) {
listeners.remove(listener);
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
errorImage.dispose();
checkImage.dispose();
super.dispose();
}
public void updateActionsForSelection() {
KeyPairInfo selectedKeyPair = getSelectedKeyPair();
refreshAction.setEnabled(true);
createNewKeyPairAction.setEnabled(true);
deleteKeyPairAction.setEnabled(selectedKeyPair != null);
// We only enable the register key pair action if the selected
// key pair doesn't have a private key file registered yet
registerKeyPairAction.setEnabled(false);
if (selectedKeyPair != null) {
String privateKeyFile = keyPairManager.lookupKeyPairPrivateKeyFile(accountId, selectedKeyPair.getKeyName());
registerKeyPairAction.setEnabled(privateKeyFile == null);
}
}
/**
* Label and content provider for the key pair table.
*/
class KeyPairTableProvider extends LabelProvider implements ITreeContentProvider, ITableLabelProvider {
List<KeyPairInfo> keyPairs;
/*
* IStructuredContentProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object inputElement) {
if (keyPairs == null) return null;
return keyPairs.toArray();
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
keyPairs = (List<KeyPairInfo>)newInput;
}
/*
* ITableLabelProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object element, int columnIndex) {
if (columnIndex != 0) return null;
if (!(element instanceof KeyPairInfo)) return null;
KeyPairInfo keyPairInfo = (KeyPairInfo)element;
if (keyPairManager.isKeyPairValid(accountId, keyPairInfo.getKeyName())) {
return checkImage;
} else {
return errorImage;
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object element, int columnIndex) {
if (!(element instanceof KeyPairInfo)) {
return "???";
}
KeyPairInfo keyPairInfo = (KeyPairInfo)element;
switch (columnIndex) {
case 0:
return keyPairInfo.getKeyName();
}
return "?";
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
}
/**
* Simple comparator to sort key pairs by name.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
class KeyPairComparator extends ViewerComparator {
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof KeyPairInfo && e2 instanceof KeyPairInfo)) {
return 0;
}
KeyPairInfo keyPair1 = (KeyPairInfo)e1;
KeyPairInfo keyPair2 = (KeyPairInfo)e2;
return keyPair1.getKeyName().compareTo(keyPair2.getKeyName());
}
}
/**
* Create a key pair table for the specified account Id.
*/
public KeyPairSelectionTable(Composite parent, String accountId) {
this(parent, accountId, null);
}
/**
* Create a key pair table for the specified account Id and ec2 endpoint.
*/
public KeyPairSelectionTable(Composite parent, String accountId, Region ec2RegionOverride) {
super(parent);
this.accountId = accountId;
KeyPairTableProvider keyPairTableProvider = new KeyPairTableProvider();
viewer.setContentProvider(keyPairTableProvider);
viewer.setLabelProvider(keyPairTableProvider);
viewer.setComparator(new KeyPairComparator());
refreshKeyPairs();
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
updateActionsForSelection();
}
});
this.ec2RegionOverride = ec2RegionOverride;
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Name", 100);
}
/**
* Sets the list of key pairs that are displayed in the key pair table.
*
* @param keyPairs
* The list of key pairs to display in the key pair table.
*/
private void setInput(final List<KeyPairInfo> keyPairs) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
final KeyPairInfo previouslySelectedKeyPair = (KeyPairInfo)getSelection();
viewer.setInput(keyPairs);
if (previouslySelectedKeyPair != null) {
for (int i = 0; i < viewer.getTree().getItemCount(); i++) {
KeyPairInfo keyPair = (KeyPairInfo) viewer.getTree().getItem(i).getData();
if (keyPair.getKeyName().equals(previouslySelectedKeyPair.getKeyName())) {
viewer.getTree().select(viewer.getTree().getItem(i));
// Selection listeners aren't notified when we
// select like this, so fire an event.
viewer.getTree().notifyListeners(SWT.Selection, null);
break;
}
}
}
}
});
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
manager.add(refreshAction);
manager.add(new Separator());
manager.add(createNewKeyPairAction);
manager.add(deleteKeyPairAction);
manager.add(registerKeyPairAction);
updateActionsForSelection();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
refreshAction = new Action() {
@Override
public void run() {
refreshKeyPairs();
}
};
refreshAction.setText("Refresh");
refreshAction.setToolTipText("Refresh the list of key pairs.");
refreshAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
createNewKeyPairAction = new Action() {
@Override
public void run() {
CreateKeyPairDialog dialog = new CreateKeyPairDialog(Display.getCurrent().getActiveShell(), accountId);
if (dialog.open() != Dialog.OK) return;
new CreateKeyPairThread(dialog.getKeyPairName(), dialog.getPrivateKeyDirectory()).start();
}
};
createNewKeyPairAction.setText("New Key Pair...");
createNewKeyPairAction.setToolTipText("Create a new key pair.");
createNewKeyPairAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("add"));
deleteKeyPairAction = new Action() {
@Override
public void run() {
KeyPairInfo keyPair = (KeyPairInfo)getSelection();
new DeleteKeyPairThread(keyPair).start();
}
};
deleteKeyPairAction.setText("Delete Key Pair");
deleteKeyPairAction.setToolTipText("Delete the selected key pair.");
deleteKeyPairAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
deleteKeyPairAction.setEnabled(false);
registerKeyPairAction = new Action() {
@Override
public void run() {
KeyPairInfo keyPair = (KeyPairInfo)getSelection();
FileDialog fileDialog = new FileDialog(getShell(), SWT.OPEN);
fileDialog.setText("Select the existing private key file for " + keyPair.getKeyName());
fileDialog.setFilterExtensions(new String[] { "*.pem", "*.*" });
String privateKeyFile = fileDialog.open();
if (privateKeyFile != null) {
try {
keyPairManager.registerKeyPair(accountId, keyPair.getKeyName(), privateKeyFile);
refreshKeyPairs();
} catch (IOException e) {
String errorMessage = "Unable to register key pair " +
"(" + keyPair.getKeyName() + " => " + privateKeyFile + "): " + e.getMessage();
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID, errorMessage, e);
StatusManager.getManager().handle(status, StatusManager.LOG | StatusManager.SHOW);
}
}
}
};
registerKeyPairAction.setText("Select Private Key File...");
registerKeyPairAction.setToolTipText("Register an existing private key with this key pair.");
registerKeyPairAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("configure"));
registerKeyPairAction.setEnabled(false);
}
/**
* Returns the user selected key pair.
*
* @return The user selected key pair.
*/
public KeyPairInfo getSelectedKeyPair() {
return (KeyPairInfo)getSelection();
}
/**
* Returns true if, and only if, a valid key pair is selected, which
* includes checking that a private key is registered for that key pair.
*
* @return True if and only if a valid key pair is selected, which includes
* checking that a private key is registered for that key pair.
*/
public boolean isValidKeyPairSelected() {
KeyPairInfo selectedKeyPair = getSelectedKeyPair();
if (selectedKeyPair == null) return false;
return keyPairManager.isKeyPairValid(accountId, selectedKeyPair.getKeyName());
}
/*
* Private Thread subclasses for making EC2 service calls
*/
/**
* Thread for making an EC2 service call to list all key pairs.
*/
private class RefreshKeyPairsThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = getAwsEc2Client(KeyPairSelectionTable.this.accountId);
DescribeKeyPairsResult response = ec2.describeKeyPairs(new DescribeKeyPairsRequest());
List<KeyPairInfo> keyPairs = response.getKeyPairs();
setInput(keyPairs);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
for ( KeyPairRefreshListener listener : listeners ) {
listener.keyPairsRefreshed();
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to list key pairs: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
/**
* Thread for making an EC2 service call to delete a key pair.
*/
private class DeleteKeyPairThread extends Thread {
/** The key pair to delete */
private final KeyPairInfo keyPair;
/**
* Creates a new thread ready to be started to delete the specified key
* pair.
*
* @param keyPair
* The key pair to delete.
*/
public DeleteKeyPairThread(final KeyPairInfo keyPair) {
this.keyPair = keyPair;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
DeleteKeyPairRequest request = new DeleteKeyPairRequest();
request.setKeyName(keyPair.getKeyName());
getAwsEc2Client(accountId).deleteKeyPair(request);
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to delete key pair: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
refreshKeyPairs();
}
}
/**
* Thread for making an EC2 service call to create a new key pair.
*/
private class CreateKeyPairThread extends Thread {
/** The name for the new key pair */
private final String name;
/** The directory to store the private key in */
private final String directory;
/**
* Creates a new thread ready to be started to create a new key pair
* with the specified name.
*
* @param name
* The name being requested for the new key pair.
* @param directory
* The directory to save the private key file in.
*/
public CreateKeyPairThread(String name, String directory) {
this.directory = directory;
this.name = name;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
keyPairManager.createNewKeyPair(accountId, name, directory, ec2RegionOverride);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to create key pair: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
refreshKeyPairs();
}
}
@Override
public void setEc2RegionOverride(Region region) {
super.setEc2RegionOverride(region);
refreshKeyPairs();
}
}
| 7,226 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/menu/OpenLaunchWizardHandler.java | /*
* Copyright 2010-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.menu;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.ec2.ui.launchwizard.LaunchWizard;
public class OpenLaunchWizardHandler extends AbstractHandler {
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new LaunchWizard("Menu"));
return dialog.open();
}
}
| 7,227 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/amis/AmiSelectionTable.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.amis;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.ILazyTreeContentProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.TagFormatter;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.ec2.ui.launchwizard.LaunchWizard;
import com.amazonaws.eclipse.ec2.utils.IMenu;
import com.amazonaws.eclipse.ec2.utils.MenuAction;
import com.amazonaws.eclipse.ec2.utils.MenuHandler;
import com.amazonaws.services.ec2.model.DeregisterImageRequest;
import com.amazonaws.services.ec2.model.DescribeImagesRequest;
import com.amazonaws.services.ec2.model.Filter;
import com.amazonaws.services.ec2.model.Image;
/**
* Selection table for AMIs.
*/
public class AmiSelectionTable extends SelectionTable implements IMenu {
/** Dropdown filter menu for AMIs */
private IAction amiFilterDropDownAction;
/** DropDown menu handler for AMI Filter Items*/
private MenuHandler amiDropDownMenuHandler;
/** Dropdown filter menu for Platforms */
private IAction platformFilterDropDownAction;
/** DropDown menu handler for Platform Filter Items*/
private MenuHandler platformDropDownMenuHandler;
/** Holds the number of AMIs currently display */
private int noOfAMIs;
/** An action object to launch instances of the selected AMI */
private Action launchAction;
/** An action object to refresh the AMI list */
private Action refreshAction;
/** An action object to delete a selected AMI */
private Action deleteAmiAction;
/** The user's account info */
private static AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
/** The content provider for the data displayed in this selection table */
private ViewContentProvider contentProvider = new ViewContentProvider();
private LoadImageDescriptionsThread loadImageThread;
/* Column identifiers */
private static final int IMAGE_ID_COLUMN = 0;
private static final int IMAGE_MANIFEST_COLUMN = 1;
private static final int IMAGE_STATE_COLUMN = 2;
private static final int IMAGE_OWNER_COLUMN = 3;
private static final int IMAGE_TAGS_COLUMN = 4;
/**
* Creates a new AMI selection table with the specified parent.
*
* @param parent
* The parent of this new selection table.
* @param listener
* The selection table listener object that should be notified
* when this selection table loads data.
*/
public AmiSelectionTable(Composite parent, SelectionTableListener listener) {
super(parent, false, true);
viewer.setContentProvider(contentProvider);
viewer.setLabelProvider(new ViewLabelProvider());
this.setListener(listener);
createToolbarActions();
refreshAmis();
viewer.getTree().addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
Image image = getSelectedImage();
if (image == null) return;
launchAction.run();
}
});
}
/**
* Refreshes the set of Amis asynchronously.
*/
private void refreshAmis() {
cancelLoadAmisThread();
loadImageThread = new LoadImageDescriptionsThread();
loadImageThread.start();
}
private void cancelLoadAmisThread() {
if ( loadImageThread != null ) {
synchronized (loadImageThread) {
if ( !loadImageThread.canceled ) {
loadImageThread.cancel();
}
}
}
}
@Override
public void dispose() {
cancelLoadAmisThread();
super.dispose();
}
private void createToolbarActions() {
amiDropDownMenuHandler = new MenuHandler();
amiDropDownMenuHandler.addListener(this);
amiDropDownMenuHandler.add("ALL", "All Images");
amiDropDownMenuHandler.add("amazon", "Amazon Images", true);
amiDropDownMenuHandler.add("Public", "Public Images");
amiDropDownMenuHandler.add("Private", "Private Images");
amiDropDownMenuHandler.add("ByMe", "Owned By Me");
amiDropDownMenuHandler.add("32-bit", "32-bit");
amiDropDownMenuHandler.add("64-bit", "64-bit");
amiFilterDropDownAction = new MenuAction("AMI Filter", "Filter AMIs", "filter", amiDropDownMenuHandler);
platformDropDownMenuHandler = new MenuHandler();
platformDropDownMenuHandler.addListener(this);
platformDropDownMenuHandler.add("ALL", "All Platforms", true);
platformDropDownMenuHandler.add("windows", "Windows");
platformFilterDropDownAction = new MenuAction("Platform Filter", "Filter by platform", "filter", platformDropDownMenuHandler);
refreshAction = new Action() {
@Override
public void run() {
refreshAmis();
}
};
refreshAction.setText("Refresh");
refreshAction.setDescription("Refresh the list of images");
refreshAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh"));
}
/**
* Returns an action object that refreshes the AMI selection table.
*
* @return An action object that refreshes the AMI selection table.
*/
public Action getRefreshAction() {
return refreshAction;
}
/**
* Returns the Action object that shows the AMI filter dropdown menus
*
* @return The IAction object that shows the AMI filter dropdown menus
*/
public IAction getAmiFilterDropDownAction() {
return amiFilterDropDownAction;
}
/**
* Returns the Action object that shows the Platform filter dropdown menus
*
* @return The IAction object that shows the Platform filter dropdown menus
*/
public IAction getPlatformFilterDropDownAction() {
return platformFilterDropDownAction;
}
/**
* Filters the AMI list to those matching the specified string.
*
* @param searchText The text on which to filter.
*/
public void filterImages(String searchText) {
contentProvider.setFilter(searchText);
viewer.refresh();
}
/**
* Returns the selected AMI.
*
* @return The currently selected AMI, or null if none is selected.
*/
public Image getSelectedImage() {
return (Image)getSelection();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("AMI ID", 10);
newColumn("Manifest", 20);
newColumn("State", 10);
newColumn("Owner", 10);
newColumn("Tags", 15);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
Image selectedImage = getSelectedImage();
launchAction.setEnabled(selectedImage != null);
deleteAmiAction.setEnabled(doesUserHavePermissionToDelete(selectedImage));
manager.add(refreshAction);
manager.add(new Separator());
manager.add(launchAction);
manager.add(new Separator());
manager.add(deleteAmiAction);
}
private boolean doesUserHavePermissionToDelete(Image ami) {
String userId = accountInfo.getUserId();
if (ami == null) return false;
if (userId == null) return false;
return ami.getOwnerId().equals(userId);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
launchAction = new Action() {
@Override
public void run() {
Image image = getSelectedImage();
new WizardDialog(Display.getCurrent().getActiveShell(), new LaunchWizard(image)).open();
}
};
launchAction.setText("Launch...");
launchAction.setToolTipText("Launch this image");
launchAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("launch"));
deleteAmiAction = new Action() {
@Override
public void run() {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText("Delete selected AMI?");
messageBox.setMessage("If you continue, you won't be able to use this AMI anymore.");
// Bail out if the user cancels...
if (messageBox.open() == SWT.CANCEL) return;
final Image image = getSelectedImage();
new DeleteAmiThread(image).start();
}
};
deleteAmiAction.setText("Delete AMI");
deleteAmiAction.setToolTipText("Delete the selected AMI");
deleteAmiAction.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("remove"));
}
private class ViewContentProvider implements ILazyTreeContentProvider {
private List<Image> unfilteredImages;
private List<Image> filteredImages;
private String filter;
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
filterImages();
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#dispose()
*/
@Override
public void dispose() {}
protected void applyFilters() {
filterImages();
}
private void filterImages() {
noOfAMIs = 0; //Resets no of AMIs
synchronized (this) {
if (unfilteredImages == null) unfilteredImages = new ArrayList<>();
}
// We filter based on Text filter and Drop down Filters
String[] searchTerms = (filter == null ? null : filter.split(" "));
List<Image> tempFilteredImages = new ArrayList<>(unfilteredImages.size());
for (Image image : unfilteredImages) {
boolean containsAllTerms = true;
if(searchTerms != null) {
for (String searchTerm : searchTerms) {
String imageDescription = image.getImageId() + " " + image.getImageLocation() + image.getOwnerId() + image.getState();
if (!imageDescription.toLowerCase().contains(searchTerm.toLowerCase())) {
containsAllTerms = false;
}
}
}
if (containsAllTerms) {
tempFilteredImages.add(image);
}
}
filteredImages = tempFilteredImages;
noOfAMIs = filteredImages.size();
viewer.getTree().setItemCount(filteredImages.size());
if (selectionTableListener != null) selectionTableListener.finishedLoadingData(noOfAMIs);
}
/**
* Sets the filter used to control what content is returned.
*
* @param filter The filter to be applied when returning content.
*/
public void setFilter(String filter) {
this.filter = filter;
applyFilters();
}
@Override
public void updateChildCount(Object element, int currentChildCount) {
if (element instanceof Image){
viewer.setChildCount(element, 0);
} else {
viewer.setChildCount(element, filteredImages.size());
}
}
@Override
public void updateElement(Object parent, int index) {
Object element = filteredImages.get(index);
viewer.replace(parent, index, element);
updateChildCount(element, -1);
}
public void setUnfilteredImages(List<Image> unfilteredImages) {
this.unfilteredImages = unfilteredImages;
}
@Override
public Object getParent(Object element) {
return null;
}
}
private class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
@Override
public String getColumnText(Object obj, int index) {
if (obj == null) {
return "??";
}
Image image = (Image)obj;
switch (index) {
case IMAGE_ID_COLUMN:
return image.getImageId();
case IMAGE_MANIFEST_COLUMN:
return image.getImageLocation();
case IMAGE_STATE_COLUMN:
return image.getState();
case IMAGE_OWNER_COLUMN:
return image.getOwnerId();
case IMAGE_TAGS_COLUMN:
return TagFormatter.formatTags(image.getTags());
}
return "???";
}
@Override
public org.eclipse.swt.graphics.Image getColumnImage(Object obj, int index) {
if (index == 0)
return Ec2Plugin.getDefault().getImageRegistry().get("ami");
return null;
}
@Override
public org.eclipse.swt.graphics.Image getImage(Object obj) {
return null;
}
}
/*
* Private Thread subclasses for making EC2 service calls.
*/
/**
* Thread subclass for making an EC2 service call to delete an AMI.
*/
private class DeleteAmiThread extends Thread {
/** The AMI to delete */
private final Image image;
/**
* Creates a new thread ready to be started to delete the specified AMI.
*
* @param image
* The AMI to delete.
*/
public DeleteAmiThread(Image image) {
this.image = image;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
DeregisterImageRequest request = new DeregisterImageRequest();
request.setImageId(image.getImageId());
getAwsEc2Client().deregisterImage(request);
refreshAmis();
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to delete AMI: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
/**
* Thread subclass for making EC2 service calls to load a list of AMIs.
*/
private class LoadImageDescriptionsThread extends Thread {
private boolean canceled = false;
private synchronized void cancel() {
canceled = true;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
enableActions(false);
if (selectionTableListener != null) selectionTableListener.loadingData();
try {
final List<Image> images = getImages();
synchronized (this) {
if ( !canceled ) {
noOfAMIs = images.size();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if ( viewer != null ) {
// There appears to be a bug in SWT virtual
// trees (at least on some platforms) that
// can lead to a stack overflow when trying
// to preserve selection on an input change.
viewer.getTree().deselectAll();
contentProvider.setUnfilteredImages(images);
viewer.setInput(images);
contentProvider.applyFilters();
}
}
});
if (selectionTableListener != null) selectionTableListener.finishedLoadingData(noOfAMIs);
enableActions(true);
}
}
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to query list of AMIs: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
if (selectionTableListener != null) selectionTableListener.finishedLoadingData(noOfAMIs);
enableActions(true);
}
}
/**
* Gets a list of images, filtering them according to the current filter
* control settings.
*/
public List<Image> getImages() {
DescribeImagesRequest request = new DescribeImagesRequest().withFilters(new LinkedList<Filter>());
request.getFilters().add(new Filter().withName("image-type").withValues("machine"));
String menuId = amiDropDownMenuHandler.getCurrentSelection().getMenuId();
if (!menuId.equals("ALL")) {
if (menuId.equals("amazon")) {
List<String> owners = new LinkedList<>();
owners.add("amazon");
request.setOwners(owners);
} else if (menuId.equals("Public")) {
request.getFilters().add(new Filter().withName("is-public").withValues("true"));
} else if (menuId.equals("Private")) {
request.getFilters().add(new Filter().withName("is-public").withValues("false"));
} else if (menuId.equals("ByMe")) {
List<String> owners = new LinkedList<>();
owners.add("self");
request.setOwners(owners);
} else if (menuId.equals("32-bit")) {
request.getFilters().add(new Filter().withName("architecture").withValues("i386"));
} else if (menuId.equals("64-bit")) {
request.getFilters().add(new Filter().withName("architecture").withValues("x86_64"));
}
}
if (!platformDropDownMenuHandler.getCurrentSelection().getMenuId().equals("ALL")) {
if (platformDropDownMenuHandler.getCurrentSelection().getMenuId().equals("windows")) {
request.getFilters().add(new Filter().withName("platform").withValues("windows"));
}
}
return getAwsEc2Client().describeImages(request).getImages();
}
}
/**
* Callback function. Is called from the DropdownMenuHandler when a menu
* option is clicked
*
* @see com.amazonaws.eclipse.ec2.utils.IMenu#menuClicked(com.amazonaws.eclipse.ec2.utils.IMenu.MenuItem)
*/
@Override
public void menuClicked(MenuItem itemSelected) {
refreshAmis();
}
/**
* Enables/Disables dropdown filters
*/
private void enableActions(boolean enabled) {
refreshAction.setEnabled(enabled);
amiFilterDropDownAction.setEnabled(enabled);
platformFilterDropDownAction.setEnabled(enabled);
}
}
| 7,228 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/amis/FilteredAmiSelectionTable.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.amis;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AccountAndRegionChangeListener;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.ui.StatusBar;
import com.amazonaws.services.ec2.model.Image;
/**
* Composite combining the AMI selection table with a status bar, filter text
* box to filter AMI results, and listeners to update the displayed AMIs when
* relevant preferences change (ex: AWS account preferences, EC2 region
* preferences, etc).
*/
public class FilteredAmiSelectionTable extends Composite implements IRefreshable {
/** The AMI selection table users select from. */
private AmiSelectionTable amiSelectionTable;
/**
* Listener for the AMI selection table to display data loading messages,
* etc.
*/
private StatusBar statusBar;
/**
* Listener for AWS account and region preference changes that require this
* view to be refreshed.
*/
private final AccountAndRegionChangeListener accountAndRegionChangeListener = new AccountAndRegionChangeListener() {
@Override
public void onAccountOrRegionChange() {
FilteredAmiSelectionTable.this.refreshData();
}
};
/**
* Constructs a new filtered AMI selection table in the specified parent.
*
* @param parent
* The parent composite in which to create the new AMI selection
* composite.
*/
public FilteredAmiSelectionTable(Composite parent) {
this(parent, null, 0);
}
/**
* Constructs a new table with an in-lined tool bar
*
* @param numButtons
* The number of widgets in the toolbar, for layout purposes.
*
* @see FilteredAmiSelectionTable#FilteredAmiSelectionTable(Composite)
*/
public FilteredAmiSelectionTable(Composite parent, ToolBarManager toolbar, int numButtons) {
super(parent, SWT.BORDER);
// Start listening to preference changes
AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().addDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().addDefaultRegionChangeListener(accountAndRegionChangeListener);
GridLayout gridLayout = new GridLayout(2 + numButtons, false);
gridLayout.marginTop = 4;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.verticalSpacing = 3;
setLayout(gridLayout);
statusBar = new StatusBar(this);
statusBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
statusBar.setRecordLabel("Displayed AMIs: ");
if ( toolbar != null ) {
toolbar.createControl(this);
}
final Text text = new Text(this, SWT.SEARCH | SWT.CANCEL);
GridData gridData = new GridData();
gridData.widthHint = 150;
text.setLayoutData(gridData);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
if (amiSelectionTable != null)
amiSelectionTable.filterImages(text.getText());
}
});
text.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {
if (e.detail != SWT.CANCEL && amiSelectionTable != null) {
amiSelectionTable.filterImages(text.getText());
}
}
});
amiSelectionTable = new AmiSelectionTable(this, statusBar);
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalSpan = 2 + numButtons;
gridData.heightHint = 250;
gridData.minimumWidth = 350;
amiSelectionTable.setLayoutData(gridData);
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
AwsToolkitCore.getDefault().getAccountManager().removeAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().removeDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(accountAndRegionChangeListener);
if (statusBar != null) statusBar.dispose();
if (amiSelectionTable != null) amiSelectionTable.dispose();
super.dispose();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.core.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
amiSelectionTable.getRefreshAction().run();
}
/**
* Adds the specified selection listener to this control.
*
* @param listener
* The selection listener to add to this control.
*
* @see AmiSelectionTable#addSelectionListener(SelectionListener)
*/
public void addSelectionListener(SelectionListener listener) {
amiSelectionTable.addSelectionListener(listener);
}
/**
* Returns the selected Amazon Machine Image (AMI), or null if there
* isn't one selected.
*
* @return The selected AMI, or null if there isn't one selected.
*
* @see AmiSelectionTable#getSelectedImage()
*/
public Image getSelectedImage() {
return amiSelectionTable.getSelectedImage();
}
/**
* Returns the AMI selection table contained in this filtered AMI selection
* table.
*
* @return The AMI selection table contained in this filtered AMI selection
* table.
*/
public AmiSelectionTable getAmiSelectionTable() {
return amiSelectionTable;
}
}
| 7,229 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/amis/AmiBrowserView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.amis;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;
import com.amazonaws.eclipse.core.ui.IRefreshable;
/**
* View for working with AMIs.
*/
public class AmiBrowserView extends ViewPart implements IRefreshable {
/** AMI selection table displaying the available AMIs */
private FilteredAmiSelectionTable filteredAmiSelectionTable;
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createPartControl(final Composite parent) {
parent.setLayout(new FillLayout());
filteredAmiSelectionTable = new FilteredAmiSelectionTable(parent);
filteredAmiSelectionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
contributeToActionBars();
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
public void dispose() {
if (filteredAmiSelectionTable != null)
filteredAmiSelectionTable.dispose();
super.dispose();
}
/**
* Adds a refresh button to this view's toolbar.
*/
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
IToolBarManager manager = bars.getToolBarManager();
manager.add(filteredAmiSelectionTable.getAmiSelectionTable().getRefreshAction());
manager.add(filteredAmiSelectionTable.getAmiSelectionTable().getAmiFilterDropDownAction());
manager.add(filteredAmiSelectionTable.getAmiSelectionTable().getPlatformFilterDropDownAction());
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
@Override
public void setFocus() {
filteredAmiSelectionTable.setFocus();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
if (filteredAmiSelectionTable != null) {
filteredAmiSelectionTable.refreshData();
}
}
}
| 7,230 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/BundleJob.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.ec2.AmiToolsVersion;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.RemoteCommandUtils;
import com.amazonaws.eclipse.ec2.ShellCommandException;
import com.amazonaws.eclipse.ec2.ShellCommandResults;
import com.amazonaws.eclipse.ec2.ui.ShellCommandErrorDialog;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.RegisterImageRequest;
/**
* Eclipse Job encapsulating the logic to bundle a specified instance as a new AMI.
*/
class BundleJob extends Job {
private final Instance instance;
private final String bundleName;
private final String s3Bucket;
private final AccountInfo accountInfo;
/** Shared utilities for executing remote commands */
private final static RemoteCommandUtils remoteCommandUtils = new RemoteCommandUtils();
/** Shared logger */
private static final Logger logger = Logger.getLogger(BundleJob.class.getName());
/** The minimum required version of the EC2 AMI Tools */
private static final AmiToolsVersion requiredVersion = new AmiToolsVersion(1, 3, 31780);
/**
* Creates a new Bundle Job to bundle the specified instances and store the
* data in the specified S3 bucket with the specified bundle name.
*
* @param instance
* The instance to bundle into an AMI.
* @param s3Bucket
* The S3 bucket to store the bundled image in.
* @param bundleName
* The name of the AMI manifest.
*/
public BundleJob(Instance instance, String s3Bucket, String bundleName) {
super("Bundling instance " + instance.getInstanceId());
this.instance = instance;
this.bundleName = bundleName;
this.s3Bucket = s3Bucket;
this.accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
}
/*
* Job Interface
*/
/* (non-Javadoc)
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Bundling", 110);
try {
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
checkRequirements();
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
transferKeys(monitor);
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
bundleVolume(monitor);
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
deleteKeys(monitor);
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
uploadBundle(monitor);
if (monitor.isCanceled()) return Status.CANCEL_STATUS;
final String amiName = registerBundle(monitor);
final String message = "Successfully created AMI " + amiName;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_INFORMATION | SWT.OK);
messageBox.setMessage(message);
messageBox.setText("AMI Bundling Complete");
messageBox.open();
}
});
Status status = new Status(Status.INFO, Ec2Plugin.PLUGIN_ID, message);
StatusManager.getManager().handle(status, StatusManager.LOG);
logger.info("Successfully created AMI: " + amiName);
} catch (final ShellCommandException sce) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
new ShellCommandErrorDialog(sce).open();
}
});
/*
* We return a warning status instead of an error status since the
* warning status doesn't cause another dialog to pop up (since
* we're already displaying our own).
*/
return new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to bundle instance: " + sce.getMessage(), sce);
} catch (Exception e) {
e.printStackTrace();
return new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to bundle instance: " + e.getMessage(), e);
}
return Status.OK_STATUS;
}
/*
* Private Interface
*/
/**
* Checks requirements such as minimum required AMI tools version on the
* remote host before the bundling process begins to try and detect anything
* that will cause problems.
*
* @throws Exception
* If this method detected a known problem.
*/
private void checkRequirements() throws Exception {
/*
* We seen bundling fail for older AMI tools versions that can't
* automatically figure out the proper architecture
* (ex: ec2-ami-tools-version 1.3-20041), so we want to warn the user
* early if we know there's going to be a problem.
*/
/*
* TODO: We should also do more error checking in general,
* such as S3 bucket validation.
*/
List<ShellCommandResults> results =
remoteCommandUtils.executeRemoteCommand("ec2-ami-tools-version", instance);
// Find the output from the first successful attempt
String output = null;
for (ShellCommandResults result : results) {
if (result.exitCode == 0) {
output = result.output;
break;
}
}
// If we can't find the output from a successful run, just bail out
if (output == null) {
return;
}
AmiToolsVersion version = null;
try {
version = new AmiToolsVersion(output);
} catch (ParseException pe) {
/*
* If we can't parse the AMI tools version, we want to bail out
* instead of stopping the bundling operation. The version number
* format could have changed, for example, and we wouldn't want to
* break everybody if that happened.
*/
return;
}
if (requiredVersion.isGreaterThan(version)) {
throw new Exception("The version of the EC2 AMI Tools on the remote host is too old " +
"(" + version.toString() + "). " +
"The AWS Toolkit for Eclipse requires version " + requiredVersion.toString() +
" or greater. \n\nFor information on updating the EC2 AMI Tools on your " +
"instance, consult the EC2 Developer Guide available from: http://aws.amazon.com/documentation ");
}
}
/**
* Registers the uploaded bundle as an EC2 AMI.
*
* @param monitor The progress monitor for this job.
* @return The ID of the AMI created when registering the bundle.
*/
private String registerBundle(IProgressMonitor monitor) {
monitor.subTask("Registering bundle");
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
RegisterImageRequest request = new RegisterImageRequest();
request.setImageLocation(s3Bucket + "/" + bundleName + ".manifest.xml");
String amiName = ec2.registerImage(request).getImageId();
monitor.worked(5);
return amiName;
}
/**
* Uploads the bundled volume to S3.
*
* @param monitor The progress monitor for this job.
* @throws IOException
* @throws InterruptedException
*/
private void uploadBundle(IProgressMonitor monitor) throws IOException,
InterruptedException {
monitor.subTask("Uploading bundle");
String manifestFile = "/mnt/" + bundleName + ".manifest.xml";
String uploadCommand = "ec2-upload-bundle "
+ " --bucket " + s3Bucket
+ " --manifest " + manifestFile
+ " --access-key " + accountInfo.getAccessKey()
+ " --secret-key " + accountInfo.getSecretKey();
Region region = RegionUtils.getCurrentRegion();
String regionId = region.getId().toLowerCase();
/*
* We need to make sure that the bundle is uploaded to the correct S3
* location depending on what region we're going to register the AMI in.
*/
if (regionId.startsWith("eu")) {
uploadCommand += " --location EU";
} else if (regionId.startsWith("us")) {
uploadCommand += " --location US";
}
remoteCommandUtils
.executeRemoteCommand(uploadCommand, instance);
monitor.worked(35);
}
/**
* Connects to the EC2 instance to bundle the volume.
*
* @param monitor The progress monitor for this job.
* @throws IOException
* @throws InterruptedException
*/
private void bundleVolume(IProgressMonitor monitor) throws IOException,
InterruptedException {
monitor.subTask("Bundling volume");
File privateKeyFile = new File(accountInfo.getEc2PrivateKeyFile());
String privateKeyBaseFileName = privateKeyFile.getName();
File certificateFile = new File(accountInfo.getEc2CertificateFile());
String certificateBaseFileName = certificateFile.getName();
String bundleCommand = "ec2-bundle-vol --destination /mnt "
+ " --privateKey /mnt/" + privateKeyBaseFileName
+ " --cert /mnt/" + certificateBaseFileName
+ " --user " + accountInfo.getUserId()
+ " --batch --prefix " + bundleName;
remoteCommandUtils.executeRemoteCommand(bundleCommand, instance);
monitor.worked(50);
}
/**
* Securely transfers the user's key and certificate to the EC2 instance so that
* the bundle can be signed.
*
* @param monitor The progress monitor for this job.
* @throws IOException
* @throws InterruptedException
*/
private void transferKeys(IProgressMonitor monitor) throws IOException,
InterruptedException {
monitor.subTask("Transfering keys");
File privateKeyFile = new File(accountInfo.getEc2PrivateKeyFile());
String privateKeyBaseFileName = privateKeyFile.getName();
File certificateFile = new File(accountInfo.getEc2CertificateFile());
String certificateBaseFileName = certificateFile.getName();
remoteCommandUtils.copyRemoteFile(accountInfo.getEc2CertificateFile(), "/mnt/" + certificateBaseFileName, instance);
monitor.worked(5);
remoteCommandUtils.copyRemoteFile(accountInfo.getEc2PrivateKeyFile(), "/mnt/" + privateKeyBaseFileName, instance);
monitor.worked(5);
}
/**
* Deletes the user's key and certificate that were previously transfered.
*
* @param monitor
* The progress monitor for this job.
* @throws IOException
* If any problems were encountered deleting the EC2 key and
* cert.
*/
private void deleteKeys(IProgressMonitor monitor) {
monitor.subTask("Deleting keys");
File privateKeyFile = new File(accountInfo.getEc2PrivateKeyFile());
String privateKeyBaseFileName = privateKeyFile.getName();
File certificateFile = new File(accountInfo.getEc2CertificateFile());
String certificateBaseFileName = certificateFile.getName();
try {
remoteCommandUtils.executeRemoteCommand("rm /mnt/" + certificateBaseFileName, instance);
} catch (IOException e) {
Status status = new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to remove EC2 certificate: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
monitor.worked(5);
try {
remoteCommandUtils.executeRemoteCommand("rm /mnt/" + privateKeyBaseFileName, instance);
} catch (IOException e) {
Status status = new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to remove EC2 private key: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
monitor.worked(5);
}
}
| 7,231 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/DeviceDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* Dialog allowing the user to select which device an EBS volume should be
* attached to.
*/
class DeviceDialog extends MessageDialog {
/** The default device to attach a volume to */
private static final String DEFAULT_DEVICE = "/dev/sdh";
/** Stores the selected device after this dialog is disposed */
private String device;
/** The combo box where the user selects the device */
private Combo deviceCombo;
/**
* Creates a new DeviceDialog ready to be opened.
*/
public DeviceDialog() {
super(new Shell(),
"Select Device",
null,
"Select the device to attach this volume to.",
MessageDialog.QUESTION,
new String[] {"OK", "Cancel"},
0);
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.MessageDialog#createCustomArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createCustomArea(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
composite.setLayout(new GridLayout(2, false));
Label label = new Label(composite, SWT.NONE);
label.setText("Device:");
deviceCombo = new Combo(composite, SWT.READ_ONLY);
deviceCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String devicePrefix = "/dev/sd";
for (char c = 'b'; c <= 'z'; c++) {
deviceCombo.add(devicePrefix + c);
}
deviceCombo.setText(DEFAULT_DEVICE);
return composite;
}
/**
* Returns the device the user selected (ex: '/dev/sdh').
*
* @return The device the user selected (ex: '/dev/sdh').
*/
public String getDevice() {
return device;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.MessageDialog#buttonPressed(int)
*/
@Override
protected void buttonPressed(int buttonId) {
if (buttonId == DeviceDialog.OK) {
device = deviceCombo.getText();
}
super.buttonPressed(buttonId);
}
}
| 7,232 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/AttachNewVolumeThread.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AttachVolumeRequest;
import com.amazonaws.services.ec2.model.CreateVolumeRequest;
import com.amazonaws.services.ec2.model.CreateVolumeResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Volume;
/**
* Thread for making a service call to EC2 to create a new EBS volume and
* attach it to a specified instance.
*/
class AttachNewVolumeThread extends Thread {
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/** The snapshot from which to create the new volume */
private final String snapshotId;
/** The instance to attach the new volume */
private final Instance instance;
/** The size of the new volume */
private final int size;
/** The device the new volume should be attached to */
private final String device;
/**
* Creates a new AttachNewVolumeThread ready to be started to create a
* new volume and attach it to the specified instance.
*
* @param instance
* The instance to attach the new volume to.
* @param size
* The size of the new volume (ignored if a snapshot is
* specified).
* @param snapshotId
* An ID of a snapshot to create the new volume from.
* @param device
* The device the EBS volume should be attached to on the
* remote instance.
* @param instanceSelectionTable TODO
*/
public AttachNewVolumeThread(Instance instance, int size, String snapshotId, String device) {
this.instance = instance;
this.size = size;
this.snapshotId = snapshotId;
this.device = device;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
CreateVolumeRequest createVolumeRequest = new CreateVolumeRequest();
createVolumeRequest.setAvailabilityZone(instance.getPlacement().getAvailabilityZone());
// Only set size if we're not using a snapshot
if (snapshotId == null) createVolumeRequest.setSize(size);
createVolumeRequest.setSnapshotId(snapshotId);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
CreateVolumeResult createVolumeResponse = ec2.createVolume(createVolumeRequest);
AttachVolumeRequest attachVolumeRequest = new AttachVolumeRequest();
Volume volume = createVolumeResponse.getVolume();
attachVolumeRequest.setDevice(device);
attachVolumeRequest.setInstanceId(instance.getInstanceId());
attachVolumeRequest.setVolumeId(volume.getVolumeId());
ec2.attachVolume(attachVolumeRequest);
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to attach new volume: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
| 7,233 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/DetachVolumeAction.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.DetachVolumeRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Volume;
import com.amazonaws.services.ec2.model.VolumeAttachment;
/**
* Action to detach a volume from a specified instance.
*/
class DetachVolumeAction extends Action {
/** The volume that will be detached */
private final Volume volume;
/** The instance to attach the specified volume to */
private final Instance instance;
/** Shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new detach volume action ready to be run.
*
* @param volume
* The volume that will be detached when this action is
* run.
* @param instance
* The instance from which to detach the specified volume.
*/
public DetachVolumeAction(Volume volume, Instance instance) {
this.volume = volume;
this.instance = instance;
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
String selectedInstanceId = instance.getInstanceId();
for (VolumeAttachment attachmentInfo : volume.getAttachments()) {
String instanceId = attachmentInfo.getInstanceId();
String volumeId = attachmentInfo.getVolumeId();
String device = attachmentInfo.getDevice();
// We want to ensure that we only detach the specified instance
if (!instanceId.equals(selectedInstanceId)) continue;
try {
DetachVolumeRequest request = new DetachVolumeRequest();
request.setVolumeId(volumeId);
request.setInstanceId(instanceId);
request.setDevice(device);
request.setForce(true);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.detachVolume(request);
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to detach volume: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Detach " + volume.getVolumeId() + " (" + volume.getSize() + " GB)";
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Detach volume " + volume.getVolumeId() + " from selected instance " + instance.getInstanceId();
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("volume");
}
}
| 7,234 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/TerminateInstancesAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.explorer.AwsAction;
final class TerminateInstancesAction extends AwsAction {
private final InstanceSelectionTable instanceSelectionTable;
/**
* @param instanceSelectionTable
*/
TerminateInstancesAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_TERMINATE_ACTION);
this.instanceSelectionTable = instanceSelectionTable;
}
@Override
public void doRun() {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText("Terminate selected instances?");
messageBox.setMessage("If you continue, you won't be able to access these instances again.");
// Bail out if the user cancels...
if (messageBox.open() == SWT.CANCEL) {
actionCanceled();
} else {
new TerminateInstancesThread(this.instanceSelectionTable, instanceSelectionTable.getAllSelectedInstances()).start();
actionSucceeded();
}
actionFinished();
}
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("terminate");
}
@Override
public String getText() {
return "Terminate";
}
@Override
public String getToolTipText() {
return "Terminate instances";
}
}
| 7,235 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/StopInstancesAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
/**
* Action to stop an EBS-backed instance.
*/
public class StopInstancesAction extends AwsAction {
private final InstanceSelectionTable instanceSelectionTable;
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new action which, when run, will start the instances given
*
* @param instance
* The instances to start.
* @param volume
* The volume to attach.
*/
public StopInstancesAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_STOP_INSTANCES_ACTION);
this.instanceSelectionTable = instanceSelectionTable;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#isEnabled()
*/
@Override
public boolean isEnabled() {
for ( Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
if ( !instance.getState().getName().equalsIgnoreCase("running")
|| !instance.getRootDeviceType().equalsIgnoreCase("ebs") )
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void doRun() {
final List<String> instanceIds = new ArrayList<>();
for ( Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
instanceIds.add(instance.getInstanceId());
}
new Thread() {
@Override
public void run() {
try {
StopInstancesRequest request = new StopInstancesRequest().withInstanceIds(instanceIds);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.stopInstances(request);
instanceSelectionTable.refreshInstances();
actionSucceeded();
} catch ( Exception e ) {
actionFailed();
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to stop instances: "
+ e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
} finally {
actionFinished();
}
}
}.start();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Stop instances";
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("stop");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Stop this instance";
}
}
| 7,236 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/TerminateInstancesThread.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
* Thread for making a service call to EC2 to terminate a list of instances.
*/
class TerminateInstancesThread extends Thread {
private final InstanceSelectionTable instanceSelectionTable;
/** The instances to terminate */
private final List<Instance> instances;
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new TerminateInstancesThread ready to be started and reboot
* the specified instances.
*
* @param instances
* The instances to reboot.
* @param instanceSelectionTable TODO
*/
public TerminateInstancesThread(InstanceSelectionTable instanceSelectionTable, List<Instance> instances) {
this.instanceSelectionTable = instanceSelectionTable;
this.instances = instances;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
List<String> instanceIds = new ArrayList<>();
for (Instance instance : instances) {
instanceIds.add(instance.getInstanceId());
}
TerminateInstancesRequest request = new TerminateInstancesRequest();
request.setInstanceIds(instanceIds);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.terminateInstances(request);
this.instanceSelectionTable.refreshInstances();
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to terminate instance: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
| 7,237 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/RefreshTimer.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.ui.IRefreshable;
/**
* Timer responsible for controlling when a specified control is refreshed.
*/
public class RefreshTimer implements Runnable {
/** The default period (in milliseconds) between refreshes */
public static final int DEFAULT_TIMER_PERIOD = 60 * 1000;
/** The control that this timer is responsible for refreshing */
private final IRefreshable control;
/** The period (in milliseconds) between refreshes */
private int refreshPeriodInMilliseconds;
/**
* Creates a new RefreshTimer ready to refresh the specified control
* with the default period. Note that once a RefreshTimer has been
* created, it needs to be explicitly started before it will start
* refreshing the specified control.
*
* @param control
* The control this timer is responsible for refreshing.
*/
public RefreshTimer(IRefreshable control) {
this(control, DEFAULT_TIMER_PERIOD);
}
/**
* Creates a new RefreshTimer ready to refresh the specified control
* with the specified period. Note that a RefreshTimer has been
* created, it needs to be explicitly started before it will start
* refreshing the specified control.
*
* @param control
* The control this timer is responsible for refreshing.
* @param refreshPeriodInMilliseconds
* The period between refreshes, in milliseconds.
*/
public RefreshTimer(IRefreshable control, int refreshPeriodInMilliseconds) {
this.control = control;
this.refreshPeriodInMilliseconds = refreshPeriodInMilliseconds;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
control.refreshData();
startTimer();
}
/**
* Sets the period, in milliseconds, between refreshes.
*
* @param refreshPeriodInMilliseconds
* The period, in milliseconds, between refreshes.
*/
public void setRefreshPeriod(int refreshPeriodInMilliseconds) {
this.refreshPeriodInMilliseconds = refreshPeriodInMilliseconds;
startTimer();
}
/**
* Starts this refresh timer.
*/
public void startTimer() {
Display.getDefault().timerExec(refreshPeriodInMilliseconds, this);
}
/**
* Stops this refresh timer.
*/
public void stopTimer() {
Display.getDefault().timerExec(-1, this);
}
}
| 7,238 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/ViewContentAndLabelProvider.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.TagFormatter;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Tag;
/**
* Label and content provider for the EC2 Instance table.
*/
class ViewContentAndLabelProvider extends BaseLabelProvider
implements ITreeContentProvider, ITableLabelProvider {
static final int INSTANCE_ID_COLUMN = 0;
static final int INSTANCE_NAME_COLUMN = 1;
static final int PUBLIC_DNS_COLUMN = 2;
static final int IMAGE_ID_COLUMN = 3;
static final int ROOT_DEVICE_COLUMN = 4;
static final int STATE_COLUMN = 5;
static final int INSTANCE_TYPE_COLUMN = 6;
static final int AVAILABILITY_ZONE_COLUMN = 7;
static final int KEY_NAME_COLUMN = 8;
static final int LAUNCH_TIME_COLUMN = 9;
static final int SECURITY_GROUPS_COLUMN = 10;
static final int TAGS_COLUMN = 11;
private final DateFormat dateFormat;
private KeyPairManager keyPairManager = new KeyPairManager();
/** The input to be displayed by this content / label provider */
private InstancesViewInput instancesViewInput;
/** Map of instance states to images representing those states */
private static final Map<String, Image> stateImageMap = new HashMap<>();
static {
stateImageMap.put("running", Ec2Plugin.getDefault().getImageRegistry().get("status-running"));
stateImageMap.put("rebooting", Ec2Plugin.getDefault().getImageRegistry().get("status-rebooting"));
stateImageMap.put("shutting-down", Ec2Plugin.getDefault().getImageRegistry().get("status-waiting"));
stateImageMap.put("pending", Ec2Plugin.getDefault().getImageRegistry().get("status-waiting"));
stateImageMap.put("stopping", Ec2Plugin.getDefault().getImageRegistry().get("status-waiting"));
stateImageMap.put("stopped", Ec2Plugin.getDefault().getImageRegistry().get("status-terminated"));
stateImageMap.put("terminated", Ec2Plugin.getDefault().getImageRegistry().get("status-terminated"));
}
/** Default constructor */
ViewContentAndLabelProvider() {
dateFormat = DateFormat.getDateTimeInstance();
}
/*
* IStructuredContentProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
instancesViewInput = (InstancesViewInput)newInput;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.BaseLabelProvider#dispose()
*/
@Override
public void dispose() {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
*/
@Override
public Object[] getElements(Object parent) {
if (instancesViewInput == null) {
return new Object[0];
}
return instancesViewInput.instances.toArray();
}
/*
* ITableLabelProvider Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
@Override
public String getColumnText(Object obj, int index) {
Instance instance = (Instance)obj;
switch (index) {
case INSTANCE_ID_COLUMN:
return instance.getInstanceId();
case INSTANCE_NAME_COLUMN:
return getInstanceName(instance);
case PUBLIC_DNS_COLUMN:
return instance.getPublicDnsName();
case ROOT_DEVICE_COLUMN:
return instance.getRootDeviceType();
case STATE_COLUMN:
return instance.getState().getName();
case INSTANCE_TYPE_COLUMN:
return instance.getInstanceType().toString();
case AVAILABILITY_ZONE_COLUMN:
return instance.getPlacement().getAvailabilityZone();
case IMAGE_ID_COLUMN:
return instance.getImageId();
case KEY_NAME_COLUMN:
return instance.getKeyName();
case LAUNCH_TIME_COLUMN:
if ( instance.getLaunchTime() == null )
return "";
return dateFormat.format(instance.getLaunchTime());
case SECURITY_GROUPS_COLUMN:
return formatSecurityGroups(instancesViewInput.securityGroupMap.get(instance.getInstanceId()));
case TAGS_COLUMN:
return TagFormatter.formatTags(instance.getTags());
default:
return "???";
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
@Override
public Image getColumnImage(Object obj, int index) {
Instance instance = (Instance)obj;
switch (index) {
case INSTANCE_ID_COLUMN:
return Ec2Plugin.getDefault().getImageRegistry().get("server");
case KEY_NAME_COLUMN:
if (keyPairManager.isKeyPairValid(AwsToolkitCore.getDefault().getCurrentAccountId(), instance.getKeyName())) {
return Ec2Plugin.getDefault().getImageRegistry().get("check");
} else {
return Ec2Plugin.getDefault().getImageRegistry().get("error");
}
case STATE_COLUMN:
String state = instance.getState().getName().toLowerCase();
return stateImageMap.get(state);
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.LabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object obj) {
return null;
}
/*
* Package Interface
*/
/**
* Provides access to the instance -> security groups mapping contained in
* this class. This should probably be shifted around into another location,
* but for now we'll provide this data from here. If the amount of other
* data we need to associated with the Instance datatype grows a lot,
* we should definitely clean this up so that other objects can more easily
* access this data.
*
* @param instanceId
* The ID of the instance to look up.
*
* @return A list of the security groups the specified instance is in.
*/
List<String> getSecurityGroupsForInstance(String instanceId) {
if (instancesViewInput == null) {
return null;
}
return instancesViewInput.securityGroupMap.get(instanceId);
}
/*
* Private Interface
*/
/**
* Takes the list of security groups and turns it into a comma separated
* string list.
*
* @param securityGroups
* A list of security groups to turn into a comma separated
* string list.
*
* @return A comma separated list containing the contents of the specified
* list of security groups.
*/
private String formatSecurityGroups(List<String> securityGroups) {
if (securityGroups == null) return "";
String allSecurityGroups = "";
for (String securityGroup : securityGroups) {
if (allSecurityGroups.length() > 0) allSecurityGroups += ", ";
allSecurityGroups += securityGroup;
}
return allSecurityGroups;
}
@Override
public Object[] getChildren(Object parentElement) {
return new Object[0];
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return false;
}
private String getInstanceName(Instance instance) {
List<Tag> tags = instance.getTags();
if (tags != null && !tags.isEmpty()) {
for (Tag tag : tags) {
if (tag.getKey().equals("Name")) {
return tag.getValue();
}
}
}
return "";
}
}
/**
* Simple container for the instances and security group mappings displayed
* by the viewer associated with this content/label provider.
*/
class InstancesViewInput {
/** The EC2 instances being displayed by this viewer */
public final List<Instance> instances;
/** A map of instance ids -> security groups */
public final Map<String, List<String>> securityGroupMap;
/**
* Constructs a new InstancesViewInput object with the specified list of
* instances and mapping of instances to security groups.
*
* @param instances
* A list of the instances that should be displayed.
* @param securityGroupMap
* A map of instance ids to the list of security groups in which
* that instance was launched.
*/
public InstancesViewInput(final List<Instance> instances, final Map<String, List<String>> securityGroupMap) {
this.instances = instances;
this.securityGroupMap = securityGroupMap;
}
}
| 7,239 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/OpenShellAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.PlatformUtils;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.eclipse.ec2.preferences.PreferenceConstants;
import com.amazonaws.eclipse.ec2.ui.SetupExternalToolsAction;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.model.Instance;
class OpenShellAction extends AwsAction {
protected final InstanceSelectionTable instanceSelectionTable;
public OpenShellAction(InstanceSelectionTable instanceSelectionTable) {
this(AwsToolkitMetricType.EXPLORER_EC2_OPEN_SHELL_ACTION, instanceSelectionTable);
}
protected OpenShellAction(AwsToolkitMetricType metricType, InstanceSelectionTable instanceSelectionTable) {
super(metricType);
this.instanceSelectionTable = instanceSelectionTable;
this.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("console"));
this.setText("Open Shell");
this.setToolTipText("Opens a connection to this host");
}
@Override
public void doRun() {
for ( final Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
try {
openInstanceShell(instance);
actionSucceeded();
} catch (Exception e) {
actionFailed();
Ec2Plugin.getDefault().reportException("Unable to open a shell to the selected instance: " + e.getMessage(), e);
} finally {
actionFinished();
}
}
}
protected void openInstanceShell(Instance instance) throws Exception {
openInstanceShell(instance, null);
}
protected void openInstanceShell(Instance instance, String user) throws Exception {
PlatformUtils platformUtils = new PlatformUtils();
KeyPairManager keyPairManager = new KeyPairManager();
String keyName = instance.getKeyName();
String keyPairFilePath = keyPairManager.lookupKeyPairPrivateKeyFile(AwsToolkitCore.getDefault().getCurrentAccountId(), keyName);
if (user == null) {
user = Ec2Plugin.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SSH_USER);
}
if ( keyPairFilePath == null ) {
throw new Exception("Unable to locate the private key file for the selected key '" + keyName + "'");
}
if ( !platformUtils.isSshClientConfigured() ) {
String message = "Your SSH client doesn't appear to be configured correctly yet. Would you like to configure it now?";
if ( MessageDialog.openQuestion(Display.getCurrent().getActiveShell(), "SSH Client Configuration",
message) ) {
new SetupExternalToolsAction().run();
}
return;
}
platformUtils.openShellToRemoteHost(user, instance.getPublicDnsName(), keyPairFilePath);
}
}
| 7,240 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/InstanceView.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;
import com.amazonaws.eclipse.core.AccountAndRegionChangeListener;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.ui.SelectionTable.SelectionTableListener;
import com.amazonaws.eclipse.ec2.ui.StatusBar;
/**
* View for working with EC2 instances.
*/
public class InstanceView extends ViewPart implements IRefreshable, SelectionTableListener {
/** Shared factory for creating EC2 clients */
private StatusBar statusBar;
/** Table of running instances */
private InstanceSelectionTable selectionTable;
/**
* Listener for AWS account and region preference changes that require this
* view to be refreshed.
*/
AccountAndRegionChangeListener accountAndRegionChangeListener = new AccountAndRegionChangeListener() {
@Override
public void onAccountOrRegionChange() {
InstanceView.this.refreshData();
}
};
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
if (selectionTable != null) {
selectionTable.refreshInstances();
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createPartControl(Composite parent) {
GridLayout layout = new GridLayout(1, false);
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.verticalSpacing = 2;
parent.setLayout(layout);
statusBar = new StatusBar(parent);
statusBar.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
statusBar.setRecordLabel("Displayed Instances: ");
selectionTable = new InstanceSelectionTable(parent);
selectionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
selectionTable.setListener(this);
refreshData();
contributeToActionBars();
}
@Override
public void init(IViewSite aSite, IMemento aMemento) throws PartInitException {
super.init(aSite, aMemento);
AwsToolkitCore.getDefault().getAccountManager().addAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().addDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().addDefaultRegionChangeListener(accountAndRegionChangeListener);
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#dispose()
*/
@Override
public void dispose() {
AwsToolkitCore.getDefault().getAccountManager().removeAccountInfoChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().getAccountManager().removeDefaultAccountChangeListener(accountAndRegionChangeListener);
AwsToolkitCore.getDefault().removeDefaultRegionChangeListener(accountAndRegionChangeListener);
if (statusBar != null) statusBar.dispose();
if (selectionTable != null) selectionTable.dispose();
super.dispose();
}
private void contributeToActionBars() {
IActionBars bars = getViewSite().getActionBars();
bars.getToolBarManager().add(selectionTable.getRefreshAction());
/** Adds Dropdown filter action for Instance States */
bars.getToolBarManager().add(selectionTable.getInstanceStateFilterDropDownAction());
/** Adds Dropdown filter action for Security Filter Groups */
bars.getToolBarManager().add(selectionTable.getSecurityGroupFilterAction());
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
selectionTable.setFocus();
}
/*
* SelectionTableListener Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable.SelectionTableListener#finishedLoadingData()
*/
@Override
public void finishedLoadingData(int noOfInstances) {
statusBar.finishedLoadingData(noOfInstances);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable.SelectionTableListener#loadingData()
*/
@Override
public void loadingData() {
statusBar.loadingData();
}
}
| 7,241 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/BundleDialog.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
/**
* Dialog to allow users to specify options for bundling AMIs from instances.
*/
class BundleDialog extends Dialog {
private Text bucketNameText;
private Text imageNameText;
private String bucketName;
private String imageName;
/**
* Creates a new Bundle Dialog parented by the specified shell.
*
* @param parentShell
* The parent shell for this new Dialog.
*/
protected BundleDialog(Shell parentShell) {
super(parentShell);
}
public String getS3Bucket() {
return bucketName;
}
public String getImageName() {
return imageName;
}
/*
* Dialog Interface
*/
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonBar(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createButtonBar(Composite parent) {
Control control = super.createButtonBar(parent);
updateOkButton();
return control;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createDialogArea(Composite parent) {
ModifyListener listener = new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateOkButton();
}
};
this.getShell().setText("Bundle Image");
Composite composite = new Composite(parent, SWT.BORDER);
GridLayout gridLayout = new GridLayout(2, false);
gridLayout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
gridLayout.marginWidth = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
gridLayout.verticalSpacing = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
gridLayout.horizontalSpacing = convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(gridLayout);
composite.setLayoutData(new GridData(GridData.FILL_BOTH));
GridData gridData;
Label label = new Label(composite, SWT.NONE);
label.setText("Amazon S3 Bucket:");
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalAlignment = SWT.LEFT;
gridData.verticalAlignment = SWT.CENTER;
label.setLayoutData(gridData);
bucketNameText = new Text(composite, SWT.BORDER);
bucketNameText.addModifyListener(listener);
gridData = new GridData(GridData.FILL_BOTH);
gridData.widthHint = 300;
bucketNameText.setLayoutData(gridData);
label = new Label(composite, SWT.NONE);
label.setText("Image Name:");
gridData = new GridData(GridData.FILL_BOTH);
gridData.horizontalAlignment = SWT.LEFT;
gridData.verticalAlignment = SWT.CENTER;
label.setLayoutData(gridData);
imageNameText = new Text(composite, SWT.BORDER);
imageNameText.addModifyListener(listener);
gridData = new GridData(GridData.FILL_BOTH);
gridData.widthHint = 300;
imageNameText.setLayoutData(gridData);
applyDialogFont(composite);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#okPressed()
*/
@Override
protected void okPressed() {
imageName = imageNameText.getText();
bucketName = bucketNameText.getText();
super.okPressed();
}
/*
* Private Interface
*/
private void updateOkButton() {
boolean b = true;
if (bucketNameText == null || bucketNameText.getText().length() == 0 || imageNameText == null || imageNameText.getText().length() == 0) {
b = false;
}
Button okButton = getButton(OK);
if (okButton == null) {
return;
}
okButton.setEnabled(b);
}
}
| 7,242 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/RebootInstancesAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.explorer.AwsAction;
final class RebootInstancesAction extends AwsAction {
private final InstanceSelectionTable instanceSelectionTable;
RebootInstancesAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_REBOOT_ACTION);
this.instanceSelectionTable = instanceSelectionTable;
}
@Override
public void doRun() {
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK | SWT.CANCEL);
messageBox.setText("Reboot selected instances?");
messageBox.setMessage("If you continue, you won't be able to access these instances " +
"until they finish rebooting.");
// Bail out if the user cancels...
if (messageBox.open() == SWT.CANCEL) {
actionCanceled();
} else {
new RebootInstancesThread(instanceSelectionTable, instanceSelectionTable.getAllSelectedInstances()).start();
actionSucceeded();
}
actionFinished();
}
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("reboot");
}
@Override
public String getText() {
return "Reboot";
}
@Override
public String getToolTipText() {
return "Reboot instances";
}
}
| 7,243 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/StartInstancesAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
/**
* Action to start a stopped EBS-backed instance.
*/
public class StartInstancesAction extends AwsAction {
private final InstanceSelectionTable instanceSelectionTable;
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new action which, when run, will start the instances given
*
* @param instance
* The instances to start.
* @param volume
* The volume to attach.
*/
public StartInstancesAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_START_INSTANCES_ACTION);
this.instanceSelectionTable = instanceSelectionTable;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#isEnabled()
*/
@Override
public boolean isEnabled() {
for ( Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
if ( !instance.getState().getName().equalsIgnoreCase("stopped") )
return false;
}
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void doRun() {
final List<String> instanceIds = new ArrayList<>();
for ( Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
instanceIds.add(instance.getInstanceId());
}
new Thread() {
@Override
public void run() {
try {
StartInstancesRequest request = new StartInstancesRequest().withInstanceIds(instanceIds);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.startInstances(request);
instanceSelectionTable.refreshInstances();
actionSucceeded();
} catch ( Exception e ) {
actionFailed();
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, "Unable to start instances: "
+ e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
} finally {
actionFinished();
}
}
}.start();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Start instances";
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("start");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Start this instance";
}
}
| 7,244 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/RebootInstancesThread.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.RebootInstancesRequest;
/**
* Thread for making a service call to EC2 to reboot a list of instances.
*/
class RebootInstancesThread extends Thread {
private final InstanceSelectionTable instanceSelectionTable;
/** The instances to be rebooted */
private final List<Instance> instances;
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new RebootInstancesThread ready to be started and reboot
* the specified instances.
*
* @param instances
* The instances to reboot.
*/
public RebootInstancesThread(InstanceSelectionTable instanceSelectionTable, final List<Instance> instances) {
this.instanceSelectionTable = instanceSelectionTable;
this.instances = instances;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
List<String> instanceIds = new ArrayList<>();
for (Instance instance : instances) {
instanceIds.add(instance.getInstanceId());
}
RebootInstancesRequest request = new RebootInstancesRequest();
request.setInstanceIds(instanceIds);
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.rebootInstances(request);
this.instanceSelectionTable.refreshInstances();
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to reboot instance: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
}
| 7,245 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/PopulateEbsMenuThread.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.DescribeVolumesRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Volume;
import com.amazonaws.services.ec2.model.VolumeAttachment;
/**
* Thread for making a service call to EC2 to list available EBS volumes and
* add them to the specified menu based on whether they can be detached or
* attached to the specified instance.
*/
class PopulateEbsMenuThread extends Thread {
/** The menu to add items to */
private final MenuManager menu;
/** The instance to acted on by menu items */
private final Instance instance;
/** A shared client factory */
private static AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new thread ready to be started to populate the specified
* menu with actions to attach or detach EBS volumes to the specified
* instance.
*
* @param instance
* The instance to detach or attach EBS volumes to.
* @param menu
* The menu to add menu items to.
* @param instanceSelectionTable TODO
*/
public PopulateEbsMenuThread(final Instance instance, final MenuManager menu) {
this.instance = instance;
this.menu = menu;
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
try {
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
List<Volume> volumes = ec2.describeVolumes(new DescribeVolumesRequest()).getVolumes();
for (Volume volume : volumes) {
String status = volume.getState();
// We don't want to allow users to attach any volumes that aren't
// available or are in different availability zones.
if (!status.equalsIgnoreCase("available")) continue;
if (!volume.getAvailabilityZone().equalsIgnoreCase(instance.getPlacement().getAvailabilityZone())) continue;
menu.add(new AttachVolumeAction(instance, volume));
}
menu.add(new Separator());
for (Volume volume : volumes) {
for (VolumeAttachment attachmentInfo : volume.getAttachments()) {
String instanceId = attachmentInfo.getInstanceId();
if (!instanceId.equals(instance.getInstanceId())) continue;
menu.add(new DetachVolumeAction(volume, instance));
}
}
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to query EBS volumes: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
| 7,246 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/OpenShellDialogAction.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.model.Instance;
public class OpenShellDialogAction extends OpenShellAction {
public OpenShellDialogAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_OPEN_SHELL_ACTION, instanceSelectionTable);
this.setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor("console"));
this.setText("Open Shell As...");
this.setToolTipText("Opens a connection to this host");
}
@Override
public void doRun() {
OpenShellDialog openShellDialog = new OpenShellDialog();
if (openShellDialog.open() < 0) {
actionCanceled();
actionFinished();
return;
}
for (final Instance instance : instanceSelectionTable.getAllSelectedInstances()) {
try {
openInstanceShell(instance, openShellDialog.getUserName());
actionSucceeded();
} catch (Exception e) {
actionFailed();
Ec2Plugin.getDefault().reportException("Unable to open a shell to the selected instance: " + e.getMessage(), e);
} finally {
actionFinished();
}
}
}
}
| 7,247 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/OpenShellDialog.java | /*
* Copyright 2011-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.preferences.PreferenceConstants;
public final class OpenShellDialog extends MessageDialog {
private Text userNameText;
private String userName;
public OpenShellDialog() {
super(Display.getDefault().getActiveShell(),
"SSH Connection Options", null,
"Configure the SSH connection to your Amazon EC2 instance with the options below.",
MessageDialog.INFORMATION,
new String[] {"Connect"}, 0);
}
@Override
protected Control createCustomArea(Composite parent) {
parent.setLayout(new FillLayout());
Composite control = new Composite(parent, SWT.NONE);
control.setLayout(new GridLayout(2, false));
new Label(control, SWT.NONE).setText("User Name: ");
userNameText = new Text(control, SWT.BORDER);
userNameText.setText(Ec2Plugin.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SSH_USER));
userNameText.setSelection(0, userNameText.getText().length());
userNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
userNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
userName = userNameText.getText();
getButton(0).setEnabled(userName.length() > 0);
}
});
return control;
}
public String getUserName() {
return userName;
}
}
| 7,248 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/CreateAmiAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.eclipse.ec2.ui.SetupAwsAccountAction;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.model.Instance;
final class CreateAmiAction extends AwsAction {
private final InstanceSelectionTable instanceSelectionTable;
public CreateAmiAction(InstanceSelectionTable instanceSelectionTable) {
super(AwsToolkitMetricType.EXPLORER_EC2_CREATE_AMI_ACTION);
this.instanceSelectionTable = instanceSelectionTable;
}
@Override
public void doRun() {
for ( Instance instance : instanceSelectionTable.getAllSelectedInstances() ) {
createAmiFromInstance(instance);
actionFinished();
}
}
private void createAmiFromInstance(Instance instance) {
boolean userIdIsValid = (InstanceSelectionTable.accountInfo.getUserId() != null);
if ( !InstanceSelectionTable.accountInfo.isValid() || !InstanceSelectionTable.accountInfo.isCertificateValid()
|| !userIdIsValid ) {
String message = "Your AWS account information doesn't appear to be fully configured yet. "
+ "To bundle an instance you'll need all the information configured, "
+ "including your AWS account ID, EC2 certificate and private key file."
+ "\n\nWould you like to configure it now?";
if ( MessageDialog.openQuestion(Display.getCurrent().getActiveShell(), "Configure AWS Account Information",
message) ) {
new SetupAwsAccountAction().run();
}
return;
}
KeyPairManager keyPairManager = new KeyPairManager();
String keyName = instance.getKeyName();
String keyPairFilePath = keyPairManager.lookupKeyPairPrivateKeyFile(AwsToolkitCore.getDefault().getCurrentAccountId(), keyName);
if ( keyPairFilePath == null ) {
String message = "There is no private key registered for the key this host was launched with (" + keyName
+ ").";
MessageDialog.openError(Display.getCurrent().getActiveShell(), "No Registered Private Key", message);
return;
}
BundleDialog bundleDialog = new BundleDialog(Display.getCurrent().getActiveShell());
if ( bundleDialog.open() != IDialogConstants.OK_ID )
return;
String bundleName = bundleDialog.getImageName();
String s3Bucket = bundleDialog.getS3Bucket();
BundleJob job = new BundleJob(instance, s3Bucket, bundleName);
job.schedule();
}
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("bundle");
}
@Override
public String getText() {
return "Bundle AMI...";
}
@Override
public String getToolTipText() {
return "Create a new Amazon Machine Image from this instance";
}
}
| 7,249 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/InstanceComparator.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.List;
import org.eclipse.jface.viewers.Viewer;
import com.amazonaws.eclipse.ec2.TagFormatter;
import com.amazonaws.eclipse.ec2.ui.SelectionTableComparator;
import com.amazonaws.services.ec2.model.Instance;
/**
* Comparator for sorting the instances by any column.
*/
class InstanceComparator extends SelectionTableComparator {
/**
*
*/
private final InstanceSelectionTable instanceSelectionTable;
/**
* @param defaultColumn
* @param instanceSelectionTable TODO
*/
public InstanceComparator(InstanceSelectionTable instanceSelectionTable, int defaultColumn) {
super(defaultColumn);
this.instanceSelectionTable = instanceSelectionTable;
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.views.instances.SelectionTableComparator#compareIgnoringDirection(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
@Override
protected int compareIgnoringDirection(Viewer viewer, Object e1, Object e2) {
if (!(e1 instanceof Instance && e2 instanceof Instance)) {
return 0;
}
Instance i1 = (Instance)e1;
Instance i2 = (Instance)e2;
switch (this.sortColumn) {
case ViewContentAndLabelProvider.INSTANCE_ID_COLUMN:
return (i1.getInstanceId().compareTo(i2.getInstanceId()));
case ViewContentAndLabelProvider.PUBLIC_DNS_COLUMN:
return (i1.getPublicDnsName().compareTo(i2.getPublicDnsName()));
case ViewContentAndLabelProvider.ROOT_DEVICE_COLUMN:
return (i1.getRootDeviceType().compareTo(i2.getRootDeviceType()));
case ViewContentAndLabelProvider.STATE_COLUMN:
return (i1.getState().getName().compareTo(i2.getState().getName()));
case ViewContentAndLabelProvider.INSTANCE_TYPE_COLUMN:
return (i1.getInstanceType().compareTo(i2.getInstanceType()));
case ViewContentAndLabelProvider.AVAILABILITY_ZONE_COLUMN:
return (i1.getPlacement().getAvailabilityZone().compareTo(i2.getPlacement().getAvailabilityZone()));
case ViewContentAndLabelProvider.IMAGE_ID_COLUMN:
return (i1.getImageId().compareTo(i2.getImageId()));
case ViewContentAndLabelProvider.KEY_NAME_COLUMN:
String k1 = i1.getKeyName();
String k2 = i2.getKeyName();
if (k1 == null)
k1 = "";
if (k2 == null)
k2 = "";
return k1.compareTo(k2);
case ViewContentAndLabelProvider.LAUNCH_TIME_COLUMN:
return (i1.getLaunchTime().compareTo(i2.getLaunchTime()));
case ViewContentAndLabelProvider.SECURITY_GROUPS_COLUMN:
return compareSecurityGroups(i1, i2);
case ViewContentAndLabelProvider.TAGS_COLUMN:
return TagFormatter.formatTags(i1.getTags()).compareTo(
TagFormatter.formatTags(i2.getTags()));
default:
return 0;
}
}
/**
* Compares the security groups for the specified instances and returns
* a -1, 0, or 1 depending on the comparison. See compareTo() for more
* details on the returned value.
*
* @param i1
* The first instance to compare.
* @param i2
* The second instance to compare.
*
* @return -1, 0, or 1 depending on the comparison of the security
* groups in the specified instances.
*/
private int compareSecurityGroups(Instance i1, Instance i2) {
List<String> groups1 = this.instanceSelectionTable.contentAndLabelProvider.getSecurityGroupsForInstance(i1.getInstanceId());
List<String> groups2 = this.instanceSelectionTable.contentAndLabelProvider.getSecurityGroupsForInstance(i2.getInstanceId());
String formattedList1 = formatSecurityGroups(groups1);
String formattedList2 = formatSecurityGroups(groups2);
return formattedList1.compareTo(formattedList2);
}
/**
* Formats a list of security groups as a string for easy comparison.
* It's assumed that the list of security groups is already sorted.
*
* @param securityGroupList
* The list to format as a single string.
*
* @return A single string containing the specified list of security
* groups.
*/
private String formatSecurityGroups(List<String> securityGroupList) {
if (securityGroupList == null) return "";
String formattedList = "";
for (String group : securityGroupList) {
if (formattedList.length() > 0) {
formattedList += ", ";
}
formattedList += group;
}
return formattedList;
}
}
| 7,250 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/AttachVolumeAction.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AttachVolumeRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Volume;
/**
* Action subclass which, when run, will attach a specified volume to a
* specified instance.
*/
class AttachVolumeAction extends Action {
/** The volume being attached to an instance */
private final Volume volume;
/** The instance to which a volume is being attached */
private final Instance instance;
/** A shared client factory */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* Creates a new action which, when run, will attach the specified volume to
* the specified instance.
*
* @param instance
* The instance to attach the volume to.
* @param volume
* The volume to attach.
*/
public AttachVolumeAction(Instance instance, Volume volume) {
this.instance = instance;
this.volume = volume;
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#isEnabled()
*/
@Override
public boolean isEnabled() {
if (!volume.getState().equalsIgnoreCase("available")) return false;
if (!instance.getState().getName().equalsIgnoreCase("running")) return false;
String volumeZone = volume.getAvailabilityZone();
String instanceZone = instance.getPlacement().getAvailabilityZone();
if (!volumeZone.equalsIgnoreCase(instanceZone)) return false;
return super.isEnabled();
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
DeviceDialog deviceDialog = new DeviceDialog();
if (deviceDialog.open() == DeviceDialog.CANCEL) {
return;
}
try {
AttachVolumeRequest request = new AttachVolumeRequest();
request.setDevice(deviceDialog.getDevice());
request.setInstanceId(instance.getInstanceId());
request.setVolumeId(volume.getVolumeId());
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
ec2.attachVolume(request);
} catch (Exception e) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to attach volume: " + e.getMessage());
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getText()
*/
@Override
public String getText() {
return "Attach " + volume.getVolumeId() + " (" + volume.getSize() + " GB) ...";
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getImageDescriptor()
*/
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("volume");
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#getToolTipText()
*/
@Override
public String getToolTipText() {
return "Attach an Elastic Block Storage volume to this instance";
}
}
| 7,251 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/views/instances/InstanceSelectionTable.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.views.instances;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.InstanceType;
import com.amazonaws.eclipse.ec2.InstanceTypes;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.eclipse.ec2.ui.SelectionTable;
import com.amazonaws.eclipse.ec2.ui.ebs.CreateNewVolumeDialog;
import com.amazonaws.eclipse.ec2.utils.DynamicMenuAction;
import com.amazonaws.eclipse.ec2.utils.IMenu;
import com.amazonaws.eclipse.ec2.utils.MenuAction;
import com.amazonaws.eclipse.ec2.utils.MenuHandler;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
/**
* Table displaying EC2 instances and a context menu with actions like opening
* remote shells, terminating instances, rebooting instances, attaching EBS
* volumes, etc.
*/
public class InstanceSelectionTable extends SelectionTable implements IRefreshable, IMenu {
/* Menu Actions */
private Action refreshAction;
private Action rebootAction;
private Action terminateAction;
private Action openShellAction;
private Action openShellDialogAction;
private Action createAmiAction;
private Action copyPublicDnsNameAction;
private Action attachNewVolumeAction;
private Action startInstancesAction;
private Action stopInstancesAction;
/** Dropdown filter menu for Instance State */
private IAction instanceStateFilterDropDownAction;
/** DropDown menu handler for Instance State */
private MenuHandler instanceStateDropDownMenuHandler;
/** Dropdown filter menu for Security Group*/
private IAction securityGroupFilterDropDownAction;
/** DropDown menu handler for Security Group */
private MenuHandler securityGroupDropDownMenuHandler;
/** Holds the ALL option for Security Group Filter Item */
private MenuItem allSecurityGroupFilterItem;
/** The timer we use to have this table automatically refreshed */
private RefreshTimer refreshInstanceListTimer;
/** Shared account info */
final static AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
/** Content and label provider for this selection table */
ViewContentAndLabelProvider contentAndLabelProvider;
private KeyPairManager keyPairManager = new KeyPairManager();
/**
* An optional field containing a list of Amazon EC2 instances to display in
* this selection table
*/
private List<String> instancesToDisplay;
/** Stores the no of instances that are displayed */
private int noOfInstances;
/*
* Public Interface
*/
/**
* Creates a new instance selection table within the specified composite.
*
* @param parent
* The parent composite for this new instance selection table.
*/
public InstanceSelectionTable(Composite parent) {
super(parent, true, false);
contentAndLabelProvider = new ViewContentAndLabelProvider();
viewer.setContentProvider(contentAndLabelProvider);
viewer.setLabelProvider(contentAndLabelProvider);
setComparator(new InstanceComparator(this, ViewContentAndLabelProvider.LAUNCH_TIME_COLUMN));
refreshInstanceListTimer = new RefreshTimer(this);
refreshInstanceListTimer.startTimer();
}
/**
* Creates a new instance selection table within the specified composite,
* displaying only the Amazon EC2 instance IDs specified.
*
* @param parent
* The parent composite for this new instance selection table.
* @param instancesToDisplay
* A list of Amazon EC2 instance IDs to limit this selection
* table to showing.
*/
public InstanceSelectionTable(Composite parent, List<String> instancesToDisplay) {
this(parent);
setInstancesToList(instancesToDisplay);
}
/**
* Sets the period, in milliseconds, between automatic refreshes of the data
* displayed in this instance selection table.
*
* @param refreshPeriodInMilliseconds
* The period, in milliseconds, between automatic refreshes of
* the data displayed in this table.
*/
public void setRefreshPeriod(int refreshPeriodInMilliseconds) {
refreshInstanceListTimer.setRefreshPeriod(refreshPeriodInMilliseconds);
}
/**
* Refreshes the list of a user's current instances.
*/
public void refreshInstances() {
new RefreshInstancesThread().start();
}
/**
* Returns the Action object that refreshes this selection table.
*
* @return The IAction object that refreshes this selection table.
*/
public Action getRefreshAction() {
return refreshAction;
}
/**
* Returns the Action object that shows the Instance State filter dropdown menus
*
* @return The IAction object that shows the Instance State filter dropdown menus
*/
public IAction getInstanceStateFilterDropDownAction() {
return instanceStateFilterDropDownAction;
}
/**
* Returns the Action object that shows the Security Group filter dropdown menus
*
* @return The Action object that shows the Security Group filter dropdown menus
*/
public IAction getSecurityGroupFilterAction() {
return securityGroupFilterDropDownAction;
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
refreshInstanceListTimer.stopTimer();
super.dispose();
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.IRefreshable#refreshData()
*/
@Override
public void refreshData() {
refreshInstances();
}
/**
* Sets the Amazon EC2 instances which should be displayed in this selection
* table. Specifying an empty list or a null list will both result in
* displaying no instances in this list. The selection table will be
* refreshed by this method so that the specified instances are being
* displayed.
*
* @param serviceInstances
* A list of Amazon EC2 instance IDs to display in this selection
* table.
*/
public void setInstancesToList(List<String> serviceInstances) {
if (serviceInstances == null) {
serviceInstances = new ArrayList<>();
}
this.instancesToDisplay = serviceInstances;
this.refreshInstances();
}
/*
* SelectionTable Interface
*/
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#createColumns()
*/
@Override
protected void createColumns() {
newColumn("Instance ID", 10);
newColumn("Instance Name", 10);
newColumn("Public DNS Name", 15);
newColumn("Image ID", 10);
newColumn("Root Device Type", 10);
newColumn("State", 10);
newColumn("Type", 10);
newColumn("Availability Zone", 10);
newColumn("Key Pair", 10);
newColumn("Launch Time", 15);
newColumn("Security Groups", 15);
newColumn("Tags", 15);
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
@Override
protected void fillContextMenu(IMenuManager manager) {
manager.add(refreshAction);
manager.add(new Separator());
manager.add(rebootAction);
manager.add(terminateAction);
manager.add(startInstancesAction);
manager.add(stopInstancesAction);
manager.add(new Separator());
manager.add(openShellAction);
manager.add(openShellDialogAction);
manager.add(new Separator());
manager.add(createAmiAction);
manager.add(new Separator());
manager.add(copyPublicDnsNameAction);
final boolean isRunningInstanceSelected = isRunningInstanceSelected();
final boolean exactlyOneInstanceSelected =
isRunningInstanceSelected && (getAllSelectedInstances().size() == 1);
if (exactlyOneInstanceSelected) {
manager.add(new Separator());
manager.add(createEbsMenu());
}
rebootAction.setEnabled(isRunningInstanceSelected);
terminateAction.setEnabled(isRunningInstanceSelected);
boolean instanceLaunchedWithKey = getSelectedInstance().getKeyName() != null;
boolean knownPrivateKey = keyPairManager.isKeyPairValid(AwsToolkitCore.getDefault().getCurrentAccountId(), getSelectedInstance().getKeyName());
boolean canOpenShell = isRunningInstanceSelected && instanceLaunchedWithKey && knownPrivateKey;
openShellAction.setEnabled(canOpenShell);
openShellDialogAction.setEnabled(canOpenShell);
copyPublicDnsNameAction.setEnabled(exactlyOneInstanceSelected);
createAmiAction.setEnabled(exactlyOneInstanceSelected && instanceLaunchedWithKey);
// These calls seem like a no-op, but it basically forces a refresh of the enablement state
startInstancesAction.setEnabled(startInstancesAction.isEnabled());
stopInstancesAction.setEnabled(stopInstancesAction.isEnabled());
}
/* (non-Javadoc)
* @see com.amazonaws.eclipse.ec2.ui.SelectionTable#makeActions()
*/
@Override
protected void makeActions() {
refreshAction = new Action("Refresh", Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh")) {
@Override
public void run() {
refreshInstances();
}
@Override
public String getToolTipText() {
return "Refresh instances";
}
};
rebootAction = new RebootInstancesAction(this);
terminateAction = new TerminateInstancesAction(this);
openShellAction = new OpenShellAction(this);
openShellDialogAction = new OpenShellDialogAction(this);
createAmiAction = new CreateAmiAction(this);
copyPublicDnsNameAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_EC2_COPY_PUBLIC_DNS_NAME_ACTION,
"Copy Public DNS Name",
Ec2Plugin.getDefault().getImageRegistry().getDescriptor("clipboard")) {
@Override
public void doRun() {
copyPublicDnsNameToClipboard(getSelectedInstance());
actionFinished();
}
@Override
public String getToolTipText() {
return "Copies this instance's public DNS name to the clipboard.";
}
};
attachNewVolumeAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_EC2_ATTACH_NEW_VOLUME_ACTION,
"Attach New Volume...") {
@Override
public void doRun() {
Instance instance = getSelectedInstance();
CreateNewVolumeDialog dialog = new CreateNewVolumeDialog(Display.getCurrent().getActiveShell(), instance);
if (dialog.open() != IDialogConstants.OK_ID) {
actionCanceled();
} else {
new AttachNewVolumeThread(instance, dialog.getSize(), dialog.getSnapshotId(), dialog.getDevice()).start();
actionSucceeded();
}
actionFinished();
}
@Override
public String getToolTipText() {
return "Attaches a new Elastic Block Storage volume to this instance.";
}
};
startInstancesAction = new StartInstancesAction(this);
stopInstancesAction = new StopInstancesAction(this);
instanceStateDropDownMenuHandler = new MenuHandler();
instanceStateDropDownMenuHandler.addListener(this);
instanceStateDropDownMenuHandler.add("ALL", "All Instances", true);
for (InstanceType instanceType : InstanceTypes.getInstanceTypes()) {
instanceStateDropDownMenuHandler.add(instanceType.id, instanceType.name + " Instances");
}
instanceStateDropDownMenuHandler.add("windows", "Windows Instances");
instanceStateFilterDropDownAction = new MenuAction("Status Filter", "Filter by instance state", "filter", instanceStateDropDownMenuHandler);
securityGroupDropDownMenuHandler = new MenuHandler();
securityGroupDropDownMenuHandler.addListener(this);
allSecurityGroupFilterItem = securityGroupDropDownMenuHandler.add("ALL", "All Security Groups", true);
securityGroupFilterDropDownAction = new DynamicMenuAction("Security Groups Filter", "Filter by security group", "filter", securityGroupDropDownMenuHandler);
}
/*
* Private Interface
*/
protected void copyPublicDnsNameToClipboard(Instance instance) {
Clipboard clipboard = new Clipboard(Display.getCurrent());
String textData = instance.getPublicDnsName();
TextTransfer textTransfer = TextTransfer.getInstance();
Transfer[] transfers = new Transfer[]{textTransfer};
Object[] data = new Object[]{textData};
clipboard.setContents(data, transfers);
clipboard.dispose();
}
/**
* Returns true if and only if at least one instance is selected and all of
* the selected instances are in a running state.
*
* @return True if and only if at least one instance is selected and all of
* the selected instances are in a running state, otherwise returns
* false.
*/
private boolean isRunningInstanceSelected() {
boolean instanceSelected = viewer.getTree().getSelectionCount() > 0;
if (!instanceSelected) {
return false;
}
for (TreeItem data : viewer.getTree().getSelection()) {
Instance instance = (Instance)data.getData();
if (!instance.getState().getName().equalsIgnoreCase("running")) {
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
List<Instance> getAllSelectedInstances() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
return selection.toList();
}
private Instance getSelectedInstance() {
StructuredSelection selection = (StructuredSelection)viewer.getSelection();
return (Instance)selection.getFirstElement();
}
private IMenuManager createEbsMenu() {
final MenuManager subMenu = new MenuManager("Elastic Block Storage");
subMenu.add(attachNewVolumeAction);
subMenu.add(new Separator());
final Instance instance = getSelectedInstance();
new PopulateEbsMenuThread(instance, subMenu).start();
return subMenu;
}
/**
* Sets the list of instances to be displayed in the instance table.
*
* @param instances
* The list of instances to be displayed in the instance table.
* @param securityGroupMap
* A map of instance IDs to a list of security groups in which
* those instances were launched.
*/
private void setInput(final List<Instance> instances, final Map<String, List<String>> securityGroupMap) {
Display.getDefault().asyncExec(new Runnable() {
@Override
@SuppressWarnings("unchecked")
public void run() {
/*
* Sometimes we see cases where the content provider for a table
* viewer is null, so we check for that here to avoid causing an
* unhandled event loop exception. All InstanceSelectionTables
* should always have a content provider set in the constructor,
* but for some reason we occasionally still see this happen.
*/
if (viewer.getContentProvider() == null) {
return;
}
StructuredSelection currentSelection = (StructuredSelection) viewer.getSelection();
viewer.setInput(new InstancesViewInput(instances, securityGroupMap));
packColumns();
Set<String> instanceIds = new HashSet<>();
for (Instance instance : (List<Instance>) currentSelection.toList()) {
instanceIds.add(instance.getInstanceId());
}
List<Instance> newSelectedInstances = new ArrayList<>();
for (TreeItem treeItem : viewer.getTree().getItems()) {
Instance instance = (Instance) treeItem.getData();
if (instanceIds.contains(instance.getInstanceId())) {
newSelectedInstances.add(instance);
}
}
viewer.setSelection(new StructuredSelection(newSelectedInstances));
}
});
}
/*
* Private Classes
*/
/**
* Thread for making a service call to EC2 to list current instances.
*/
private class RefreshInstancesThread extends Thread {
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
@Override
public void run() {
synchronized (RefreshInstancesThread.class) {
if (selectionTableListener != null) {
selectionTableListener.loadingData();
enableDropDowns(false);
}
List<Reservation> reservations = null;
try {
boolean needsToDescribeInstances = true;
DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
if (instancesToDisplay != null) {
/*
* If the caller explicitly asked for a list of zero
* instances to be displayed, don't even bother querying for
* anything.
*/
if (instancesToDisplay.size() == 0) {
needsToDescribeInstances = false;
};
describeInstancesRequest.setInstanceIds(instancesToDisplay);
}
final List<Instance> allInstances = new ArrayList<>();
final Map<String, List<String>> securityGroupsByInstanceId = new HashMap<>();
if (needsToDescribeInstances) {
DescribeInstancesResult response = getAwsEc2Client().describeInstances(describeInstancesRequest);
reservations = response.getReservations();
noOfInstances = -1; //Reset the value
Set<String> allSecurityGroups = new TreeSet<>();
for (Reservation reservation : reservations) {
List<Instance> instances = reservation.getInstances();
List<String> groupNames = reservation.getGroupNames();
Collections.sort(groupNames);
allSecurityGroups.addAll(groupNames);
//Filter Security Groups
if (securityGroupDropDownMenuHandler.getCurrentSelection().getMenuId().equals("ALL") || groupNames.contains(securityGroupDropDownMenuHandler.getCurrentSelection().getMenuId())) {
for (Instance instance : instances) {
//Filter Instances
if (!instanceStateDropDownMenuHandler.getCurrentSelection().getMenuId().equals("ALL")) {
if (instanceStateDropDownMenuHandler.getCurrentSelection().getMenuId().equalsIgnoreCase("windows")) {
if (instance.getPlatform() == null || !instance.getPlatform().equals("windows"))
continue;
} else if (!instance.getInstanceType().equalsIgnoreCase(instanceStateDropDownMenuHandler.getCurrentSelection().getMenuId())) {
continue;
}
}
allInstances.add(instance);
// Populate the map of instance IDs -> security groups
securityGroupsByInstanceId.put(instance.getInstanceId(), groupNames);
}
}
}
//Populate all Security Groups dynamically
securityGroupDropDownMenuHandler.clear();
securityGroupDropDownMenuHandler.add(allSecurityGroupFilterItem);
for(String securityGroup : allSecurityGroups) {
securityGroupDropDownMenuHandler.add(new MenuItem(securityGroup, securityGroup));
}
}
noOfInstances = allInstances.size();
setInput(allInstances, securityGroupsByInstanceId);
} catch (Exception e) {
// Only log an error if the account info is valid and we
// actually expected this call to work
if (AwsToolkitCore.getDefault().getAccountInfo().isValid()) {
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to list instances: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
} finally {
if (selectionTableListener != null) {
selectionTableListener.finishedLoadingData(noOfInstances);
enableDropDowns(true);
}
}
}
}
}
/**
* Callback function. Is called from the DropdownMenuHandler when a menu option is clicked
*
* @param itemSelected The selected MenuItem
*
* @see com.amazonaws.eclipse.ec2.utils.IMenu#menuClicked(com.amazonaws.eclipse.ec2.utils.IMenu.MenuItem)
*/
@Override
public void menuClicked(MenuItem menuItemSelected) {
refreshData();
}
/**
* Enables/Disables dropdown filters
*
* @param checked A TRUE value will imply the dropdown filter is enabled; FALSE value will make it disabled
*/
private void enableDropDowns(boolean checked) {
instanceStateFilterDropDownAction.setEnabled(checked);
securityGroupFilterDropDownAction.setEnabled(checked);
}
}
| 7,252 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/launchwizard/LaunchWizardPage.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.launchwizard;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.InstanceType;
import com.amazonaws.eclipse.ec2.InstanceTypes;
import com.amazonaws.eclipse.ec2.ui.ChargeWarningComposite;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairComposite;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairSelectionTable;
import com.amazonaws.eclipse.ec2.ui.securitygroups.SecurityGroupSelectionComposite;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AvailabilityZone;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.services.identitymanagement.model.InstanceProfile;
import com.amazonaws.services.identitymanagement.model.ListInstanceProfilesResult;
/**
* Wizard Page for launching EC2 instances.
*/
public class LaunchWizardPage extends WizardPage {
private static final String NO_INSTANCE_PROFILE = "None";
private Combo availabilityZoneCombo;
private Combo instanceTypeCombo;
private Label instanceTypeArchitectureLabel;
private Label instanceTypeVirtualCoresLabel;
private Label instanceTypeDiskCapacityLabel;
private Label instanceTypeMemoryLabel;
private Combo instanceProfileCombo;
private Text userDataText;
private KeyPairComposite keyPairComposite;
private SecurityGroupSelectionComposite securityGroupSelectionComposite;
private Spinner numberOfHostsSpinner;
/** The Image being launched */
private Image image;
/** Label displaying the name of the AMI being launched */
private Label amiLabel;
/**
* Creates a new LaunchWizardPage, configured to launch the specified Image.
*
* @param image
* The Image being launched by this LaunchWizardPage.
*/
protected LaunchWizardPage(Image image) {
super("Launch", "Launch Amazon EC2 Instances", null);
this.image = image;
this.setDescription("Configure the options for launching your Amazon EC2 instances");
}
/**
* Loads the controls (key pair selection table, availability zones,
* image details) once this page is displayed.
*
* @see org.eclipse.jface.dialogs.DialogPage#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
if (visible) {
LaunchWizard launchWizard = (LaunchWizard)this.getWizard();
image = launchWizard.getImageToLaunch();
if (image != null) {
amiLabel.setText(image.getImageId() + " (" + image.getArchitecture() + ")");
populateValidInstanceTypes();
}
securityGroupSelectionComposite.getRefreshSecurityGroupsAction().run();
keyPairComposite.getKeyPairSelectionTable().refreshKeyPairs();
loadAvailabilityZones();
try {
loadInstanceProfiles();
} catch ( Exception e ) {
instanceProfileCombo.select(0);
AwsToolkitCore.getDefault().logError("Couldn't load IAM Instance Profiles", e);
}
}
super.setVisible(visible);
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createControl(Composite originalParent) {
Composite parent = new Composite(originalParent, SWT.NONE);
GridLayout parentLayout = new GridLayout(2, false);
parent.setLayout(parentLayout);
newLabel(parent, "AMI:");
amiLabel = newLabel(parent, "N/A");
amiLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
newLabel(parent, "Number of Hosts:");
numberOfHostsSpinner = new Spinner(parent, SWT.BORDER);
numberOfHostsSpinner.setSelection(1);
numberOfHostsSpinner.setMaximum(20);
numberOfHostsSpinner.setMinimum(1);
numberOfHostsSpinner.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
newLabel(parent, "Instance Type:");
instanceTypeCombo = new Combo(parent, SWT.READ_ONLY);
instanceTypeCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
instanceTypeCombo.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateInstanceTypeInformation();
}
});
populateValidInstanceTypes();
new Label(parent, SWT.NONE);
createInstanceTypeDetailsComposite(parent);
// Create the availability zone combo; zones are loaded when the page
// becomes visible
newLabel(parent, "Availability Zone:");
availabilityZoneCombo = new Combo(parent, SWT.READ_ONLY);
availabilityZoneCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
SelectionListener selectionListener = new SelectionListener() {
@Override
public void widgetDefaultSelected(SelectionEvent e) {}
@Override
public void widgetSelected(SelectionEvent e) {
updateControls();
}
};
newLabel(parent, "Key Pair:");
keyPairComposite = new KeyPairComposite(parent);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = 100;
keyPairComposite.setLayoutData(gridData);
keyPairComposite.getViewer().addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
updateControls();
}
});
newLabel(parent, "Security Group:");
securityGroupSelectionComposite = new SecurityGroupSelectionComposite(parent);
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = 100;
securityGroupSelectionComposite.setLayoutData(gridData);
securityGroupSelectionComposite.addSelectionListener(selectionListener);
newLabel(parent, "Instance Profile:");
instanceProfileCombo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
instanceProfileCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
instanceProfileCombo.setItems(new String[] { NO_INSTANCE_PROFILE });
instanceProfileCombo.select(0);
newLabel(parent, "User Data:");
userDataText = new Text(parent, SWT.MULTI | SWT.BORDER);
userDataText.setLayoutData(new GridData(GridData.FILL_BOTH));
gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = 85;
userDataText.setLayoutData(gridData);
userDataText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
updateControls();
}
});
ChargeWarningComposite chargeWarningComposite = new ChargeWarningComposite(parent, SWT.NONE);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
data.widthHint = 150;
chargeWarningComposite.setLayoutData(data);
updateControls();
this.setControl(parent);
}
/**
* Loads the EC2 availability zones for the current region and displays them
* in the combo box.
*/
private void loadAvailabilityZones() {
try {
availabilityZoneCombo.removeAll();
AmazonEC2 ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
DescribeAvailabilityZonesResult response = ec2.describeAvailabilityZones();
for ( AvailabilityZone zone : response.getAvailabilityZones() ) {
availabilityZoneCombo.add(zone.getZoneName());
availabilityZoneCombo.select(0);
}
} catch ( Exception e ) {
Status status = new Status(Status.WARNING, Ec2Plugin.PLUGIN_ID, "Unable to query EC2 availability zones: "
+ e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
private void loadInstanceProfiles() {
ListInstanceProfilesResult listInstanceProfiles = AwsToolkitCore.getClientFactory()
.getIAMClient().listInstanceProfiles();
List<String> profileNames = new ArrayList<>();
profileNames.add(NO_INSTANCE_PROFILE);
for ( InstanceProfile profile : listInstanceProfiles.getInstanceProfiles() ) {
profileNames.add(profile.getInstanceProfileName());
instanceProfileCombo.setData(profile.getInstanceProfileName(), profile);
}
instanceProfileCombo.setItems(profileNames.toArray(new String[profileNames.size()]));
instanceProfileCombo.select(0);
}
/**
* Updates the EC2 instance type combo box so that only the instance types
* that are appropriate for the selected Amazon Machine Image being launched
* (i.e. the instnace type architecture matches the AMI architecture - 32bit
* vs. 64bit).
*/
private void populateValidInstanceTypes() {
instanceTypeCombo.removeAll();
for (InstanceType instanceType : InstanceTypes.getInstanceTypes()) {
// Only display instance types that will work with the selected AMI
if ( !instanceType.canLaunch(image) )
continue;
instanceTypeCombo.add(instanceType.name);
instanceTypeCombo.setData(instanceType.name, instanceType);
instanceTypeCombo.select(0);
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.DialogPage#performHelp()
*/
@Override
public void performHelp() {
PlatformUI.getWorkbench().getHelpSystem().displayHelp(
"com.amazonaws.eclipse.ec2.launchWizardHelp");
}
private void updateControls() {
setErrorMessage(null);
if (keyPairComposite.getKeyPairSelectionTable().isValidKeyPairSelected() == false) {
// If an invalid key is selected (as opposed to no key selected)
// we want to display an error message.
if (keyPairComposite.getKeyPairSelectionTable().getSelectedKeyPair() != null) {
setErrorMessage(KeyPairSelectionTable.INVALID_KEYPAIR_MESSAGE);
}
setPageComplete(false);
return;
}
if (securityGroupSelectionComposite.getSelectedSecurityGroup() == null) {
setPageComplete(false);
return;
}
setErrorMessage(null);
setPageComplete(true);
}
private Label newLabel(Composite parent, String text) {
Label label;
label = new Label(parent, SWT.NONE);
label.setText(text);
GridData gridData = new GridData(GridData.VERTICAL_ALIGN_BEGINNING);
gridData.verticalIndent = 4;
label.setLayoutData(gridData);
return label;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
@Override
public void dispose() {
super.dispose();
keyPairComposite.dispose();
}
private void createInstanceTypeDetailsComposite(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(4, true));
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Label label = new Label(composite, SWT.NONE);
label.setText("Memory:");
instanceTypeMemoryLabel = new Label(composite, SWT.NONE);
instanceTypeMemoryLabel.setLayoutData(new GridData(GridData.FILL_BOTH));
label = new Label(composite, SWT.NONE);
label.setText("Virtual Cores:");
instanceTypeVirtualCoresLabel = new Label(composite, SWT.NONE);
instanceTypeVirtualCoresLabel.setLayoutData(new GridData(GridData.FILL_BOTH));
label = new Label(composite, SWT.NONE);
label.setText("Disk Capacity:");
instanceTypeDiskCapacityLabel = new Label(composite, SWT.NONE);
instanceTypeDiskCapacityLabel.setLayoutData(new GridData(GridData.FILL_BOTH));
label = new Label(composite, SWT.NONE);
label.setText("Architecture:");
instanceTypeArchitectureLabel = new Label(composite, SWT.NONE);
instanceTypeArchitectureLabel.setLayoutData(new GridData(GridData.FILL_BOTH));
updateInstanceTypeInformation();
}
private void updateInstanceTypeInformation() {
// Bail out early if this method has been called before
// all the widgets have been initialized
if ( instanceTypeCombo == null
|| instanceTypeArchitectureLabel == null
|| instanceTypeDiskCapacityLabel == null
|| instanceTypeMemoryLabel == null
|| instanceTypeVirtualCoresLabel == null) return;
String s = instanceTypeCombo.getText();
InstanceType instanceType = (InstanceType)instanceTypeCombo.getData(s);
if (instanceType == null) {
instanceTypeArchitectureLabel.setText("N/A");
instanceTypeDiskCapacityLabel.setText("N/A");
instanceTypeMemoryLabel.setText("N/A");
instanceTypeVirtualCoresLabel.setText("N/A");
} else {
instanceTypeArchitectureLabel.setText(instanceType.architectureBits + " bits");
instanceTypeDiskCapacityLabel.setText(instanceType.diskSpaceWithUnits);
instanceTypeMemoryLabel.setText(instanceType.memoryWithUnits);
instanceTypeVirtualCoresLabel.setText(Integer.toString(instanceType.numberOfVirtualCores));
}
}
/*
* Accessors for user entered data
*/
/**
* Returns the selected availability zone.
*
* @return The selected availability zone.
*/
public String getAvailabilityZone() {
return availabilityZoneCombo.getText();
}
/**
* Returns the selected security group.
*
* @return The selected security group.
*/
public String getSecurityGroup() {
return securityGroupSelectionComposite.getSelectedSecurityGroup().getGroupName();
}
/**
* Returns the String ID of the selected instance type.
*
* @return The String ID of the selected instance type.
*/
public String getInstanceTypeId() {
String s = instanceTypeCombo.getText();
InstanceType instanceType = (InstanceType)instanceTypeCombo.getData(s);
return instanceType.id;
}
/**
* Returns the selected key pair name.
*
* @return The selected key pair name.
*/
public String getKeyPairName() {
return keyPairComposite.getKeyPairSelectionTable().getSelectedKeyPair().getKeyName();
}
/**
* Returns the arn of the selected instance profile, or null if none is
* selected.
*/
public String getInstanceProfileArn() {
if ( instanceProfileCombo.getSelectionIndex() == 0 ) {
return null;
} else {
return ((InstanceProfile) instanceProfileCombo.getData(instanceProfileCombo.getText())).getArn();
}
}
/**
* Returns the requested user data to pass to instances.
*
* @return The requested user data to pass to instances.
*/
public String getUserData() {
return userDataText.getText();
}
/**
* Returns the number of instances requested to be launched.
*
* @return The number of instances requested to be launched.
*/
public int getNumberOfInstances() {
return numberOfHostsSpinner.getSelection();
}
}
| 7,253 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/launchwizard/LaunchWizard.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.launchwizard;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.services.ec2.model.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.telemetry.MetricsDataModel;
import com.amazonaws.eclipse.ec2.Ec2InstanceLauncher;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.views.instances.InstanceView;
import com.amazonaws.eclipse.explorer.AwsAction;
/**
* Wizard for launching EC2 instances.
*/
public class LaunchWizard extends Wizard {
/** Wizard page for selecting the AMI to launch */
private AmiSelectionWizardPage amiSelectionWizardPage;
/** Wizard page for selecting launch options */
private LaunchWizardPage launchOptionsWizardPage;
/** The EC2 AMI being launched by this wizard */
private Image image;
/** The source action triggering this Wizard */
private final String actionSource;
/**
* Creates a new launch wizard. Since no AMI has been specified in this
* constructor form, the wizard will include an extra page at the beginning
* to allow the user to select an AMI.
*/
public LaunchWizard() {
this(null, "Default");
}
public LaunchWizard(String actionSource) {
this(null, actionSource);
}
public LaunchWizard(Image image) {
this(image, "Default");
}
/**
* Creates a new launch wizard to launch the specified AMI.
*
* @param image
* The AMI this launch wizard will launch.
*/
public LaunchWizard(Image image, String actionSource) {
this.image = image;
this.actionSource = actionSource;
if (image == null) {
amiSelectionWizardPage = new AmiSelectionWizardPage();
this.addPage(amiSelectionWizardPage);
}
launchOptionsWizardPage = new LaunchWizardPage(image);
this.addPage(launchOptionsWizardPage);
this.setNeedsProgressMonitor(true);
this.setWindowTitle("Launch Amazon EC2 Instances");
/*
* TODO: Grab a better image for the wizard...
*/
this.setDefaultPageImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
}
/**
* Returns the Amazon Machine Image this launch wizard is launching. This
* could be an image the user selected from the AMI browser, or it could be
* an image the user selected within in the launch wizard.
*
* @return The Amazon Machine Image this launch wizard is launching.
*/
public Image getImageToLaunch() {
if (image != null) return image;
return amiSelectionWizardPage.getSelectedAmi();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
/*
* TODO: performFinish executes in the UI thread. It might be nice to
* run this in a separate thread in case of network issues, but it's
* probably not the most critical piece to get out of the UI thread.
*/
String keyPairName = launchOptionsWizardPage.getKeyPairName();
Ec2InstanceLauncher launcher = new Ec2InstanceLauncher(getImageToLaunch().getImageId(), keyPairName);
launcher.setNumberOfInstances(launchOptionsWizardPage.getNumberOfInstances());
launcher.setAvailabilityZone(launchOptionsWizardPage.getAvailabilityZone());
launcher.setInstanceType(launchOptionsWizardPage.getInstanceTypeId());
launcher.setUserData(launchOptionsWizardPage.getUserData());
launcher.setSecurityGroup(launchOptionsWizardPage.getSecurityGroup());
launcher.setInstanceProfileArn(launchOptionsWizardPage.getInstanceProfileArn());
try {
launcher.launch();
activateInstanceView();
publishMetrics(AwsAction.SUCCEEDED);
} catch (Exception e) {
publishMetrics(AwsAction.FAILED);
String message = "Unable to launch instances: " + e.getMessage();
Status status = new Status(IStatus.ERROR, Ec2Plugin.PLUGIN_ID, message, e);
StatusManager.getManager().handle(status, StatusManager.LOG);
MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_ERROR | SWT.OK);
messageBox.setMessage(message);
messageBox.setText("Launch Error");
messageBox.open();
return false;
}
return true;
}
@Override
public boolean performCancel() {
publishMetrics(AwsAction.CANCELED);
return super.performCancel();
}
private void publishMetrics(String endResult) {
MetricsDataModel metricsDataModel = new MetricsDataModel(AwsToolkitMetricType.EC2_LAUNCH_INSTANCES);
metricsDataModel.addAttribute("ActionSource", actionSource);
metricsDataModel.addAttribute(AwsAction.END_RESULT, endResult);
metricsDataModel.publishEvent();
}
private void activateInstanceView() {
try {
IViewPart viewPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.findView("com.amazonaws.eclipse.ec2.ui.views.InstanceView");
if (viewPart != null) {
InstanceView instanceView = (InstanceView)viewPart;
instanceView.refreshData();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().activate(instanceView);
}
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to activate instance view: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
| 7,254 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/ui/launchwizard/AmiSelectionWizardPage.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.ui.launchwizard;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.ec2.ui.amis.FilteredAmiSelectionTable;
import com.amazonaws.services.ec2.model.Image;
/**
* Wizard page for the launch wizard allowing users to select an Amazon Machine
* Image to launch.
*/
class AmiSelectionWizardPage extends WizardPage {
/**
* The composite listing the available AMIs for users to select.
*/
private FilteredAmiSelectionTable amiSelectionComposite;
/**
* Creates a new AMI selection wizard page for the launch wizard.
*/
public AmiSelectionWizardPage() {
super("AMI Selection Page", "Select an AMI to launch", null);
this.setDescription("Select an Amazon Machine Image to launch");
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.DialogPage#dispose()
*/
@Override
public void dispose() {
if (amiSelectionComposite != null) amiSelectionComposite.dispose();
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.WizardPage#canFlipToNextPage()
*/
@Override
public boolean canFlipToNextPage() {
// Bail out early if the table doesn't exist yet
if (amiSelectionComposite == null) return false;
// Make sure the user has selected an AMI
return amiSelectionComposite.getSelectedImage() != null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
@Override
public void createControl(Composite parent) {
Composite control = new Composite(parent, SWT.NONE);
control.setLayout(new GridLayout(1, false));
control.setLayoutData(new GridData(GridData.FILL_BOTH));
ToolBarManager manager = new ToolBarManager(SWT.None);
amiSelectionComposite = new FilteredAmiSelectionTable(control, manager, 3);
amiSelectionComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
amiSelectionComposite.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateErrorMessages();
getContainer().updateButtons();
}
});
manager.add(amiSelectionComposite.getAmiSelectionTable().getRefreshAction());
manager.add(amiSelectionComposite.getAmiSelectionTable().getAmiFilterDropDownAction());
manager.add(amiSelectionComposite.getAmiSelectionTable().getPlatformFilterDropDownAction());
manager.update(true);
updateErrorMessages();
this.setControl(control);
}
/**
* Returns the AMI the user selected to launch.
*
* @return The AMI the user selected to launch.
*/
Image getSelectedAmi() {
if (amiSelectionComposite == null) return null;
return amiSelectionComposite.getSelectedImage();
}
/**
* Updates the wizard error message with any issues that the user needs to
* take care of before they can progress to the next page in the wizard.
*/
private void updateErrorMessages() {
if (amiSelectionComposite == null) return;
if (amiSelectionComposite.getSelectedImage() == null) {
this.setErrorMessage("No AMI selected");
} else {
this.setErrorMessage(null);
}
}
}
| 7,255 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/preferences/PreferenceInitializer.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.preferences;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
/**
* Class used to initialize default preference values.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/** The default ssh client for unix-ish hosts (Linux and Mac) */
private static final String DEFAULT_UNIX_SSH_CLIENT = "/usr/bin/ssh";
/** The default graphical terminal for Linux hosts */
private static final String DEFAULT_LINUX_TERMINAL = "/usr/bin/gnome-terminal";
/** The default PuTTY path on Windows */
private static final String DEFAULT_WINDOWS_PUTTY_PATH = "C:\\Program Files\\PuTTY\\PuTTY.exe";
/** The default SSH options for connections to EC2 instances */
private static final String DEFAULT_SSH_OPTIONS = "-o CheckHostIP=no -o TCPKeepAlive=yes " +
"-o StrictHostKeyChecking=no -o ServerAliveInterval=120 -o ServerAliveCountMax=100";
/** The default SSH user for connections to EC2 instances */
private static final String DEFAULT_SSH_USER = "ec2-user";
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Ec2Plugin.getDefault().getPreferenceStore();
store.setDefault(PreferenceConstants.P_SSH_USER, DEFAULT_SSH_USER);
// Windows specific preferences...
store.setDefault(PreferenceConstants.P_PUTTY_EXECUTABLE, DEFAULT_WINDOWS_PUTTY_PATH);
// Unix specific preferences...
store.setDefault(PreferenceConstants.P_SSH_CLIENT, DEFAULT_UNIX_SSH_CLIENT);
store.setDefault(PreferenceConstants.P_SSH_OPTIONS, DEFAULT_SSH_OPTIONS);
// Linux specific preferences...
store.setDefault(PreferenceConstants.P_TERMINAL_EXECUTABLE, DEFAULT_LINUX_TERMINAL);
}
}
| 7,256 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/preferences/KeyPairsPreferencePage.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.eclipse.core.ui.preferences.AwsToolkitPreferencePage;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairComposite;
/**
* Preference page displaying key pairs for a user's account.
*/
public class KeyPairsPreferencePage extends AwsToolkitPreferencePage implements
IWorkbenchPreferencePage {
public KeyPairsPreferencePage() {
super("Amazon EC2 Key Pairs");
this.setPreferenceStore(Ec2Plugin.getDefault().getPreferenceStore());
setDescription("Key Pair Management");
noDefaultAndApplyButton();
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createContents(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Group group = newGroup("Key Pairs:", composite);
newLabel("Key pairs allow you to securely log into your EC2 instances.", group);
KeyPairComposite keyPairSelectionTable = new KeyPairComposite(group);
GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
gridData.heightHint = 150;
keyPairSelectionTable.setLayoutData(gridData);
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performHelp()
*/
@Override
public void performHelp() {
String keyPairHelpResource = "/" + Ec2Plugin.PLUGIN_ID + "/html/concepts/keyPairs.html";
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(keyPairHelpResource);
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
@Override
public void init(IWorkbench workbench) {}
}
| 7,257 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/preferences/ExternalToolsPreferencePage.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.preferences;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.core.util.OsPlatformUtils;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
/**
* Preference page for configuring how external tools (ex: ssh clients) are invoked.
*/
public class ExternalToolsPreferencePage
extends PreferencePage
implements IWorkbenchPreferencePage {
private FileFieldEditor terminalExecutable;
private FileFieldEditor sshClient;
private StringFieldEditor sshOptions;
private FileFieldEditor puttyExecutable;
private StringFieldEditor sshUser;
private static final int MAX_FIELD_EDITOR_COLUMNS = 3;
public ExternalToolsPreferencePage() {
super("External Tool Configuration");
setPreferenceStore(Ec2Plugin.getDefault().getPreferenceStore());
setDescription("External Tool Configuration");
}
@Override
public void init(IWorkbench workbench) {}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#createContents(org.eclipse.swt.widgets.Composite)
*/
@Override
protected Control createContents(Composite parent) {
Composite top = new Composite(parent, SWT.LEFT);
// Sets the layout data for the top composite's
// place in its parent's layout.
top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
top.setLayout(new GridLayout());
Group sshClientGroup = new Group(top, SWT.LEFT);
sshClientGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
sshClientGroup.setText("SSH Client:");
if (OsPlatformUtils.isWindows()) {
String puttyUrl = "http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html";
WebLinkListener webLinkListener = new WebLinkListener();
Link l = new Link(sshClientGroup, SWT.NONE);
l.setText("PuTTY is required for remote shell connections "
+ "to EC2 instances from Windows. \nYou can download it for free "
+ "from <a href=\"" + puttyUrl + "\">" + puttyUrl + "</a>.");
l.addListener(SWT.Selection, webLinkListener);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = MAX_FIELD_EDITOR_COLUMNS;
l.setLayoutData(data);
puttyExecutable = newFileFieldEditor(PreferenceConstants.P_PUTTY_EXECUTABLE, "PuTTY Executable:", sshClientGroup);
} else {
// For the Mac, we use a custom AppleScript script that we ship with the
// plugin so we don't need a seperate terminal exectuable.
if (!OsPlatformUtils.isMac()) {
terminalExecutable = newFileFieldEditor(PreferenceConstants.P_TERMINAL_EXECUTABLE, "Terminal:", sshClientGroup);
}
sshClient = newFileFieldEditor(PreferenceConstants.P_SSH_CLIENT, "SSH Client:", sshClientGroup);
sshOptions = new StringFieldEditor(PreferenceConstants.P_SSH_OPTIONS, "SSH Options: ", sshClientGroup);
sshOptions.setPage(this);
sshOptions.setPreferenceStore(this.getPreferenceStore());
sshOptions.load();
sshOptions.fillIntoGrid(sshClientGroup, MAX_FIELD_EDITOR_COLUMNS);
}
sshUser = new StringFieldEditor(PreferenceConstants.P_SSH_USER, "SSH User: ", sshClientGroup);
sshUser.setPage(this);
sshUser.setPreferenceStore(this.getPreferenceStore());
sshUser.load();
sshUser.fillIntoGrid(sshClientGroup, MAX_FIELD_EDITOR_COLUMNS);
// Reset the layout to three columns after the FieldEditors have mucked with it
GridLayout layout = (GridLayout)(sshClientGroup.getLayout());
layout.numColumns = MAX_FIELD_EDITOR_COLUMNS;
layout.marginWidth = 10;
layout.marginHeight = 8;
return top;
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performDefaults()
*/
@Override
protected void performDefaults() {
if (terminalExecutable != null) terminalExecutable.loadDefault();
if (sshClient != null) sshClient.loadDefault();
if (sshOptions != null) sshOptions.loadDefault();
if (sshUser != null) sshUser.loadDefault();
if (puttyExecutable != null) puttyExecutable.loadDefault();
super.performDefaults();
}
/* (non-Javadoc)
* @see org.eclipse.jface.preference.PreferencePage#performOk()
*/
@Override
public boolean performOk() {
if (terminalExecutable != null) terminalExecutable.store();
if (sshClient != null) sshClient.store();
if (sshOptions != null) sshOptions.store();
if (sshUser != null) sshUser.store();
if (puttyExecutable != null) puttyExecutable.store();
return super.performOk();
}
/*
* Private Interface
*/
/**
* Convenience method for creating a FileFieldEditor.
*
* @param preferenceName
* The preference managed by this FileFieldEditor.
* @param label
* The label for this FieldEditor.
* @param parent
* The parent for this new FieldEditor widget.
*
* @return The new FileFieldEditor.
*/
private FileFieldEditor newFileFieldEditor(String preferenceName, String label, Composite parent) {
FileFieldEditor editor = new FileFieldEditor(preferenceName, label, parent);
editor.setPage(this);
editor.setPreferenceStore(this.getPreferenceStore());
editor.load();
editor.fillIntoGrid(parent, MAX_FIELD_EDITOR_COLUMNS);
return editor;
}
}
| 7,258 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/preferences/PreferenceConstants.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.preferences;
/**
* Constant definitions for plug-in preference keys.
*/
public class PreferenceConstants {
/** Preference key for the path to the PuTTY executable on Windows. */
public static final String P_PUTTY_EXECUTABLE = "puttyExecutable";
/** Preference key for the path to the terminal executable. */
public static final String P_TERMINAL_EXECUTABLE = "terminalExecutable";
/** Preference key for the path to the ssh executable. */
public static final String P_SSH_CLIENT = "sshExecutable";
/** Preference key for additional SSH command line options. */
public static final String P_SSH_OPTIONS = "sshOptions";
/** Preference key for the SSH user to log in as */
public static final String P_SSH_USER = "sshUser";
}
| 7,259 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/utils/MenuAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.utils;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.utils.IMenu.MenuItem;
/**
* Action class to create static Menu objects
*/
public class MenuAction extends Action implements IMenuCreator {
/** Holds MenuHandler object to process the menus */
private MenuHandler menuHandler;
/** Menu that gets displayed */
protected Menu menu;
/**
* Constructor
*
* @param text
* Text that gets displayed on the Menu
* @param toolTip
* Tooltip that gets displayed for the menu
* @param imageDescriptor
* The icon used for the menu
* @param menuHandler
* The MenuHandler object used to manage actions
*/
public MenuAction(String text, String toolTip,
String imageDescriptor, MenuHandler menuHandler) {
setText(text);
setToolTipText(toolTip);
setImageDescriptor(Ec2Plugin.getDefault().getImageRegistry().getDescriptor(imageDescriptor));
this.menuHandler = menuHandler;
setMenuCreator(this);
}
/**
* @see org.eclipse.jface.action.IMenuCreator#getMenu(Menu)
*/
@Override
public Menu getMenu(Menu parent) {
return menu;
}
/**
* @see org.eclipse.jface.action.IMenuCreator#getMenu(Control)
*/
@Override
public Menu getMenu(Control parent) {
if (menu != null) {
return menu;
}
return constructMenu(parent);
}
/**
* Creates the menu dynamically
*
* @param parent
* Composite on which the menu is drawn
*
* @return The created menu
*/
protected Menu constructMenu(Control parent) {
menu = new Menu(parent);
for (final MenuItem menuItem : menuHandler.getMenuItems()) {
if (menuItem.equals(MenuItem.SEPARATOR)) {
new org.eclipse.swt.widgets.MenuItem(menu, SWT.SEPARATOR);
} else {
IAction action = new Action(menuItem.getMenuText(), AS_RADIO_BUTTON) {
@Override
public void run() {
if (isChecked()) {
menuHandler.setCurrentSelection(menuItem);
}
}
};
addActionToMenu(action);
// Every Time new object is created, so getMenuId is used for
// determining the current selection
action.setChecked(menuHandler.getCurrentSelection().getMenuId().equals(menuItem.getMenuId()));
}
}
return menu;
}
/**
* Use to add different MenuItems to the menu
*
* @param action
* The Action to be added
*/
protected void addActionToMenu(IAction action) {
ActionContributionItem item = new ActionContributionItem(action);
item.fill(menu, -1);
}
/**
* @see org.eclipse.jface.action.IMenuCreator#dispose()
*/
@Override
public void dispose() {
if (menu != null) {
menu.dispose();
}
}
/**
* Used to popup the menu
*
* @see org.eclipse.jface.action.Action#run()
*/
@Override
public void run() {
if (menu != null)
menu.setVisible(true);
}
}
| 7,260 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/utils/IMenu.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.utils;
/**
* Interface for defining Menus
*/
public interface IMenu {
public class MenuItem {
public static final MenuItem SEPARATOR = new MenuItem("SEPARATOR", "Separator");
private String menuId;
private String menuText;
private boolean checked;
public MenuItem(String menuId, String menuText) {
this.menuId = menuId;
this.menuText = menuText;
}
public MenuItem(String menuText, boolean checked) {
this.menuText = menuText;
this.checked = checked;
}
public String getMenuId() {
return menuId;
}
public void setMenuId(String menuId) {
this.menuId = menuId;
}
public String getMenuText() {
return menuText;
}
public void setMenuText(String menuText) {
this.menuText = menuText;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
/**
* Callback function for Caller when the MenuItem is clicked
*
* @param menuItemSelected The selected MenuItem
*/
public void menuClicked(MenuItem menuItemSelected);
}
| 7,261 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/utils/DynamicMenuAction.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.utils;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
/**
* Action class to create dynamic Menu objects. The menu is created everytime
* the widget is invoked, enabling the menu to be re-populated with fresh data
*/
public class DynamicMenuAction extends MenuAction {
/**
* Constructor
*
* @param text
* Text that gets displayed on the Menu
* @param toolTip
* Tooltip that gets displayed for the menu
* @param imageDescriptor
* The icon used for the menu
* @param menuHandler
* The MenuHandler object used to manage actions
*/
public DynamicMenuAction(String text, String toolTip,
String imageDescriptor, MenuHandler dropdownMenuHandler) {
super(text, toolTip, imageDescriptor, dropdownMenuHandler);
}
/**
* If there is already a menu from previous, dispose it for being able to
* create a fresh one
*
* @see com.amazonaws.eclipse.ec2.utils.MenuAction#getMenu(Menu parent)
*/
@Override
public Menu getMenu(Control parent) {
if (menu != null) {
menu.dispose();
}
return constructMenu(parent);
}
}
| 7,262 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/utils/MenuHandler.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.utils;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.eclipse.ec2.utils.IMenu.MenuItem;
/**
* Handler to process Menu selections
*/
public class MenuHandler {
/** Holds the currently selected Menu Item */
private MenuItem currentSelection;
/** Holds all the Menu Items that needs to be displayed */
private List<MenuItem> menuItems;
/** Holds the client from which the Menu is invoked */
private IMenu observer;
/**
* Constructor
*/
public MenuHandler() {
menuItems = new ArrayList<>();
}
/**
* Creates a MenuItem for the menu
*
* @param menuId
* An Id for the menu
* @param menuText
* The text that gets displayed
* @return Created MenuItem
*
* @see MenuHandler#add(String, String, boolean)
*/
public MenuItem add(String menuId, String menuText) {
return add(menuId, menuText, false);
}
/**
* Creates a MenuItem for the menu
*
* @param menuId
* An Id for the menu
* @param menuText
* The text that gets displayed
* @param boolean The current MenuItem is marked for selection
*
* @return Created MenuItem
*/
public MenuItem add(String menuId, String menuText, boolean selected) {
MenuItem menuItem = new MenuItem(menuId, menuText);
menuItems.add(menuItem);
currentSelection = selected ? menuItem : currentSelection;
return menuItem;
}
/**
* Adds a MenuItem to the current MenuList
*
* @param menuItem
* MenuItem to be added
*/
public void add(MenuItem menuItem) {
menuItems.add(menuItem);
}
/**
* Clears the MenuItem list. Used when Menu needs to be refreshed with new
* data
*/
public void clear() {
menuItems.clear();
}
/**
* Returns the current MenuItem selected
*
* @return MenuItem selected
*/
public MenuItem getCurrentSelection() {
return currentSelection;
}
/**
* Sets the current selection of the MEnuItem
*
* @param currentSelection
* Current selected MenuItem
*/
public void setCurrentSelection(MenuItem currentSelection) {
this.currentSelection = currentSelection;
if (observer != null)
observer.menuClicked(currentSelection);
}
/**
* Returns the list of MenuItems
*
* @return List The menu list
*/
public List<MenuItem> getMenuItems() {
return menuItems;
}
/**
* Registers the client as the listener, which will be notified using
* callback
*
* @param observer
* The client which wishes to get notified for every MenuItems
* selected
*/
public void addListener(IMenu observer) {
this.observer = observer;
}
}
| 7,263 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/keypairs/KeyPairManager.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.keypairs;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
import com.amazonaws.services.ec2.model.CreateKeyPairResult;
import com.amazonaws.services.ec2.model.KeyPair;
/**
* Manages the EC2 key pairs that the plugin knows about, including creating new
* key pairs, registering private key files with a named key, etc.
*/
public class KeyPairManager {
/** The suffix for private key files */
private static final String PRIVATE_KEY_SUFFIX = ".pem";
/**
* Returns the private key file associated with the named key, or null if no
* key file can be found.
*
* @param accountId
* The account id that owns the key name
* @param keyPairName
* The name of the key being looked up.
* @return The file path to the associated private key file for the named
* key.
*/
public String lookupKeyPairPrivateKeyFile(String accountId, String keyPairName) {
try {
Properties registeredKeyPairs = loadRegisteredKeyPairs(accountId);
String privateKeyPath = registeredKeyPairs.getProperty(keyPairName);
if ( privateKeyPath != null )
return privateKeyPath;
} catch ( IOException e ) {
Status status = new Status(Status.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to load registered key pairs file: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
return null;
}
/**
* Returns true if and only if the specified key pair is valid, meaning it
* has a valid registered private key file.
*
* @param accountId
* The account id that owns the key name
* @param keyPairName
* The name of the key pair to check.
* @return True if and only if the specified key pair is valid, meaning it
* has a valid registered private key file.
*/
public boolean isKeyPairValid(String accountId, String keyPairName) {
try {
String keyFile = lookupKeyPairPrivateKeyFile(accountId, keyPairName);
if ( keyFile == null )
return false;
File f = new File(keyFile);
return f.isFile();
} catch ( Exception e ) {
// If we catch an exception, we know this must not be valid
}
return false;
}
/**
* Requests a new key pair from EC2 with the specified name, and saves the
* private key portion in the specified directory.
*
* @param accountId
* The account id that owns the key name
* @param keyPairName
* The name of the requested key pair.
* @param keyPairDirectory
* The directory in which to save the private key file.
* @param ec2RegionOverride
* The region where the EC2 key pair is created.
* @throws IOException
* If any problems were encountered storing the private key to
* disk.
* @throws AmazonClientException
* If any problems were encountered requesting a new key pair
* from EC2.
*/
public void createNewKeyPair(String accountId, String keyPairName, String keyPairDirectory, Region ec2RegionOverride) throws IOException,
AmazonClientException {
File keyPairDirectoryFile = new File(keyPairDirectory);
if ( !keyPairDirectoryFile.exists() ) {
if ( !keyPairDirectoryFile.mkdirs() ) {
throw new IOException("Unable to create directory: " + keyPairDirectory);
}
}
/**
* It's possible that customers could have two keys with the same name,
* so silently rename to avoid such a conflict. This isn't the most
* straightforward user interface, but probably better than enforced
* directory segregation by account, or else disallowing identical names
* across accounts.
*/
File privateKeyFile = new File(keyPairDirectoryFile, keyPairName + PRIVATE_KEY_SUFFIX);
int i = 1;
while ( privateKeyFile.exists() ) {
privateKeyFile = new File(keyPairDirectoryFile, keyPairName + "-" + i + PRIVATE_KEY_SUFFIX);
}
CreateKeyPairRequest request = new CreateKeyPairRequest();
request.setKeyName(keyPairName);
AmazonEC2 ec2 = null;
if (ec2RegionOverride == null) {
ec2 = Ec2Plugin.getDefault().getDefaultEC2Client();
} else {
ec2 = AwsToolkitCore.getClientFactory().getEC2ClientByEndpoint(ec2RegionOverride.getServiceEndpoint(ServiceAbbreviations.EC2));
}
CreateKeyPairResult response = ec2.createKeyPair(request);
KeyPair keyPair = response.getKeyPair();
String privateKey = keyPair.getKeyMaterial();
try (FileWriter writer = new FileWriter(privateKeyFile)) {
writer.write(privateKey);
}
registerKeyPair(accountId, keyPairName, privateKeyFile.getAbsolutePath());
/*
* SSH requires our private key be locked down.
*/
try {
/*
* TODO: We should model these platform differences better (and
* support windows).
*/
Runtime.getRuntime().exec("chmod 600 " + privateKeyFile.getAbsolutePath());
} catch ( IOException e ) {
Status status = new Status(Status.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to restrict permissions on private key file: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
/**
* Requests a new key pair from EC2 with the specified name, and saves the
* private key portion in the specified directory.
*
* @param accountId
* The account id that owns the key name
* @param keyPairName
* The name of the requested key pair.
* @param keyPairDirectory
* The directory in which to save the private key file.
* @throws IOException
* If any problems were encountered storing the private key to
* disk.
* @throws AmazonClientException
* If any problems were encountered requesting a new key pair
* from EC2.
*/
public void createNewKeyPair(String accountId, String keyPairName, String keyPairDirectory) throws IOException, AmazonClientException {
createNewKeyPair(accountId, keyPairName, keyPairDirectory, null);
}
/**
* Returns the default directory where the plugin assumes private keys are
* stored.
*
* @return The default directory where the plugin assumes private keys are
* stored.
*/
public static File getDefaultPrivateKeyDirectory() {
String userHomeDir = System.getProperty("user.home");
if ( userHomeDir == null || userHomeDir.length() == 0 )
return null;
return new File(userHomeDir + File.separator + ".ec2");
}
/**
* Registers an existing key pair and private key file with this key pair
* manager. This method is only for *existing* key pairs. If you need a new
* key pair created, you should be using createNewKeyPair.
*
* @param accountId
* The account id that owns the key name
* @param keyName
* The name of the key being registered.
* @param privateKeyFile
* The path to the private key file for the specified key pair.
* @throws IOException
* If any problems are encountered adding the specified key pair
* to the mapping of registered key pairs.
*/
public void registerKeyPair(String accountId, String keyName, String privateKeyFile) throws IOException {
Properties registeredKeyPairs = loadRegisteredKeyPairs(accountId);
registeredKeyPairs.put(keyName, privateKeyFile);
storeRegisteredKeyPairs(accountId, registeredKeyPairs);
}
/**
* Attempts to convert any legacy private key files by renaming them.
*/
public static void convertLegacyPrivateKeyFiles() throws IOException {
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
File pluginStateLocation = Ec2Plugin.getDefault().getStateLocation().toFile();
File keyPairsFile = new File(pluginStateLocation, getKeyPropertiesFileName(accountId));
if ( !keyPairsFile.exists() ) {
File legacyKeyPairsFile = new File(pluginStateLocation, "registeredKeyPairs.properties");
if ( legacyKeyPairsFile.exists() ) {
FileUtils.copyFile(legacyKeyPairsFile, keyPairsFile);
}
}
}
/*
* Private Interface
*/
private Properties loadRegisteredKeyPairs(String accountId) throws IOException {
/*
* If the plugin isn't running (such as during tests), just return an
* empty property list.
*/
Ec2Plugin plugin = Ec2Plugin.getDefault();
if ( plugin == null )
return new Properties();
/*
* TODO: we could optimize this and only load the registered key pairs
* on startup and after changes.
*/
File pluginStateLocation = plugin.getStateLocation().toFile();
File registeredKeyPairsFile = new File(pluginStateLocation, getKeyPropertiesFileName(accountId));
registeredKeyPairsFile.createNewFile();
try (FileInputStream fileInputStream = new FileInputStream(registeredKeyPairsFile)) {
Properties registeredKeyPairs = new Properties();
registeredKeyPairs.load(fileInputStream);
return registeredKeyPairs;
}
}
private void storeRegisteredKeyPairs(String accountId, Properties registeredKeyPairs) throws IOException {
File pluginStateLocation = Ec2Plugin.getDefault().getStateLocation().toFile();
File registeredKeyPairsFile = new File(pluginStateLocation, getKeyPropertiesFileName(accountId));
registeredKeyPairsFile.createNewFile();
try (FileOutputStream fileOutputStream = new FileOutputStream(registeredKeyPairsFile)) {
registeredKeyPairs.store(fileOutputStream, null);
}
}
private static String getKeyPropertiesFileName(String accountId) {
return "registeredKeyPairs." + accountId + ".properties";
}
}
| 7,264 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/eclipse/ec2/databinding/ValidKeyPairValidator.java | /*
* Copyright 2010-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.ec2.databinding;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.eclipse.ec2.keypairs.KeyPairManager;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairSelectionTable;
import com.amazonaws.services.ec2.model.KeyPairInfo;
public class ValidKeyPairValidator implements IValidator {
private static final KeyPairManager keyPairManager = new KeyPairManager();
private final String accountId;
public ValidKeyPairValidator(String accountId) {
super();
this.accountId = accountId;
}
@Override
public IStatus validate(Object value) {
KeyPairInfo keyPair = (KeyPairInfo) value;
if ( keyPair == null ) {
return ValidationStatus.error("Select a valid key pair");
} else if ( !keyPairManager.isKeyPairValid(accountId, keyPair.getKeyName()) ) {
return ValidationStatus.error(KeyPairSelectionTable.INVALID_KEYPAIR_MESSAGE);
} else {
return ValidationStatus.ok();
}
}
}
| 7,265 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/Ec2Server.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.ec2.cluster;
import java.io.File;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.ec2.InstanceUtils;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Instance;
/**
* Represents an individual server/host running in EC2. This class
* is not intended to be used directly and should be subclasses by
* clients instead.
*/
public abstract class Ec2Server {
/** The EC2 instance running this server */
protected Instance instance;
/** True if this server is (or should be) in debug mode */
private boolean debugMode;
/**
* Creates a new Ec2Server associated with the specified EC2 instance.
*
* @param instance
* The EC2 instance associated with this Ec2Server.
*/
public Ec2Server(Instance instance) {
this.instance = instance;
}
/**
* Optional method that application server subclasses can implement to
* perform additional server initialization. Subclasses who do chose to
* implement this should be aware that they are responsible for detecting if
* initializing is necessary or not inside their implementation. The
* framework will call this during each launch.
*
* @throws Exception
* If there were any problems while initializing this
* application server.
*/
public void initialize() throws Exception {}
/**
* Subclasses of Ec2Server must implement this method with the specific code
* required to start their server application on the EC2 instance associated
* with this server object.
*
* @throws Exception
* If any problems are encountered while starting the
* application server on this EC2 instance.
*/
public abstract void stop() throws Exception;
/**
* Subclasses of Ec2Server must implement this method with the specific code
* required to stop their server application on the EC2 instance associated
* with this server object.
*
* @throws Exception
* If any problems are encountered while starting the
* application server on this EC2 instance.
*/
public abstract void start() throws Exception;
/**
* Publishes the archive file (containing the project resources that the EC2
* cluster management layer determined needed to be published) for the
* project associated with the specified module to this host.
*
* @param archiveFile
* An archive file containing the project resources that need to
* be published. This is not necessarily the entire project, but
* just what the EC2 cluster management layer thinks needs to be
* published to this host, based on its knowledge of prior
* publish events.
* @param moduleName
* The name of the module associated with the project being
* published.
*
* @throws Exception
* If any problems are encountered while publishing.
*/
public abstract void publish(File archiveFile, String moduleName) throws Exception;
/**
* Publishes the server configuration files for this host.
*
* @param serverConfigurationDirectory
* The directory containing the server configuration files that need
* to be published to this server.
*
* @throws Exception
* If any problems are encountered while publishing.
*/
public abstract void publishServerConfiguration(File serverConfigurationDirectory) throws Exception;
/**
* Sets whether or not this server should be running in debug mode.
*
* @param debugMode
* True if this server should be running in debug mode.
*/
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
/**
* Returns whether or not this server is (or should be) running in debug
* mode.
*
* @return True if this server should be running in debug mode.
*/
public boolean isDebugMode() {
return debugMode;
}
/**
* Reloads the data about the EC2 instance represented by this server.
*
* @param ec2Client
* The EC2 client to use when refreshing the instance data.
* @throws AmazonClientException
* If any problems are encountered refreshing the instance data.
*/
public void refreshInstance(AmazonEC2 ec2Client) throws AmazonClientException {
InstanceUtils instanceUtils = new InstanceUtils(ec2Client);
Instance tempInstance = instanceUtils.lookupInstanceById(getInstanceId());
if (tempInstance == null) {
throw new AmazonClientException(
"Unable to find a running instance with id: " + getInstanceId());
}
instance = tempInstance;
}
/**
* Returns the IP address of this host.
*
* @return The IP address of this host.
*/
public String getIp() {
return instance.getPublicDnsName();
}
/**
* Returns the ID of the Amazon EC2 instance this server represents.
*
* @return The ID of the Amazon EC2 instance this server represents.
*/
public String getInstanceId() {
return instance.getInstanceId();
}
/**
* Returns the Amazon EC2 instance this server represents.
*
* @return The Amazon EC2 instance this server represents.
*/
public Instance getInstance() {
return instance;
}
}
| 7,266 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/SimpleCluster.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.ec2.cluster;
import java.lang.reflect.Constructor;
import com.amazonaws.services.ec2.model.Instance;
/**
* Simple cluster implementation suitable for basic clusters that don't need a
* lot of customization. Callers can create a new BasicCluster object and pass
* in an implementation of the application server class that they want
* instantiated for every host in the cluster.
*/
public class SimpleCluster extends Cluster {
/**
* The application server class that will be instantiated for any hosts
* added to this cluster and contains all the logic required for working
* with application servers in this cluster (publishing, initializing, etc)
*/
private final Class<? extends Ec2Server> appServerClass;
/**
* Creates a new SimpleCluster object that will use the specified
* application server class for all members of this cluster.
*
* @param clusterConfiguration
* The configuration details for this cluster instance, including
* the security group it runs in, the key pair used to access it,
* etc.
* @param appServerClass
* The application server subclass that will be instantiated for
* all servers that are added to this cluster. This class must
* have a publicly accessible constructor taking a
* Instance object, otherwise this class will fail when it
* tries to instantiate objects of this class for any hosts added
* to this cluster.
*/
public SimpleCluster(ClusterConfiguration clusterConfiguration, Class<? extends Ec2Server> appServerClass) {
super(clusterConfiguration);
this.appServerClass = appServerClass;
}
/**
* {@inheritDoc}
*
* Simple implementation of createApplicationServer that instantiates the
* application server class specified in the constructor for the specified
* Amazon EC2 instance.
*
* @throws RuntimeException
* If there were any problems instantiating the application
* server class specified in this class' constructor.
*/
@Override
protected Ec2Server createApplicationServer(Instance instance) {
try {
Constructor<? extends Ec2Server> constructor = appServerClass.getConstructor(Instance.class);
return constructor.newInstance(instance);
} catch (Exception e) {
throw new RuntimeException("Unable to create new application server object of type "
+ appServerClass.getName());
}
}
}
| 7,267 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/Cluster.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.ec2.cluster;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.ec2.Ec2InstanceLauncher;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.ec2.InstanceUtils;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.AssociateAddressRequest;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.DescribeAddressesRequest;
import com.amazonaws.services.ec2.model.DescribeAddressesResult;
import com.amazonaws.services.ec2.model.Instance;
/**
* Models a cluster of hosts running in Amazon EC2. Specific application server
* clusters will need to override this class to provide details on their
* application servers.
*/
public abstract class Cluster {
/** Shared logger */
private static final Logger logger = Logger.getLogger(Cluster.class.getName());
/** Shared factory for creating Amazon EC2 clients */
private final AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory();
/**
* The individual application servers that make up this cluster.
*/
protected List<Ec2Server> applicationServers = new ArrayList<>();
/** The optional proxy for this elastic cluster */
private Ec2WebProxy webProxy;
/**
* A set of EC2 instance IDs representing servers who have had their
* server configuration successfully published since the last time
* the server configuration files were invalidated.
*/
protected Set<String> serversWithUpToDateConfiguration = new HashSet<>();
/**
* The configuration that defines how a cluster instance runs, including the
* security group in which the AMIs run, the key pair that provides access
* to the instance, etc.
*/
protected final ClusterConfiguration clusterConfiguration;
/**
* A map of the application server AMIs to launch for this cluster mapped by
* Amazon EC2 region name.
*/
private Map<String, String> amisByRegion = new HashMap<>();
/**
* True if this cluster should be running in debug mode, false otherwise.
*/
private boolean debugMode;
/**
* Creates a new cluster with the specified cluster configuration.
*
* @param clusterConfiguration
* The configuration details for this cluster including what
* security group it runs in, what key pair is used to access it,
* etc.
*/
public Cluster(ClusterConfiguration clusterConfiguration) {
this.clusterConfiguration = clusterConfiguration;
}
/**
* Sets whether or not this cluster should be running in debug mode.
*
* @param debugMode
* True if this cluster should be running in debug mode,
* otherwise false.
*/
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
for (Ec2Server server : applicationServers) {
server.setDebugMode(debugMode);
}
}
/**
* Adds a new host to this cluster.
*
* @param instance
* The Amazon EC2 instance to add to this cluster.
*/
public void addHost(Instance instance) {
Ec2Server server = createApplicationServer(instance);
server.setDebugMode(debugMode);
applicationServers.add(server);
}
/**
* Adds the specified host as the proxy for this cluster.
*
* @param instance
* The Amazon EC2 instance that will serve as the proxy for this
* cluster.
*/
public void addProxyHost(Instance instance) {
webProxy = new Ec2WebProxy(instance);
int serverPort = clusterConfiguration.getMainPort();
if (serverPort != -1) {
this.webProxy.setMainPort(serverPort);
}
}
/**
* Publishes the specified resources to this cluster. The default
* implementation simply iterates over the hosts in the cluster and calls
* publish on the individual application servers.
*
* Subclasses can override the default implementation if a specific cluster
* of application servers requires a more involved publish process at the
* cluster level.
*
* @see Ec2Server#publish(File, String) for more details on the data
* provided in the moduleArchive.
*
* @param moduleArchive
* The archive of resources to be deployed.
* @param moduleName
* The name of the module being deployed.
* @throws Exception
* If any problems were encountered while publishing.
*/
public void publish(File moduleArchive, String moduleName) throws Exception {
for (Ec2Server server : applicationServers) {
server.publish(moduleArchive, moduleName);
}
}
/**
* Notifies this cluster that the server configuration files on the cluster
* hosts are out of sync and need to be published the next time
* publishServerConfiguration is called.
*/
public void invalidateServerConfiguration() {
serversWithUpToDateConfiguration.clear();
}
/**
* Returns the number of hosts contained in this cluster.
*
* @return The number of hosts contained in this cluster.
*/
public int size() {
return applicationServers.size();
}
/**
* Initializes this running cluster so that it's ready to be used. The exact
* initialization performed depends on the specifics of the actual
* application servers. The default implementation simply gives each
* application server a chance to initialize themselves.
*
* Subclasses can override this method to perform initialization specific to
* other types of application server clusters.
*
* @throws Exception
* If any problems were encountered while initializing this
* cluster.
*/
public void initialize() throws Exception {
for (Ec2Server server : applicationServers) {
server.initialize();
}
}
/**
* Returns a list of the Amazon EC2 instance IDs for this cluster.
*
* @return A list of the Amazon EC2 instance IDs for this cluster.
*/
public List<String> getInstanceIds() {
List<String> instanceIds = new ArrayList<>();
if (applicationServers == null) {
return instanceIds;
}
for (Ec2Server server : applicationServers) {
instanceIds.add(server.getInstanceId());
}
return instanceIds;
}
/**
* Stops the application servers in this cluster.
*
* @throws Exception
* If any problems are encountered while stopping the
* application servers.
*/
public void stopApplicationServers() throws Exception {
if (applicationServers != null) {
for (Ec2Server server : applicationServers) {
server.stop();
}
}
if (webProxy != null) {
webProxy.stop();
}
}
/**
* Starts the application servers in this cluster.
*
* @throws Exception
* If any problems are encountered while starting the
* application servers.
*/
public void startApplicationServers() throws Exception {
if (applicationServers != null) {
for (Ec2Server server : applicationServers) {
server.start();
}
}
if (webProxy != null) {
webProxy.start();
}
}
/**
* Starts this cluster, launching any Amazon EC2 instances that need to be
* launched, otherwise just reusing the existing hosts in the cluster if
* they're available. If a proxy is required for this cluster, it will be
* launched (if necessary) and configured here as well.
*
* @param monitor
* The progress monitor to use to report progress of starting
* this cluster.
*
* @throws Exception
* If there are any problems launching the cluster hosts,
* initializing the application server environments, configuring
* the proxy, etc.
*/
public void start(IProgressMonitor monitor) throws Exception {
if (monitor == null)
monitor = new NullProgressMonitor();
if (monitor.isCanceled())
return;
monitor.beginTask("Starting cluster", 30);
// Automatic security group configuration...
configureEc2SecurityGroupPermissions(clusterConfiguration
.getSecurityGroupName());
monitor.worked(10);
// Service container launching...
launchServiceContainerInstances(monitor);
monitor.worked(10);
// Proxy launching...
if (clusterConfiguration.getClusterSize() > 1) {
launchProxyInstance(monitor);
} else {
webProxy = null;
}
monitor.worked(10);
String elasticIp = clusterConfiguration.getElasticIp();
if (elasticIp != null) {
associateElasticIp(elasticIp);
}
monitor.done();
}
/**
* Returns the IP address (as a String) for the head of this cluster. If this
* cluster is fronted by a proxy for load balancing, that address will be
* returned.
*
* @return The IP address (as a String) for the head of this cluster.
*/
public String getIp() {
// if we're associated with an elastic IP, use that...
if (clusterConfiguration.getElasticIp() != null) {
return clusterConfiguration.getElasticIp();
}
// if we're using a proxy to load balance, use that...
if (webProxy != null) {
return webProxy.getIp();
}
// otherwise just use the first instance's public IP
return applicationServers.get(0).getIp();
}
/**
* Returns the IP address for one of the servers in this cluster (not
* including the proxy if one is used for load balancing). Callers that need
* the address of a real server and need to ensure that they aren't going
* through the load balancer should use this method to ensure they get
* direct access to one of the application servers.
*
* @return The IP address for one of the application servers in this
* cluster.
*/
public String getInstanceIp() {
return applicationServers.get(0).getIp();
}
/**
* Publishes any server configuration files that need to be published based
* on callers use of the invalidateServerConfiguration method.
*
* @param serverConfigurationDirectory
* The directory containing the app server specific configuration
* files.
*
* @throws Exception
* If any problems were encountered publishing the server
* configuration files.
*/
public void publishServerConfiguration(File serverConfigurationDirectory) throws Exception {
for (Ec2Server server : applicationServers) {
if (isConfigurationDirty(server.getInstanceId())) {
server.publishServerConfiguration(serverConfigurationDirectory);
setConfigurationClean(server.getInstanceId());
}
}
/*
* TODO: it'd be nice to pass the progress monitor into
* publishServerConfiguration and get a finer granularity on the
* progress being made, but at the same time, we want to try to keep any
* Eclipse specific dependencies out of the cluster management layer as
* much as possible.
*
* We might consider building a simple interface that mirrors what we
* need from IProgressMonitor and then a simple adapter.
*/
// monitor.worked(10 * cluster.size());
if (webProxy != null && isConfigurationDirty(webProxy.getInstanceId())) {
int mainPort = clusterConfiguration.getMainPort();
if (mainPort != -1) {
webProxy.setMainPort(mainPort);
}
try {
webProxy.publishServerConfiguration(null);
webProxy.start();
setConfigurationClean(webProxy.getInstanceId());
} catch (Exception ioe) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to publish proxy configuration: "
+ ioe.getMessage(), ioe);
throw new CoreException(status);
}
}
}
/**
* Registers the specified AMI for the specified Amazon EC2 region with this
* cluster. When this cluster needs to launch Amazon EC2 instances, it will
* use the registered AMIs and the configured region to determine which AMI
* to launch.
*
* @param amiId
* The ID of the Amazon EC2 AMI that should be launched for
* application servers in this cluster in the specified Amazon
* EC2 region.
* @param region
* The name of the Amazon EC2 region in which the specified AMI
* exists.
*/
public void registerAmiForRegion(String amiId, String region) {
amisByRegion.put(region, amiId);
}
/**
* Returns the ID of the Amazon EC2 AMI for this cluster in the specified
* region, otherwise null if there is no AMI supported for the specified
* region.
*
* @param region
* The Amazon EC2 region in which the returned AMI exists.
*
* @return The ID of the Amazon EC2 AMI for this cluster in the specified
* region, otherwise null if there is no AMI supported for the
* specified region.
*/
public String getAmiByRegion(String region) {
return amisByRegion.get(region);
}
/**
* Returns the set of Amazon EC2 region names in which this cluster can run.
*
* @return The set of Amazon EC2 region names in which this cluster can run.
*/
public Set<String> getSupportedRegions() {
return amisByRegion.keySet();
}
/**
* Returns a unique ID for the Amazon EC2 resource responsible for load
* balancing in this cluster.
*
* @return A unique ID for the Amazon EC2 resource responsible for load
* balancing in this cluster.
*/
public String getProxyId() {
if (webProxy == null) {
return null;
}
return webProxy.getInstanceId();
}
/*
* Protected Interface
*/
/**
* Subclasses must implement this callback method to create the actual
* application server object for a specified Amazon EC2 instance. The
* application server object is what defines the custom interaction required
* for working with a specific application server.
*
* @param instance
* The Amazon EC2 instance with which the new application server
* is associated.
*
* @return An object extending the Ec2Server abstract class that provides
* the exact logic for working with a specific application server
* (publishing, initializing, etc).
*/
protected abstract Ec2Server createApplicationServer(Instance instance);
/**
* Returns true if the specified instance ID needs to have its configuration
* republished.
*
* @param instanceId
* The ID of the EC2 instance representing the server whose
* configuration files are in question.
*
* @return True if the specified instance ID has not been published since
* the last time the server configuration files were invalidated
* by the invalidateServerConfiguration method,
* otherwise false if the published server configuration files for
* the specified EC2 instance are up to date.
*/
protected boolean isConfigurationDirty(String instanceId) {
return !serversWithUpToDateConfiguration.contains(instanceId);
}
/**
* Notifies this cluster that the specified EC2 instance ID has had its
* server configuration files successfully published and is now up to date.
*
* @param instanceId
* The ID of the EC2 instance whose server configuration has been
* successfully published.
*/
protected void setConfigurationClean(String instanceId) {
serversWithUpToDateConfiguration.add(instanceId);
}
/**
* Returns the Amazon EC2 client to use when working with this cluster.
*
* @return The Amazon EC2 client to use when working with this cluster.
*/
protected AmazonEC2 getEc2Client() {
String clusterEndpoint = clusterConfiguration.getEc2RegionEndpoint();
if (clusterEndpoint != null && clusterEndpoint.length() > 0) {
return clientFactory.getEC2ClientByEndpoint(clusterEndpoint);
}
// We should always have a region/endpoint configured in the cluster,
// but just in case we don't, we'll still return something.
return Ec2Plugin.getDefault().getDefaultEC2Client();
}
/*
* Private Interface
*/
/**
* Configures the security group in which this cluster is running so that
* the cluster can be remotely administered and accessed.
*
* @param securityGroup
* The security group to configure.
*
* @throws CoreException
* If any problems are encountered configuring the specified
* security group.
*/
private void configureEc2SecurityGroupPermissions(String securityGroup)
throws CoreException {
String permissiveNetmask = "0.0.0.0/0";
String strictNetmask = permissiveNetmask;
try {
/*
* We use checkip.amazonaws.com to determine our IP and the most
* restrictive netmask we can use to lock down security group
* permissions, but it only works in the US region.
*/
String region = clusterConfiguration.getEc2RegionName();
region = region.toLowerCase();
} catch (Exception e) {
Status status = new Status(Status.INFO, Ec2Plugin.PLUGIN_ID,
"Unable to lookup netmask from checkip.amazon.com. Defaulting to "
+ strictNetmask);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
// We want locked down permissions for the control/management port (SSH)
authorizeSecurityGroupIngressAndSwallowErrors(securityGroup, "tcp", 22,
22, strictNetmask);
// TODO: we'll eventually need the remote debugging port to be configurable
authorizeSecurityGroupIngressAndSwallowErrors(securityGroup, "tcp",
443, 443, strictNetmask);
// We want more permissive permissions for the main, public port
int mainPort = clusterConfiguration.getMainPort();
if (mainPort != -1) {
authorizeSecurityGroupIngressAndSwallowErrors(securityGroup, "tcp",
mainPort, mainPort, permissiveNetmask);
}
}
/**
* Calls out to EC2 to authorize the specified port range, protocol, netmask
* for the specified security group. If any errors are encountered (ex: the
* requested ingress is already included in the security group permissions),
* they are silently swallowed.
*
* @param securityGroup
* The security group to add permissions to.
* @param protocol
* The protocol for the new permissions.
* @param fromPort
* The starting port of the port range.
* @param toPort
* The ending port of the port range.
* @param netmask
* The netmask associated with the new permissions.
*/
private void authorizeSecurityGroupIngressAndSwallowErrors(
String securityGroup, String protocol, int fromPort, int toPort,
String netmask) {
AmazonEC2 ec2 = getEc2Client();
AuthorizeSecurityGroupIngressRequest request = new AuthorizeSecurityGroupIngressRequest();
request.setGroupName(securityGroup);
request.setFromPort(fromPort);
request.setToPort(toPort);
request.setIpProtocol(protocol);
request.setCidrIp(netmask);
try {
ec2.authorizeSecurityGroupIngress(request);
} catch (AmazonClientException e) {
/*
* We don't worry about these exceptions, since callers specifically
* asked for them to be swallowed
*/
}
}
/**
* Launches any application server instances that need to be launched to
* bring this cluster up to full size.
*
* @param monitor
* The progress monitor to use to report progress.
* @throws CoreException
* If any problems are encountered launching the new Amazon EC2
* instances.
* @throws OperationCanceledException
* If we detect that the user canceled the launch.
*/
private void launchServiceContainerInstances(IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
// Calculate how many hosts we need to bring up based on the total size
// of the cluster and how many hosts we already have up.
int numberOfActiveHosts = size();
int numberOfTotalHosts = clusterConfiguration.getClusterSize();
int numberOfMissingHosts = numberOfTotalHosts - numberOfActiveHosts;
if (numberOfMissingHosts < 0)
numberOfMissingHosts = 0;
/*
* TODO: Add logic to shutdown extra instances if we're running too
* many.
*/
// Launch as many hosts as we need to get our fleet to the right size
List<Instance> instances = new ArrayList<>();
if (numberOfMissingHosts > 0) {
logger.info("Launching " + numberOfMissingHosts
+ " service container instances");
String keyPairName = clusterConfiguration.getKeyPairName();
try {
String region = clusterConfiguration.getEc2RegionName();
String amiId = amisByRegion.get(region);
if (amiId == null) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"This cluster doesn't have an AMI registered for the '" + region + "' region");
throw new CoreException(status);
}
Ec2InstanceLauncher launcher = new Ec2InstanceLauncher(amiId,
keyPairName);
launcher.setProgressMonitor(monitor);
launcher.setInstanceType(clusterConfiguration
.getEc2InstanceType());
launcher.setEc2RegionEndpoint(clusterConfiguration
.getEc2RegionEndpoint());
launcher.setNumberOfInstances(numberOfMissingHosts);
launcher.setSecurityGroup(clusterConfiguration
.getSecurityGroupName());
instances = launcher.launchAndWait();
// Mark the web proxy configuration as out of date so that it
// gets published next time this cluster is deployed
if (webProxy != null) {
serversWithUpToDateConfiguration.remove(webProxy
.getInstanceId());
}
} catch (OperationCanceledException oce) {
// We want to let OperationCanceledExceptions propagate up so we
// can deal with them at a higher layer.
throw oce;
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to start cluster: " + e.getMessage(), e);
throw new CoreException(status);
}
logger.info("Successfully started " + instances.size()
+ " instance(s).");
} else {
logger.info("No missing service container instances need to be launched");
}
// Update the local list of application servers
for (Instance instance : instances) {
addHost(instance);
}
try {
initialize();
} catch (Exception e) {
throw new CoreException(new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to fully initialize cluster", e));
}
}
/**
* Returns the EC2 instance ID of the instance attached to the specified
* Elastic IP address, or null if the Elastic IP address wasn't found, or
* isn't attached to an instance.
*
* @param elasticIp
* The Elastic IP address to check.
*
* @return The EC2 instance ID of the instance attached to the specified
* Elastic IP address, or null if no instance is attached to this
* address.
*
* @throws AmazonEC2Exception
* If any problems were encountered while looking up the
* specified Elastic IP.
*/
private String lookupAttachedInstance(String elasticIp) throws AmazonClientException {
DescribeAddressesRequest request = new DescribeAddressesRequest().withPublicIps(elasticIp);
DescribeAddressesResult result = getEc2Client().describeAddresses(request);
if (!result.getAddresses().isEmpty()) {
return result.getAddresses().get(0).getInstanceId();
}
return null;
}
/**
* Associates the specified Elastic IP with this cluster.
*
* @param elasticIp
* The Elastic IP to associate with this cluster.
*/
private void associateElasticIp(String elasticIp) {
AmazonEC2 ec2 = getEc2Client();
InstanceUtils instanceUtils = new InstanceUtils(ec2);
try {
String instanceId;
if (webProxy != null) {
logger.info("Associating Elastic IP with proxy...");
instanceId = webProxy.getInstanceId();
} else {
logger.info("Associating Elastic IP with application server...");
instanceId = applicationServers.get(0).getInstanceId();
}
logger.info(" - Elastic IP '" + elasticIp + "' => '" + instanceId + "'");
/*
* Check if the ElasticIP is already associated with the correct
* instance, and if so, we don't need to do anything...
*/
String attachedInstance = this.lookupAttachedInstance(elasticIp);
if (attachedInstance != null && attachedInstance.equals(instanceId)) {
return;
}
String previousDnsName = instanceUtils.lookupInstanceById(instanceId).getPublicDnsName();
AssociateAddressRequest request = new AssociateAddressRequest();
request.setInstanceId(instanceId);
request.setPublicIp(elasticIp);
ec2.associateAddress(request);
/*
* When we associate the Elastic IP the public DNS name of that host
* changes, so we need to refresh our Instance objects in
* order to see the new DNS name. If we don't do that, then we'll
* run into problems (sooner or later) where the old DNS name
* doesn't work anymore. We check periodically to account for the
* fact that Elastic IP changes can take different amounts of time
* to show up.
*/
String currentDnsName;
int pollCount = 0;
do {
if (pollCount++ > 90) {
throw new Exception("Unable to detect that the Elastic IP was correctly associated");
}
try {Thread.sleep(5000);} catch (InterruptedException e) {}
currentDnsName = instanceUtils.lookupInstanceById(instanceId).getPublicDnsName();
} while (currentDnsName.equals(previousDnsName));
if (webProxy != null) {
webProxy.refreshInstance(getEc2Client());
} else {
applicationServers.get(0).refreshInstance(getEc2Client());
}
} catch (Exception e) {
Status status = new Status(Status.WARNING, Ec2Plugin.PLUGIN_ID,
"Unable to associate Elastic IP with cluster: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW | StatusManager.LOG);
}
}
/**
* Launches the load balancing proxy instance if necessary.
*
* @param monitor
* The progress monitor for this method to use to report progress
* and check for a request from the user to cancel this
* operation.
*
* @throws CoreException
* If any problems are encountered that prevent this method from
* launching and configuring the load balancing proxy instance.
* @throws OperationCanceledException
* If this method detects that the user requested to cancel this
* operation while this method is executing.
*/
private void launchProxyInstance(IProgressMonitor monitor)
throws CoreException, OperationCanceledException {
List<String> instanceIds = getInstanceIds();
List<Instance> proxiedInstances;
try {
InstanceUtils instanceUtils = new InstanceUtils(getEc2Client());
proxiedInstances = instanceUtils.lookupInstancesById(instanceIds);
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to start proxy: " + e.getMessage(), e);
throw new CoreException(status);
}
if (webProxy == null) {
String keyPairName = clusterConfiguration.getKeyPairName();
List<Instance> proxyInstances = null;
try {
String region = clusterConfiguration.getEc2RegionName();
String amiId = Ec2WebProxy.getAmiIdByRegion(region);
// TODO: availability zone support might be nice
Ec2InstanceLauncher proxyLauncher = new Ec2InstanceLauncher(
amiId, keyPairName);
proxyLauncher.setProgressMonitor(monitor);
proxyLauncher.setEc2RegionEndpoint(clusterConfiguration
.getEc2RegionEndpoint());
proxyLauncher.setInstanceType(clusterConfiguration
.getEc2InstanceType());
proxyLauncher.setSecurityGroup(clusterConfiguration
.getSecurityGroupName());
proxyInstances = proxyLauncher.launchAndWait();
} catch (OperationCanceledException oce) {
// We want to let OperationCanceledExceptions propagate up so we
// can deal with them at a higher layer.
throw oce;
} catch (Exception e) {
Status status = new Status(Status.ERROR, Ec2Plugin.PLUGIN_ID,
"Unable to start proxy: " + e.getMessage(), e);
throw new CoreException(status);
}
webProxy = new Ec2WebProxy(proxyInstances.get(0));
webProxy.setMainPort(clusterConfiguration.getMainPort());
}
webProxy.setProxiedHosts(proxiedInstances);
}
}
| 7,268 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/ClusterConfiguration.java | /*
* Copyright 2009-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.ec2.cluster;
/**
* Interface for querying cluster configuration options such as what security
* group the cluster runs in, what key pair is used to access the instances in
* this cluster, etc.
*/
public interface ClusterConfiguration {
/**
* Returns the name of the security group in which this cluster's instances
* run.
*
* @return The name of the security group in which this cluster's instances
* run.
*/
public String getSecurityGroupName();
/**
* Returns the desired size for this cluster.
*
* @return The desired size for this cluster.
*/
public int getClusterSize();
/**
* Returns the optional Elastic IP associated with this cluster.
*
* @return The optional Elastic IP associated with this cluster.
*/
public String getElasticIp();
/**
* Returns the name of the Amazon EC2 region in which this cluster is to
* run.
*
* @return The name of the Amazon EC2 region in which this cluster is to
* run.
*/
public String getEc2RegionName();
/**
* Returns the main port on which this cluster is configured to listen for
* requests.
*
* @return The main port on which this cluster is configured to listen for
* requests.
*/
public int getMainPort();
/**
* Returns the name of the key pair required to log into the instances in
* this cluster.
*
* @return The name of the key pair required to log into the instances in
* this cluster.
*/
public String getKeyPairName();
/**
* Returns the ID of the Amazon EC2 instance type for the hosts in this
* cluster.
*
* @return The ID of the Amazon EC2 instance type for the hosts in this
* cluster.
*/
public String getEc2InstanceType();
/**
* Returns the Amazon EC2 service endpoint with which this cluster
* communicates.
*
* @return The Amazon EC2 service endpoint with which this cluster
* communicates.
*/
public String getEc2RegionEndpoint();
}
| 7,269 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.ec2/src/com/amazonaws/ec2/cluster/Ec2WebProxy.java | /*
* Copyright 2008-2012 Amazon Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.ec2.cluster;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.eclipse.ec2.RemoteCommandUtils;
/**
* Models a proxy that sits in front of servers and load balances requests
* between them.
*/
public class Ec2WebProxy extends Ec2Server {
/** The ID for our US-East proxy AMI */
private static final String US_EAST_1_AMI_ID = "ami-d1ca2db8";
/** The ID for our EU-West proxy AMI */
private static final String EU_WEST_1_AMI_ID = "ami-10163e64";
/** The ID for our US-West proxy AMI */
private static final String US_WEST_1_AMI_ID = "ami-3b09587e";
/** The ID for our AP-Southeast proxy AMI */
private static final String AP_SOUTHEAST_1_AMI_ID = "ami-0df38c5f";
/** The EC2 instances behind this proxy */
private List<Instance> proxiedInstances;
/** Shared utilities for executing remote commands */
private static final RemoteCommandUtils remoteCommandUtils = new RemoteCommandUtils();
/** Shared logger */
private static final Logger logger = Logger.getLogger(Ec2WebProxy.class.getName());
/**
* The port on which this proxy should listen for requests, and on which the
* servers behind this proxy are listening for requests.
*/
private int serverPort = DEFAULT_PORT;
/**
* The default port for this proxy to listen for requests.
*/
private static final int DEFAULT_PORT = 80;
/**
* Returns the ID of the AMI to use when starting this server in EC2, based
* on the specified region. If an AMI isn't available for the specified
* region, this method will throw an exception.
*
* @param region
* The name of the EC2 region (ex: 'us-east-1') in which the
* instance will be launched.
*
* @return The ID of the AMI to use when starting this server in EC2, based
* on the specified region.
*
* @throws Exception
* If there is no AMI registered for the specified region.
*/
public static String getAmiIdByRegion(String region) throws Exception {
if (region.equalsIgnoreCase("us-east-1")) {
return US_EAST_1_AMI_ID;
} else if (region.equalsIgnoreCase("eu-west-1")) {
return EU_WEST_1_AMI_ID;
} else if (region.equalsIgnoreCase("us-west-1")) {
return US_WEST_1_AMI_ID;
} else if (region.equalsIgnoreCase("ap-southeast-1")) {
return AP_SOUTHEAST_1_AMI_ID;
}
throw new Exception("Unsupported region: '" + region + "'");
}
/**
* Creates a new EC2 web proxy running on the specified instance.
*
* @param instance
* A started instance running the EC2 web proxy AMI.
*/
public Ec2WebProxy(Instance instance) {
super(instance);
}
/**
* Sets the main server port for this proxy and the servers behind it. This
* is the port on which this proxy will listen for requests, and the port on
* which the servers behind it are listening for requests. It is not
* currently possible to have the proxy listening on one port and have the
* servers behind it listening on a different port.
*
* @param serverPort
* The port on which this proxy should listen for requests, and
* on which the servers behind this proxy are listening for
* requests.
*/
public void setMainPort(int serverPort) {
this.serverPort = serverPort;
}
/**
* Connects to the proxy and starts the proxy software.
*
* @throws IOException
* If any problems are encountered connecting to the proxy and
* starting the proxy software.
*/
public void startProxy() throws IOException {
String newHaproxyLocation = "/env/haproxy/haproxy";
String startCommand = newHaproxyLocation + " -D -f /etc/haproxy.cfg -p /var/run/haproxy.pid -sf $(</var/run/haproxy.pid)";
remoteCommandUtils.executeRemoteCommand(startCommand, instance);
}
/**
* Connects to the proxy and publishes the proxy configuration.
*
* @throws IOException
* If any problems were encountered publishing the
* configuration.
*/
@Override
public void publishServerConfiguration(File unused) throws Exception {
HaproxyConfigurationListenSection section
= new HaproxyConfigurationListenSection("proxy", serverPort);
for (Instance instance : proxiedInstances) {
section.addServer(instance.getPrivateDnsName() + ":" + serverPort);
}
String proxyConfiguration
= getGlobalSection().toConfigString()
+ getDefaultsSection().toConfigString()
+ section.toConfigString();
logger.fine("Publishing proxy configuration:\n" + proxyConfiguration);
File f = File.createTempFile("haproxyConfig", ".cfg");
try (FileWriter writer = new FileWriter(f)) {
writer.write(proxyConfiguration);
}
String remoteFile = "/tmp/" + f.getName();
remoteCommandUtils.copyRemoteFile(f.getAbsolutePath(), remoteFile, instance);
String remoteCommand = "cp " + remoteFile + " /etc/haproxy.cfg";
remoteCommandUtils.executeRemoteCommand(remoteCommand, instance);
}
/**
* Sets the instances that this proxy load balances between.
*
* @param instances
* The instances that this proxy will load balance between.
*/
public void setProxiedHosts(List<Instance> instances) {
this.proxiedInstances = instances;
}
/**
* Returns an HaproxyConfigurationSection object already set up with the
* defaults for the "global" section.
*
* @return An HaproxyConfigurationSection object already set up with the
* defaults for the "global" section.
*/
private HaproxyConfigurationSection getGlobalSection() {
HaproxyConfigurationSection section = new HaproxyConfigurationSection("global");
section.addProperty("log 127.0.0.1", "local0");
section.addProperty("log 127.0.0.1", "local1 notice");
section.addProperty("maxconn", "4096");
section.addProperty("user", "nobody");
section.addProperty("group", "nobody");
return section;
}
/**
* Returns an HaproxyConfigurationSection object already set up with the
* defaults for the "defaults" section.
*
* @return An HaproxyConfigurationSection object already set up with the
* defaults for the "defaults" section.
*/
private HaproxyConfigurationSection getDefaultsSection() {
HaproxyConfigurationSection section = new HaproxyConfigurationSection("defaults");
section.addProperty("log", "global");
section.addProperty("mode", "http");
section.addProperty("option", "httplog");
section.addProperty("option", "dontlognull");
section.addProperty("retries", "3");
section.addProperty("redispatch", "");
section.addProperty("maxconn", "2000");
section.addProperty("contimeout", "5000");
section.addProperty("clitimeout", "50000");
section.addProperty("srvtimeout", "50000");
return section;
}
/**
* Models the HAProxy configuration data for a "listen" section.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
private class HaproxyConfigurationListenSection extends HaproxyConfigurationSection {
private int serverCount = 1;
public HaproxyConfigurationListenSection(String sectionName, int port) {
super("listen " + sectionName);
this.addProperty("bind", ":" + port);
this.addProperty("balance", "roundrobin");
}
public void addServer(String server) {
this.addProperty("server s" + serverCount++, server);
}
}
/**
* Models an HAProxy configuration section.
*
* @author Jason Fulghum <fulghum@amazon.com>
*/
private class HaproxyConfigurationSection {
private final String sectionName;
private final List<String[]> properties = new ArrayList<>();
/**
* Creates a new object with the specified section name.
*
* @param sectionName
* The name of this section that all properties will be
* listed under.
*/
public HaproxyConfigurationSection(String sectionName) {
this.sectionName = sectionName;
}
/**
* Adds a property to this section. Note that multiple different
* properties can have the same key.
*
* @param key
* The name of the property being set.
* @param value
* The value of the property being set.
*/
public void addProperty(String key, String value) {
properties.add(new String[] {key, value});
}
/**
* Returns a string representation of this section, designed for use in
* an haproxy configuration file.
*
* @return A string representation of this section, designed for use in
* an haproxy configuration file.
*/
public String toConfigString() {
StringBuilder builder = new StringBuilder();
builder.append(sectionName + "\n");
for (String[] pair : properties) {
String key = pair[0];
String value = pair[1];
builder.append("\t" + key + " \t" + value + "\n");
}
builder.append("\n");
return builder.toString();
}
}
public void setInstance(Instance newInstance) {
this.instance = newInstance;
}
@Override
public void start() throws Exception {
startProxy();
}
@Override
public void stop() throws Exception {
// no-op since it's not needed yet
}
@Override
public void publish(File archiveFile, String moduleName) throws Exception {
// no-op since there's no content
}
}
| 7,270 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesis/AmazonKinesisRecordProducerSample.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.TimeUnit;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder;
import com.amazonaws.services.kinesis.model.CreateStreamRequest;
import com.amazonaws.services.kinesis.model.DescribeStreamRequest;
import com.amazonaws.services.kinesis.model.DescribeStreamResult;
import com.amazonaws.services.kinesis.model.ListStreamsRequest;
import com.amazonaws.services.kinesis.model.ListStreamsResult;
import com.amazonaws.services.kinesis.model.PutRecordRequest;
import com.amazonaws.services.kinesis.model.PutRecordResult;
import com.amazonaws.services.kinesis.model.ResourceNotFoundException;
import com.amazonaws.services.kinesis.model.StreamDescription;
public class AmazonKinesisRecordProducerSample {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
private static AmazonKinesis kinesis;
private static void init() throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
kinesis = AmazonKinesisClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
}
public static void main(String[] args) throws Exception {
init();
final String myStreamName = AmazonKinesisApplicationSample.SAMPLE_APPLICATION_STREAM_NAME;
final Integer myStreamSize = 1;
// Describe the stream and check if it exists.
DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest().withStreamName(myStreamName);
try {
StreamDescription streamDescription = kinesis.describeStream(describeStreamRequest).getStreamDescription();
System.out.printf("Stream %s has a status of %s.\n", myStreamName, streamDescription.getStreamStatus());
if ("DELETING".equals(streamDescription.getStreamStatus())) {
System.out.println("Stream is being deleted. This sample will now exit.");
System.exit(0);
}
// Wait for the stream to become active if it is not yet ACTIVE.
if (!"ACTIVE".equals(streamDescription.getStreamStatus())) {
waitForStreamToBecomeAvailable(myStreamName);
}
} catch (ResourceNotFoundException ex) {
System.out.printf("Stream %s does not exist. Creating it now.\n", myStreamName);
// Create a stream. The number of shards determines the provisioned throughput.
CreateStreamRequest createStreamRequest = new CreateStreamRequest();
createStreamRequest.setStreamName(myStreamName);
createStreamRequest.setShardCount(myStreamSize);
kinesis.createStream(createStreamRequest);
// The stream is now being created. Wait for it to become active.
waitForStreamToBecomeAvailable(myStreamName);
}
// List all of my streams.
ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
listStreamsRequest.setLimit(10);
ListStreamsResult listStreamsResult = kinesis.listStreams(listStreamsRequest);
List<String> streamNames = listStreamsResult.getStreamNames();
while (listStreamsResult.isHasMoreStreams()) {
if (streamNames.size() > 0) {
listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
}
listStreamsResult = kinesis.listStreams(listStreamsRequest);
streamNames.addAll(listStreamsResult.getStreamNames());
}
// Print all of my streams.
System.out.println("List of my streams: ");
for (int i = 0; i < streamNames.size(); i++) {
System.out.println("\t- " + streamNames.get(i));
}
System.out.printf("Putting records in stream : %s until this application is stopped...\n", myStreamName);
System.out.println("Press CTRL-C to stop.");
// Write records to the stream until this program is aborted.
while (true) {
long createTime = System.currentTimeMillis();
PutRecordRequest putRecordRequest = new PutRecordRequest();
putRecordRequest.setStreamName(myStreamName);
putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", createTime).getBytes()));
putRecordRequest.setPartitionKey(String.format("partitionKey-%d", createTime));
PutRecordResult putRecordResult = kinesis.putRecord(putRecordRequest);
System.out.printf("Successfully put record, partition key : %s, ShardID : %s, SequenceNumber : %s.\n",
putRecordRequest.getPartitionKey(),
putRecordResult.getShardId(),
putRecordResult.getSequenceNumber());
}
}
private static void waitForStreamToBecomeAvailable(String myStreamName) throws InterruptedException {
System.out.printf("Waiting for %s to become ACTIVE...\n", myStreamName);
long startTime = System.currentTimeMillis();
long endTime = startTime + TimeUnit.MINUTES.toMillis(10);
while (System.currentTimeMillis() < endTime) {
Thread.sleep(TimeUnit.SECONDS.toMillis(20));
try {
DescribeStreamRequest describeStreamRequest = new DescribeStreamRequest();
describeStreamRequest.setStreamName(myStreamName);
// ask for no more than 10 shards at a time -- this is an optional parameter
describeStreamRequest.setLimit(10);
DescribeStreamResult describeStreamResponse = kinesis.describeStream(describeStreamRequest);
String streamStatus = describeStreamResponse.getStreamDescription().getStreamStatus();
System.out.printf("\t- current state: %s\n", streamStatus);
if ("ACTIVE".equals(streamStatus)) {
return;
}
} catch (ResourceNotFoundException ex) {
// ResourceNotFound means the stream doesn't exist yet,
// so ignore this error and just keep polling.
} catch (AmazonServiceException ase) {
throw ase;
}
}
throw new RuntimeException(String.format("Stream %s never became active", myStreamName));
}
}
| 7,271 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesis/AmazonKinesisApplicationRecordProcessorFactory.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessor;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorFactory;
/**
* Used to create new record processors.
*/
public class AmazonKinesisApplicationRecordProcessorFactory implements IRecordProcessorFactory {
/**
* {@inheritDoc}
*/
@Override
public IRecordProcessor createProcessor() {
return new AmazonKinesisApplicationSampleRecordProcessor();
}
}
| 7,272 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesis/AmazonKinesisApplicationSample.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.net.InetAddress;
import java.util.UUID;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.AmazonKinesisClientBuilder;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorFactory;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.KinesisClientLibConfiguration;
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.Worker;
import com.amazonaws.services.kinesis.model.ResourceNotFoundException;
/**
* Sample Amazon Kinesis Application.
*/
public final class AmazonKinesisApplicationSample {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static final String SAMPLE_APPLICATION_STREAM_NAME = "myFirstStream";
private static final String SAMPLE_APPLICATION_NAME = "SampleKinesisApplication";
// Initial position in the stream when the application starts up for the first time.
// Position can be one of LATEST (most recent data) or TRIM_HORIZON (oldest available data)
private static final InitialPositionInStream SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM =
InitialPositionInStream.LATEST;
private static ProfileCredentialsProvider credentialsProvider;
private static void init() {
// Ensure the JVM will refresh the cached IP values of AWS resources (e.g. service endpoints).
java.security.Security.setProperty("networkaddress.cache.ttl", "60");
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.", e);
}
}
public static void main(String[] args) throws Exception {
init();
if (args.length == 1 && "delete-resources".equals(args[0])) {
deleteResources();
return;
}
String workerId = InetAddress.getLocalHost().getCanonicalHostName() + ":" + UUID.randomUUID();
KinesisClientLibConfiguration kinesisClientLibConfiguration =
new KinesisClientLibConfiguration(SAMPLE_APPLICATION_NAME,
SAMPLE_APPLICATION_STREAM_NAME,
credentialsProvider,
workerId);
kinesisClientLibConfiguration.withInitialPositionInStream(SAMPLE_APPLICATION_INITIAL_POSITION_IN_STREAM);
IRecordProcessorFactory recordProcessorFactory = new AmazonKinesisApplicationRecordProcessorFactory();
Worker worker = new Worker(recordProcessorFactory, kinesisClientLibConfiguration);
System.out.printf("Running %s to process stream %s as worker %s...\n",
SAMPLE_APPLICATION_NAME,
SAMPLE_APPLICATION_STREAM_NAME,
workerId);
int exitCode = 0;
try {
worker.run();
} catch (Throwable t) {
System.err.println("Caught throwable while processing data.");
t.printStackTrace();
exitCode = 1;
}
System.exit(exitCode);
}
public static void deleteResources() {
// Delete the stream
AmazonKinesis kinesis = AmazonKinesisClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
System.out.printf("Deleting the Amazon Kinesis stream used by the sample. Stream Name = %s.\n",
SAMPLE_APPLICATION_STREAM_NAME);
try {
kinesis.deleteStream(SAMPLE_APPLICATION_STREAM_NAME);
} catch (ResourceNotFoundException ex) {
// The stream doesn't exist.
}
// Delete the table
AmazonDynamoDB dynamoDB = AmazonDynamoDBClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
System.out.printf("Deleting the Amazon DynamoDB table used by the Amazon Kinesis Client Library. Table Name = %s.\n",
SAMPLE_APPLICATION_NAME);
try {
dynamoDB.deleteTable(SAMPLE_APPLICATION_NAME);
} catch (com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException ex) {
// The table doesn't exist.
}
}
}
| 7,273 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesis/AmazonKinesisApplicationSampleRecordProcessor.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.InvalidStateException;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.ShutdownException;
import com.amazonaws.services.kinesis.clientlibrary.exceptions.ThrottlingException;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessor;
import com.amazonaws.services.kinesis.clientlibrary.interfaces.IRecordProcessorCheckpointer;
import com.amazonaws.services.kinesis.clientlibrary.types.ShutdownReason;
import com.amazonaws.services.kinesis.model.Record;
/**
* Processes records and checkpoints progress.
*/
public class AmazonKinesisApplicationSampleRecordProcessor implements IRecordProcessor {
private static final Log LOG = LogFactory.getLog(AmazonKinesisApplicationSampleRecordProcessor.class);
private String kinesisShardId;
// Backoff and retry settings
private static final long BACKOFF_TIME_IN_MILLIS = 3000L;
private static final int NUM_RETRIES = 10;
// Checkpoint about once a minute
private static final long CHECKPOINT_INTERVAL_MILLIS = 60000L;
private long nextCheckpointTimeInMillis;
private final CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
/**
* {@inheritDoc}
*/
@Override
public void initialize(String shardId) {
LOG.info("Initializing record processor for shard: " + shardId);
this.kinesisShardId = shardId;
}
/**
* {@inheritDoc}
*/
@Override
public void processRecords(List<Record> records, IRecordProcessorCheckpointer checkpointer) {
LOG.info("Processing " + records.size() + " records from " + kinesisShardId);
// Process records and perform all exception handling.
processRecordsWithRetries(records);
// Checkpoint once every checkpoint interval.
if (System.currentTimeMillis() > nextCheckpointTimeInMillis) {
checkpoint(checkpointer);
nextCheckpointTimeInMillis = System.currentTimeMillis() + CHECKPOINT_INTERVAL_MILLIS;
}
}
/**
* Process records performing retries as needed. Skip "poison pill" records.
*
* @param records Data records to be processed.
*/
private void processRecordsWithRetries(List<Record> records) {
for (Record record : records) {
boolean processedSuccessfully = false;
for (int i = 0; i < NUM_RETRIES; i++) {
try {
//
// Logic to process record goes here.
//
processSingleRecord(record);
processedSuccessfully = true;
break;
} catch (Throwable t) {
LOG.warn("Caught throwable while processing record " + record, t);
}
// backoff if we encounter an exception.
try {
Thread.sleep(BACKOFF_TIME_IN_MILLIS);
} catch (InterruptedException e) {
LOG.debug("Interrupted sleep", e);
}
}
if (!processedSuccessfully) {
LOG.error("Couldn't process record " + record + ". Skipping the record.");
}
}
}
/**
* Process a single record.
*
* @param record The record to be processed.
*/
private void processSingleRecord(Record record) {
// TODO Add your own record processing logic here
String data = null;
try {
// For this app, we interpret the payload as UTF-8 chars.
data = decoder.decode(record.getData()).toString();
// Assume this record came from AmazonKinesisSample and log its age.
long recordCreateTime = new Long(data.substring("testData-".length()));
long ageOfRecordInMillis = System.currentTimeMillis() - recordCreateTime;
LOG.info(record.getSequenceNumber() + ", " + record.getPartitionKey() + ", " + data + ", Created "
+ ageOfRecordInMillis + " milliseconds ago.");
} catch (NumberFormatException e) {
LOG.info("Record does not match sample record format. Ignoring record with data; " + data);
} catch (CharacterCodingException e) {
LOG.error("Malformed data: " + data, e);
}
}
/**
* {@inheritDoc}
*/
@Override
public void shutdown(IRecordProcessorCheckpointer checkpointer, ShutdownReason reason) {
LOG.info("Shutting down record processor for shard: " + kinesisShardId);
// Important to checkpoint after reaching end of shard, so we can start processing data from child shards.
if (reason == ShutdownReason.TERMINATE) {
checkpoint(checkpointer);
}
}
/** Checkpoint with retries.
* @param checkpointer
*/
private void checkpoint(IRecordProcessorCheckpointer checkpointer) {
LOG.info("Checkpointing shard " + kinesisShardId);
for (int i = 0; i < NUM_RETRIES; i++) {
try {
checkpointer.checkpoint();
break;
} catch (ShutdownException se) {
// Ignore checkpoint if the processor instance has been shutdown (fail over).
LOG.info("Caught shutdown exception, skipping checkpoint.", se);
break;
} catch (ThrottlingException e) {
// Backoff and re-attempt checkpoint upon transient failures
if (i >= (NUM_RETRIES - 1)) {
LOG.error("Checkpoint failed after " + (i + 1) + "attempts.", e);
break;
} else {
LOG.info("Transient issue when checkpointing - attempt " + (i + 1) + " of "
+ NUM_RETRIES, e);
}
} catch (InvalidStateException e) {
// This indicates an issue with the DynamoDB table (check for table, provisioned IOPS).
LOG.error("Cannot save checkpoint to the DynamoDB table used by the Amazon Kinesis Client Library.", e);
break;
}
try {
Thread.sleep(BACKOFF_TIME_IN_MILLIS);
} catch (InterruptedException e) {
LOG.debug("Interrupted sleep", e);
}
}
}
}
| 7,274 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonSimpleQueueService/SimpleQueueServiceSample.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.List;
import java.util.Map.Entry;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
/**
* This sample demonstrates how to make basic requests to Amazon SQS using the
* AWS SDK for Java.
* <p>
* <b>Prerequisites:</b> You must have a valid Amazon Web
* Services developer account, and be signed up to use Amazon SQS. For more
* information on Amazon SQS, see http://aws.amazon.com/sqs.
* <p>
* Fill in your AWS access credentials in the provided credentials file
* template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the credentials from.
* <p>
* <b>WARNING:</b> To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public class SimpleQueueServiceSample {
public static void main(String[] args) throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
AmazonSQS sqs = AmazonSQSClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(Regions.US_WEST_2)
.build();
System.out.println("===========================================");
System.out.println("Getting Started with Amazon SQS");
System.out.println("===========================================\n");
try {
// Create a queue
System.out.println("Creating a new SQS queue called MyQueue.\n");
CreateQueueRequest createQueueRequest = new CreateQueueRequest("MyQueue");
String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();
// List queues
System.out.println("Listing all queues in your account.\n");
for (String queueUrl : sqs.listQueues().getQueueUrls()) {
System.out.println(" QueueUrl: " + queueUrl);
}
System.out.println();
// Send a message
System.out.println("Sending a message to MyQueue.\n");
sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));
// Receive messages
System.out.println("Receiving messages from MyQueue.\n");
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
for (Message message : messages) {
System.out.println(" Message");
System.out.println(" MessageId: " + message.getMessageId());
System.out.println(" ReceiptHandle: " + message.getReceiptHandle());
System.out.println(" MD5OfBody: " + message.getMD5OfBody());
System.out.println(" Body: " + message.getBody());
for (Entry<String, String> entry : message.getAttributes().entrySet()) {
System.out.println(" Attribute");
System.out.println(" Name: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
System.out.println();
// Delete a message
System.out.println("Deleting a message.\n");
String messageReceiptHandle = messages.get(0).getReceiptHandle();
sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));
// Delete a queue
System.out.println("Deleting the test queue.\n");
sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it " +
"to Amazon SQS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered " +
"a serious internal problem while trying to communicate with SQS, such as not " +
"being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
}
| 7,275 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-Advanced/InlineTaggingCodeSampleApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
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.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
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.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
*/
public class InlineTaggingCodeSampleApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) {
//============================================================================================//
//=============================== Submitting a Request =======================================//
//============================================================================================//
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
// Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
//============================================================================================//
//=========================== Getting the Request ID from the Request ========================//
//============================================================================================//
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.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());
}
//============================================================================================//
//====================================== Tag the Spot Requests ===============================//
//============================================================================================//
// Create the list of tags we want to create
ArrayList<Tag> requestTags = new ArrayList<Tag>();
requestTags.add(new Tag("keyname1","value1"));
// Create a tag request for requests.
CreateTagsRequest createTagsRequest_requests = new CreateTagsRequest();
createTagsRequest_requests.setResources(spotInstanceRequestIds);
createTagsRequest_requests.setTags(requestTags);
// Try to tag the Spot request submitted.
try {
ec2.createTags(createTagsRequest_requests);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=========================== Determining the State of the Spot Request ======================//
//============================================================================================//
// Create a variable that will track whether there are any requests still in the open state.
boolean anyOpen;
// Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there are no requests open unless
// we find one that is still open.
anyOpen=false;
try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
anyOpen = true;
}
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
}
} while (anyOpen);
//============================================================================================//
//====================================== Tag the Spot Instances ===============================//
//============================================================================================//
// Create the list of tags we want to create
ArrayList<Tag> instanceTags = new ArrayList<Tag>();
instanceTags.add(new Tag("keyname1","value1"));
// Create a tag request for instances.
CreateTagsRequest createTagsRequest_instances = new CreateTagsRequest();
createTagsRequest_instances.setResources(instanceIds);
createTagsRequest_instances.setTags(instanceTags);
// Try to tag the Spot instance started.
try {
ec2.createTags(createTagsRequest_instances);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//====================================== Canceling the Request ==============================//
//============================================================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=================================== Terminating any Instances ==============================//
//============================================================================================//
try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
}
}
| 7,276 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-Advanced/GettingStartedApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.ArrayList;
import java.util.Calendar;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.ec2.model.Tag;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
*/
public class GettingStartedApp {
private static final long SLEEP_CYCLE = 5000;
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) throws Exception {
System.out.println("===========================================");
System.out.println("Welcome to the AWS Java SDK!");
System.out.println("===========================================");
/*
* Amazon EC2
*
* The AWS EC2 client allows you to create, delete, and administer
* instances programmatically.
*
* In this sample, we use an EC2 client to submit a Spot request,
* wait for it to reach the active state, and then cancel and terminate
* the associated instance.
*/
try {
// Setup the helper object that will perform all of the API calls.
Requests requests = new Requests("t1.micro","ami-8c1fece5","0.03","GettingStartedGroup");
// Submit all of the requests.
requests.submitRequests();
// Create the list of tags we want to create and tag any associated requests.
ArrayList<Tag> tags = new ArrayList<Tag>();
tags.add(new Tag("keyname1","value1"));
requests.tagRequests(tags);
// Initialize the timer to now.
Calendar startTimer = Calendar.getInstance();
Calendar nowTimer = null;
// Loop through all of the requests until all bids are in the active state
// (or at least not in the open state).
do
{
// Sleep for 60 seconds.
Thread.sleep(SLEEP_CYCLE);
// Initialize the timer to now, and then subtract 15 minutes, so we can
// compare to see if we have exceeded 15 minutes compared to the startTime.
nowTimer = Calendar.getInstance();
nowTimer.add(Calendar.MINUTE, -15);
} while (requests.areAnyOpen() && !nowTimer.after(startTimer));
// If we couldn't launch Spot within the timeout period, then we should launch an On-Demand
// Instance.
if (nowTimer.after(startTimer)) {
// Cancel all requests because we timed out.
requests.cleanup();
// Launch On-Demand instances instead
requests.launchOnDemand();
}
// Tag any created instances.
requests.tagInstances(tags);
// Cancel all requests and terminate all running instances.
requests.cleanup();
} catch (AmazonServiceException ase) {
// Write out any exceptions that may have occurred.
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
}
}
| 7,277 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-Advanced/Requests.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.BlockDeviceMapping;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
import com.amazonaws.services.ec2.model.EbsBlockDevice;
import com.amazonaws.services.ec2.model.Instance;
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.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.SpotPlacement;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
public class Requests {
private AmazonEC2 ec2;
private ArrayList<String> instanceIds;
private ArrayList<String> spotInstanceRequestIds;
private String instanceType;
private String amiID;
private String bidPrice;
private String securityGroup;
private String placementGroupName;
private boolean deleteOnTermination;
private String availabilityZoneName;
private String availabilityZoneGroupName;
private String launchGroupName;
private Date validFrom;
private Date validTo;
private String requestType;
/**
* Public constructor.
* @throws Exception
*/
public Requests (String instanceType, String amiID, String bidPrice, String securityGroup) throws Exception {
init(instanceType, amiID, bidPrice,securityGroup);
}
/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.PropertiesCredentials
* @see com.amazonaws.ClientConfiguration
*/
private void init(String instanceType, String amiID, String bidPrice, String securityGroup) throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
this.instanceType = instanceType;
this.amiID = amiID;
this.bidPrice = bidPrice;
this.securityGroup = securityGroup;
this.deleteOnTermination = true;
this.placementGroupName = null;
}
/**
* The submit method will create 1 x one-time t1.micro request with a maximum bid
* price of $0.03 using the Amazon Linux AMI.
*
* Note the AMI id may change after the release of this code sample, and it is important
* to use the latest. You can find the latest version by logging into the AWS Management
* console, and attempting to perform a launch. You will be presented with AMI options,
* one of which will be Amazon Linux. Simply use that AMI id.
*/
public void submitRequests() {
//==========================================================================//
//================= Submit a Spot Instance Request =====================//
//==========================================================================//
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice(bidPrice);
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId(amiID);
launchSpecification.setInstanceType(instanceType);
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add(securityGroup);
launchSpecification.setSecurityGroups(securityGroups);
// If a placement group has been set, then we will use it in the request.
if (placementGroupName != null && !placementGroupName.equals("")) {
// Setup the placement group to use with whatever name you desire.
SpotPlacement placement = new SpotPlacement();
placement.setGroupName(placementGroupName);
launchSpecification.setPlacement(placement);
}
// Check to see if we need to set the availability zone name.
if (availabilityZoneName != null && !availabilityZoneName.equals("")) {
// Setup the availability zone to use. Note we could retrieve the availability
// zones using the ec2.describeAvailabilityZones() API.
SpotPlacement placement = new SpotPlacement(availabilityZoneName);
launchSpecification.setPlacement(placement);
}
if (availabilityZoneGroupName != null && !availabilityZoneGroupName.equals("")) {
// Set the availability zone group.
requestRequest.setAvailabilityZoneGroup(availabilityZoneGroupName);
}
// Check to see if we need to set the launch group.
if (launchGroupName != null && !launchGroupName.equals("")) {
// Set the availability launch group.
requestRequest.setLaunchGroup(launchGroupName);
}
// Check to see if we need to set the valid from option.
if (validFrom != null) {
requestRequest.setValidFrom(validFrom);
}
// Check to see if we need to set the valid until option.
if (validTo != null) {
requestRequest.setValidUntil(validFrom);
}
// Check to see if we need to set the request type.
if (requestType != null && !requestType.equals("")) {
// Set the type of the bid.
requestRequest.setType(requestType);
}
// If we should delete the EBS boot partition on termination.
if (!deleteOnTermination) {
// Create the block device mapping to describe the root partition.
BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
blockDeviceMapping.setDeviceName("/dev/sda1");
// Set the delete on termination flag to false.
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setDeleteOnTermination(Boolean.FALSE);
blockDeviceMapping.setEbs(ebs);
// Add the block device mapping to the block list.
ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
blockList.add(blockDeviceMapping);
// Set the block device mapping configuration in the launch specifications.
launchSpecification.setBlockDeviceMappings(blockList);
}
// Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.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.
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());
}
}
public void launchOnDemand () {
//============================================================================================//
//====================================== Launch an On-Demand Instance ========================//
//====================================== If we Didn't Get a Spot Instance ====================//
//============================================================================================//
// Setup the request for 1 x t1.micro using the same security group and
// AMI id as the Spot request.
RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
runInstancesRequest.setInstanceType(instanceType);
runInstancesRequest.setImageId(amiID);
runInstancesRequest.setMinCount(Integer.valueOf(1));
runInstancesRequest.setMaxCount(Integer.valueOf(1));
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add(securityGroup);
runInstancesRequest.setSecurityGroups(securityGroups);
// Launch the instance.
RunInstancesResult runResult = ec2.runInstances(runInstancesRequest);
// Add the instance id into the instance id list, so we can potentially later
// terminate that list.
for (Instance instance: runResult.getReservation().getInstances()) {
System.out.println("Launched On-Demand Instace: "+instance.getInstanceId());
instanceIds.add(instance.getInstanceId());
}
}
/**
* The areOpen method will determine if any of the requests that were started are still
* in the open state. If all of them have transitioned to either active, cancelled, or
* closed, then this will return false.
* @return
*/
public boolean areAnyOpen() {
//==========================================================================//
//============== Describe Spot Instance Requests to determine =============//
//==========================================================================//
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
System.out.println("Checking to determine if Spot Bids have reached the active state...");
// Initialize variables.
instanceIds = new ArrayList<String>();
try
{
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
System.out.println(" " +describeResponse.getSpotInstanceRequestId() +
" is in the "+describeResponse.getState() + " state.");
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
return true;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// Print out the error.
System.out.println("Error when calling describeSpotInstances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
return true;
}
return false;
}
/**
* Tag any of the resources we specify.
* @param resources
* @param tags
*/
private void tagResources(List<String> resources, List<Tag> tags) {
// Create a tag request.
CreateTagsRequest createTagsRequest = new CreateTagsRequest();
createTagsRequest.setResources(resources);
createTagsRequest.setTags(tags);
// Try to tag the Spot request submitted.
try {
ec2.createTags(createTagsRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
}
/**
* Tags all of the instances started with this object with the tags specified.
* @param tags
*/
public void tagInstances(List<Tag> tags) {
tagResources(instanceIds, tags);
}
/**
* Tags all of the requests started with this object with the tags specified.
* @param tags
*/
public void tagRequests(List<Tag> tags) {
tagResources(spotInstanceRequestIds, tags);
}
/**
* The cleanup method will cancel and active requests and terminate any running instances
* that were created using this object.
*/
public void cleanup () {
//==========================================================================//
//================= Cancel/Terminate Your Spot Request =====================//
//==========================================================================//
try {
// Cancel requests.
System.out.println("Cancelling requests.");
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
try {
// Terminate instances.
System.out.println("Terminate instances");
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
// Delete all requests and instances that we have terminated.
instanceIds.clear();
spotInstanceRequestIds.clear();
}
/**
* Sets the request type to either persistent or one-time.
*/
public void setRequestType(String type) {
this.requestType = type;
}
/**
* Sets the valid to and from time. If you set either value to null
* or "" then the period will not be set.
* @param from
* @param to
*/
public void setValidPeriod(Date from, Date to) {
this.validFrom = from;
this.validTo = to;
}
/**
* Sets the launch group to be used. If you set this to null
* or "" then launch group will be used.
* @param az
*/
public void setLaunchGroup(String launchGroup) {
this.launchGroupName = launchGroup;
}
/**
* Sets the availability zone group to be used. If you set this to null
* or "" then availability zone group will be used.
* @param az
*/
public void setAvailabilityZoneGroup(String azGroup) {
this.availabilityZoneGroupName = azGroup;
}
/**
* Sets the availability zone to be used. If you set this to null
* or "" then availability zone will be used.
* @param az
*/
public void setAvailabilityZone(String az) {
this.availabilityZoneName = az;
}
/**
* Sets the placementGroupName to be used. If you set this to null
* or "" then no placementgroup will be used.
* @param pg
*/
public void setPlacementGroup(String pg) {
this.placementGroupName = pg;
}
/**
* This sets the deleteOnTermination flag, so that we can determine whether or not
* we should delete the root partition if the instance is interrupted or terminated.
* @param terminate
*/
public void setDeleteOnTermination(boolean terminate) {
this.deleteOnTermination = terminate;
}
}
| 7,278 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-Advanced/CreateSecurityGroupApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupResult;
import com.amazonaws.services.ec2.model.IpPermission;
public class CreateSecurityGroupApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Create a new security group.
try {
CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
"GettingStartedGroup", "Getting Started Security Group");
CreateSecurityGroupResult result = ec2
.createSecurityGroup(securityGroupRequest);
System.out.println(String.format("Security group created: [%s]",
result.getGroupId()));
} catch (AmazonServiceException ase) {
// Likely this means that the group is already created, so ignore.
System.out.println(ase.getMessage());
}
String ipAddr = "0.0.0.0/0";
// Get the IP of the current host, so that we can limit the Security Group
// by default to the ip range associated with your subnet.
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
ipAddr = addr.getHostAddress()+"/10";
} catch (UnknownHostException e) {
}
// Create a range that you would like to populate.
List<String> ipRanges = Collections.singletonList(ipAddr);
// Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
IpPermission ipPermission = new IpPermission()
.withIpProtocol("tcp")
.withFromPort(new Integer(22))
.withToPort(new Integer(22))
.withIpRanges(ipRanges);
List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);
try {
// Authorize the ports to the used.
AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
"GettingStartedGroup", ipPermissions);
ec2.authorizeSecurityGroupIngress(ingressRequest);
System.out.println(String.format("Ingress port authroized: [%s]",
ipPermissions.toString()));
} catch (AmazonServiceException ase) {
// Ignore because this likely means the zone has already been authorized.
System.out.println(ase.getMessage());
}
}
}
| 7,279 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-Advanced/InlineGettingStartedCodeSampleApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.BlockDeviceMapping;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
import com.amazonaws.services.ec2.model.EbsBlockDevice;
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.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.SpotPlacement;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
*/
public class InlineGettingStartedCodeSampleApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) {
//============================================================================================//
//=============================== Submitting a Request =======================================//
//============================================================================================//
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
//*************************** Required Parameters Settings ************************//
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
//*************************** Bid Type Settings ************************//
// Set the type of the bid to persistent.
requestRequest.setType("persistent");
//*************************** Valid From/To Settings ************************//
// Set the valid start time to be two minutes from now.
Calendar from = Calendar.getInstance();
from.add(Calendar.MINUTE, 2);
requestRequest.setValidFrom(from.getTime());
// Set the valid end time to be two minutes and two hours from now.
Calendar until = (Calendar) from.clone();
until.add(Calendar.HOUR, 2);
requestRequest.setValidUntil(until.getTime());
//*************************** Launch Group Settings ************************//
// Set the launch group.
requestRequest.setLaunchGroup("ADVANCED-DEMO-LAUNCH-GROUP");
//*************************** Availability Zone Group Settings ************************//
// Set the availability zone group.
requestRequest.setAvailabilityZoneGroup("ADVANCED-DEMO-AZ-GROUP");
//*************************** Add the block device mapping ************************//
// Goal: Setup block device mappings to ensure that we will not delete
// the root partition on termination.
// Create the block device mapping to describe the root partition.
BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
blockDeviceMapping.setDeviceName("/dev/sda1");
// Set the delete on termination flag to false.
EbsBlockDevice ebs = new EbsBlockDevice();
ebs.setDeleteOnTermination(Boolean.FALSE);
blockDeviceMapping.setEbs(ebs);
// Add the block device mapping to the block list.
ArrayList<BlockDeviceMapping> blockList = new ArrayList<BlockDeviceMapping>();
blockList.add(blockDeviceMapping);
// Set the block device mapping configuration in the launch specifications.
launchSpecification.setBlockDeviceMappings(blockList);
//*************************** Add the availability zone ************************//
// Setup the availability zone to use. Note we could retrieve the availability
// zones using the ec2.describeAvailabilityZones() API. For this demo we will just use
// us-east-1b.
SpotPlacement placement = new SpotPlacement("us-east-1b");
launchSpecification.setPlacement(placement);
//*************************** Add the placement group ************************//
// Setup the placement group to use with whatever name you desire.
// For this demo we will just use "ADVANCED-DEMO-PLACEMENT-GROUP".
// Note: We have commented this out, because we are not leveraging cc1.4xlarge or
// cg1.4xlarge in this example.
/*
SpotPlacement pg = new SpotPlacement();
pg.setGroupName("ADVANCED-DEMO-PLACEMENT-GROUP");
launchSpecification.setPlacement(pg);
*/
//*************************** Add the launch specification ************************//
// Add the launch specification.
requestRequest.setLaunchSpecification(launchSpecification);
//============================================================================================//
//=========================== Getting the Request ID from the Request ========================//
//============================================================================================//
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.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());
}
//============================================================================================//
//=========================== Determining the State of the Spot Request ======================//
//============================================================================================//
// Create a variable that will track whether there are any requests still in the open state.
boolean anyOpen;
// Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there are no requests open unless
// we find one that is still open.
anyOpen=false;
try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
anyOpen = true;
}
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
}
} while (anyOpen);
//============================================================================================//
//====================================== Canceling the Request ==============================//
//============================================================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=================================== Terminating any Instances ==============================//
//============================================================================================//
try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
}
}
| 7,280 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonS3TransferProgress/S3TransferProgressSample.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.TransferManagerBuilder;
import com.amazonaws.services.s3.transfer.Upload;
import com.amazonaws.util.StringUtils;
/**
* Demonstrates how to upload data to Amazon S3, and track progress, using a
* Swing progress bar.
* <p>
* <b>Prerequisites:</b> You must have a valid Amazon Web Services developer
* account, and be signed up to use Amazon S3. For more information on Amazon
* S3, see http://aws.amazon.com/s3.
* <p>
* Fill in your AWS access credentials in the provided credentials file
* template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the credentials from.
* <p>
* <b>WARNING:</b> To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*
* http://aws.amazon.com/security-credentials
*/
public class S3TransferProgressSample {
private static ProfileCredentialsProvider credentialsProvider = null;
private static TransferManager tx;
private static String bucketName;
private JProgressBar pb;
private JFrame frame;
private Upload upload;
private JButton button;
public static void main(String[] args) throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*
* TransferManager manages a pool of threads, so we create a
* single instance and share it throughout our application.
*/
credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
tx = TransferManagerBuilder.standard()
.withS3Client(s3)
.build();
final String accessKeyId = credentialsProvider.getCredentials().getAWSAccessKeyId();
bucketName = "s3-upload-sdk-sample-" + StringUtils.lowerCase(accessKeyId);
new S3TransferProgressSample();
}
public S3TransferProgressSample() throws Exception {
frame = new JFrame("Amazon S3 File Upload");
button = new JButton("Choose File...");
button.addActionListener(new ButtonListener());
pb = new JProgressBar(0, 100);
pb.setStringPainted(true);
frame.setContentPane(createContentPane());
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int showOpenDialog = fileChooser.showOpenDialog(frame);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) return;
createAmazonS3Bucket();
ProgressListener progressListener = new ProgressListener() {
public void progressChanged(ProgressEvent progressEvent) {
if (upload == null) return;
pb.setValue((int)upload.getProgress().getPercentTransferred());
switch (progressEvent.getEventCode()) {
case ProgressEvent.COMPLETED_EVENT_CODE:
pb.setValue(100);
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;
}
}
};
File fileToUpload = fileChooser.getSelectedFile();
PutObjectRequest request = new PutObjectRequest(
bucketName, fileToUpload.getName(), fileToUpload)
.withGeneralProgressListener(progressListener);
upload = tx.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() {
JPanel panel = new JPanel();
panel.add(button);
panel.add(pb);
JPanel borderPanel = new JPanel();
borderPanel.setLayout(new BorderLayout());
borderPanel.add(panel, BorderLayout.NORTH);
borderPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
return borderPanel;
}
}
| 7,281 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-GettingStarted/GettingStartedApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import com.amazonaws.AmazonServiceException;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
*/
public class GettingStartedApp {
private static final long SLEEP_CYCLE = 60000;
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) throws Exception {
System.out.println("===========================================");
System.out.println("Welcome to the AWS Java SDK!");
System.out.println("===========================================");
/*
* Amazon EC2
*
* The AWS EC2 client allows you to create, delete, and administer
* instances programmatically.
*
* In this sample, we use an EC2 client to submit a Spot request,
* wait for it to reach the active state, and then cancel and terminate
* the associated instance.
*/
try {
// Setup the helper object that will perform all of the API calls.
Requests requests = new Requests();
// Submit all of the requests.
requests.submitRequests();
// Loop through all of the requests until all bids are in the active state
// (or at least not in the open state).
do
{
// Sleep for 60 seconds.
Thread.sleep(SLEEP_CYCLE);
} while (requests.areAnyOpen());
// Cancel all requests and terminate all running instances.
requests.cleanup();
} catch (AmazonServiceException ase) {
// Write out any exceptions that may have occurred.
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
}
}
| 7,282 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-GettingStarted/Requests.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
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.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
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.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
public class Requests {
private AmazonEC2 ec2;
private ArrayList<String> instanceIds;
private ArrayList<String> spotInstanceRequestIds;
/**
* Public constructor.
* @throws Exception
*/
public Requests () throws Exception {
init();
}
/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.PropertiesCredentials
* @see com.amazonaws.ClientConfiguration
*/
private void init() throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
}
/**
* The submit method will create 1 x one-time t1.micro request with a maximum bid
* price of $0.03 using the Amazon Linux AMI.
*
* Note the AMI id may change after the release of this code sample, and it is important
* to use the latest. You can find the latest version by logging into the AWS Management
* console, and attempting to perform a launch. You will be presented with AMI options,
* one of which will be Amazon Linux. Simply use that AMI id.
*/
public void submitRequests() {
//==========================================================================//
//================= Submit a Spot Instance Request =====================//
//==========================================================================//
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
// Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.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.
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());
}
}
/**
* The areOpen method will determine if any of the requests that were started are still
* in the open state. If all of them have transitioned to either active, cancelled, or
* closed, then this will return false.
* @return
*/
public boolean areAnyOpen() {
//==========================================================================//
//============== Describe Spot Instance Requests to determine =============//
//==========================================================================//
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
System.out.println("Checking to determine if Spot Bids have reached the active state...");
// Initialize variables.
instanceIds = new ArrayList<String>();
try
{
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
System.out.println(" " +describeResponse.getSpotInstanceRequestId() +
" is in the "+describeResponse.getState() + " state.");
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
return true;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// Print out the error.
System.out.println("Error when calling describeSpotInstances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
return true;
}
return false;
}
/**
* The cleanup method will cancel and active requests and terminate any running instances
* that were created using this object.
*/
public void cleanup () {
//==========================================================================//
//================= Cancel/Terminate Your Spot Request =====================//
//==========================================================================//
try {
// Cancel requests.
System.out.println("Cancelling requests.");
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
try {
// Terminate instances.
System.out.println("Terminate instances");
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
// Delete all requests and instances that we have terminated.
instanceIds.clear();
spotInstanceRequestIds.clear();
}
}
| 7,283 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-GettingStarted/CreateSecurityGroupApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
import com.amazonaws.services.ec2.model.CreateSecurityGroupResult;
import com.amazonaws.services.ec2.model.IpPermission;
public class CreateSecurityGroupApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Create a new security group.
try {
CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
"GettingStartedGroup", "Getting Started Security Group");
CreateSecurityGroupResult result = ec2
.createSecurityGroup(securityGroupRequest);
System.out.println(String.format("Security group created: [%s]",
result.getGroupId()));
} catch (AmazonServiceException ase) {
// Likely this means that the group is already created, so ignore.
System.out.println(ase.getMessage());
}
String ipAddr = "0.0.0.0/0";
// Get the IP of the current host, so that we can limit the Security Group
// by default to the ip range associated with your subnet.
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
ipAddr = addr.getHostAddress()+"/10";
} catch (UnknownHostException e) {
}
// Create a range that you would like to populate.
List<String> ipRanges = Collections.singletonList(ipAddr);
// Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
IpPermission ipPermission = new IpPermission()
.withIpProtocol("tcp")
.withFromPort(new Integer(22))
.withToPort(new Integer(22))
.withIpRanges(ipRanges);
List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);
try {
// Authorize the ports to the used.
AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
"GettingStartedGroup", ipPermissions);
ec2.authorizeSecurityGroupIngress(ingressRequest);
System.out.println(String.format("Ingress port authroized: [%s]",
ipPermissions.toString()));
} catch (AmazonServiceException ase) {
// Ignore because this likely means the zone has already been authorized.
System.out.println(ase.getMessage());
}
}
}
| 7,284 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonEC2SpotInstances-GettingStarted/InlineGettingStartedCodeSampleApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
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.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.CancelSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsRequest;
import com.amazonaws.services.ec2.model.DescribeSpotInstanceRequestsResult;
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.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.TerminateInstancesRequest;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
*/
public class InlineGettingStartedCodeSampleApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) {
//============================================================================================//
//=============================== Submitting a Request =======================================//
//============================================================================================//
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
// Initializes a Spot Instance Request
RequestSpotInstancesRequest requestRequest = new RequestSpotInstancesRequest();
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the instance type (e.g. t1.micro)
// and the latest Amazon Linux AMI id available. Note, you should always use the latest
// Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
// Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
// Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
//============================================================================================//
//=========================== Getting the Request ID from the Request ========================//
//============================================================================================//
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.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());
}
//============================================================================================//
//=========================== Determining the State of the Spot Request ======================//
//============================================================================================//
// Create a variable that will track whether there are any requests still in the open state.
boolean anyOpen;
// Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with tall of the request id to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpotInstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there are no requests open unless
// we find one that is still open.
anyOpen=false;
try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeSpotInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.getSpotInstanceRequests();
// Look through each request and determine if they are all in the active state.
for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we attempted to request it.
// There is the potential for it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
}
// Add the instance id to the list we will eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of the loop.
// This prevents the scenario where there was blip on the wire.
anyOpen = true;
}
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
// Do nothing because it woke up early.
}
} while (anyOpen);
//============================================================================================//
//====================================== Canceling the Request ==============================//
//============================================================================================//
try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
//============================================================================================//
//=================================== Terminating any Instances ==============================//
//============================================================================================//
try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(instanceIds);
ec2.terminateInstances(terminateRequest);
} catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
}
}
| 7,285 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonSimpleEmailService/AmazonSESSample.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.IOException;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailService;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder;
import com.amazonaws.services.simpleemail.model.Body;
import com.amazonaws.services.simpleemail.model.Content;
import com.amazonaws.services.simpleemail.model.Destination;
import com.amazonaws.services.simpleemail.model.Message;
import com.amazonaws.services.simpleemail.model.SendEmailRequest;
public class AmazonSESSample {
static final String FROM = "SENDER@EXAMPLE.COM"; // Replace with your "From" address. This address must be verified.
static final String TO = "RECIPIENT@EXAMPLE.COM"; // Replace with a "To" address. If you have not yet requested
// production access, this address must be verified.
static final String BODY = "This email was sent through Amazon SES by using the AWS SDK for Java.";
static final String SUBJECT = "Amazon SES test (AWS SDK for Java)";
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public static void main(String[] args) throws IOException {
// Construct an object to contain the recipient address.
Destination destination = new Destination().withToAddresses(new String[]{TO});
// Create the subject and body of the message.
Content subject = new Content().withData(SUBJECT);
Content textBody = new Content().withData(BODY);
Body body = new Body().withText(textBody);
// Create a message with the specified subject and body.
Message message = new Message().withSubject(subject).withBody(body);
// Assemble the email.
SendEmailRequest request = new SendEmailRequest().withSource(FROM).withDestination(destination).withMessage(message);
try {
System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*
* TransferManager manages a pool of threads, so we create a
* single instance and share it throughout our application.
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
// Instantiate an Amazon SES client, which will make the service call with the supplied AWS credentials.
AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
.withCredentials(credentialsProvider)
// Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your production
// access status, sending limits, and Amazon SES identity-related settings are specific to a given
// AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
// the US East (N. Virginia) region. Examples of other regions that Amazon SES supports are US_WEST_2
// and EU_WEST_1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
.withRegion("us-east-1")
.build();
// Send the email.
client.sendEmail(request);
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("The email was not sent.");
System.out.println("Error message: " + ex.getMessage());
}
}
}
| 7,286 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AwsCloudFormation/CloudFormationSample.java | /*
* Copyright 2011-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.cloudformation.AmazonCloudFormation;
import com.amazonaws.services.cloudformation.AmazonCloudFormationClientBuilder;
import com.amazonaws.services.cloudformation.model.CreateStackRequest;
import com.amazonaws.services.cloudformation.model.DeleteStackRequest;
import com.amazonaws.services.cloudformation.model.DescribeStackResourcesRequest;
import com.amazonaws.services.cloudformation.model.DescribeStacksRequest;
import com.amazonaws.services.cloudformation.model.Stack;
import com.amazonaws.services.cloudformation.model.StackResource;
import com.amazonaws.services.cloudformation.model.StackStatus;
/**
* This sample demonstrates how to make basic requests to AWS CloudFormation
* using the AWS SDK for Java.
* <p>
* <b>Prerequisites:</b> You must have a valid Amazon Web Services developer
* account, and be signed up to use AWS CloudFormation. For more information on
* AWS CloudFormation, see http://aws.amazon.com/cloudformation.
* <p>
* Fill in your AWS access credentials in the provided credentials file
* template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the credentials from.
* <p>
* <b>WARNING:</b> To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
public class CloudFormationSample {
public static void main(String[] args) throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
AmazonCloudFormation stackbuilder = AmazonCloudFormationClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(Regions.US_WEST_2)
.build();
System.out.println("===========================================");
System.out.println("Getting Started with AWS CloudFormation");
System.out.println("===========================================\n");
String stackName = "CloudFormationSampleStack";
String logicalResourceName = "SampleNotificationTopic";
try {
// Create a stack
CreateStackRequest createRequest = new CreateStackRequest();
createRequest.setStackName(stackName);
createRequest.setTemplateBody(convertStreamToString(CloudFormationSample.class.getResourceAsStream("CloudFormationSample.template")));
System.out.println("Creating a stack called " + createRequest.getStackName() + ".");
stackbuilder.createStack(createRequest);
// Wait for stack to be created
// Note that you could use SNS notifications on the CreateStack call to track the progress of the stack creation
System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName));
// Show all the stacks for this account along with the resources for each stack
for (Stack stack : stackbuilder.describeStacks(new DescribeStacksRequest()).getStacks()) {
System.out.println("Stack : " + stack.getStackName() + " [" + stack.getStackStatus().toString() + "]");
DescribeStackResourcesRequest stackResourceRequest = new DescribeStackResourcesRequest();
stackResourceRequest.setStackName(stack.getStackName());
for (StackResource resource : stackbuilder.describeStackResources(stackResourceRequest).getStackResources()) {
System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId());
}
}
// Lookup a resource by its logical name
DescribeStackResourcesRequest logicalNameResourceRequest = new DescribeStackResourcesRequest();
logicalNameResourceRequest.setStackName(stackName);
logicalNameResourceRequest.setLogicalResourceId(logicalResourceName);
System.out.format("Looking up resource name %1$s from stack %2$s\n", logicalNameResourceRequest.getLogicalResourceId(), logicalNameResourceRequest.getStackName());
for (StackResource resource : stackbuilder.describeStackResources(logicalNameResourceRequest).getStackResources()) {
System.out.format(" %1$-40s %2$-25s %3$s\n", resource.getResourceType(), resource.getLogicalResourceId(), resource.getPhysicalResourceId());
}
// Delete the stack
DeleteStackRequest deleteRequest = new DeleteStackRequest();
deleteRequest.setStackName(stackName);
System.out.println("Deleting the stack called " + deleteRequest.getStackName() + ".");
stackbuilder.deleteStack(deleteRequest);
// Wait for stack to be deleted
// Note that you could used SNS notifications on the original CreateStack call to track the progress of the stack deletion
System.out.println("Stack creation completed, the stack " + stackName + " completed with " + waitForCompletion(stackbuilder, stackName));
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to AWS CloudFormation, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with AWS CloudFormation, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
// Convert a stream into a single, newline separated string
public static String convertStreamToString(InputStream in) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringbuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringbuilder.append(line + "\n");
}
in.close();
return stringbuilder.toString();
}
// Wait for a stack to complete transitioning
// End stack states are:
// CREATE_COMPLETE
// CREATE_FAILED
// DELETE_FAILED
// ROLLBACK_FAILED
// OR the stack no longer exists
public static String waitForCompletion(AmazonCloudFormation stackbuilder, String stackName) throws Exception {
DescribeStacksRequest wait = new DescribeStacksRequest();
wait.setStackName(stackName);
Boolean completed = false;
String stackStatus = "Unknown";
String stackReason = "";
System.out.print("Waiting");
while (!completed) {
List<Stack> stacks = stackbuilder.describeStacks(wait).getStacks();
if (stacks.isEmpty())
{
completed = true;
stackStatus = "NO_SUCH_STACK";
stackReason = "Stack has been deleted";
} else {
for (Stack stack : stacks) {
if (stack.getStackStatus().equals(StackStatus.CREATE_COMPLETE.toString()) ||
stack.getStackStatus().equals(StackStatus.CREATE_FAILED.toString()) ||
stack.getStackStatus().equals(StackStatus.ROLLBACK_FAILED.toString()) ||
stack.getStackStatus().equals(StackStatus.DELETE_FAILED.toString())) {
completed = true;
stackStatus = stack.getStackStatus();
stackReason = stack.getStackStatusReason();
}
}
}
// Show we are waiting
System.out.print(".");
// Not done yet so sleep for 10 seconds.
if (!completed) Thread.sleep(10000);
}
// Show we are done
System.out.print("done\n");
return stackStatus + " (" + stackReason + ")";
}
}
| 7,287 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesisFirehose/AmazonKinesisFirehoseToRedshiftSample.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.kinesisfirehose.model.BufferingHints;
import com.amazonaws.services.kinesisfirehose.model.CopyCommand;
import com.amazonaws.services.kinesisfirehose.model.CreateDeliveryStreamRequest;
import com.amazonaws.services.kinesisfirehose.model.DeliveryStreamDescription;
import com.amazonaws.services.kinesisfirehose.model.RedshiftDestinationConfiguration;
import com.amazonaws.services.kinesisfirehose.model.RedshiftDestinationUpdate;
import com.amazonaws.services.kinesisfirehose.model.S3DestinationConfiguration;
import com.amazonaws.services.kinesisfirehose.model.UpdateDestinationRequest;
import com.amazonaws.util.StringUtils;
/**
* Amazon Kinesis Firehose is a fully managed service for real-time streaming data delivery
* to destinations such as Amazon S3 and Amazon Redshift. Firehose is part of the Amazon Kinesis
* streaming data family, along with Amazon Kinesis Streams. With Firehose, you do not need to
* write any applications or manage any resources. You configure your data producers to send data
* to Firehose and it automatically delivers the data to the destination that you specified.
*
* Detailed Amazon Kinesis Firehose documentation can be found here:
* https://aws.amazon.com/documentation/firehose/
*
* This is a sample java application to deliver data to Amazon Redshift destination.
*/
public class AmazonKinesisFirehoseToRedshiftSample extends AbstractAmazonKinesisFirehoseDelivery {
/*
* Before running the code:
*
* Step 1: Please check you have AWS access credentials set under
* (~/.aws/credentials). If not, fill in your AWS access credentials in the
* provided credentials file template, and be sure to move the file to the
* default location (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING: To avoid accidental leakage of your credentials, DO NOT keep the
* credentials file in your source directory.
*
* Step 2: Update the firehosetoredshiftsample.properties file with required parameters.
*/
// Redshift properties
private static String clusterJDBCUrl;
private static String username;
private static String password;
private static String dataTableName;
private static String copyOptions;
private static String updatedCopyOptions;
// Properties file
private static final String CONFIG_FILE = "firehosetoredshiftsample.properties";
// Logger
private static final Log LOG = LogFactory.getLog(AmazonKinesisFirehoseToRedshiftSample.class);
/**
* Initialize the parameters.
*
* @throws Exception
*/
private static void init() throws Exception {
// Load the parameters from properties file
loadConfig();
// Initialize the clients
initClients();
// Validate AccountId parameter is set
if (StringUtils.isNullOrEmpty(accountId)) {
throw new IllegalArgumentException("AccountId is empty. Please enter the accountId in "
+ CONFIG_FILE + " file");
}
}
/**
* Load the input parameters from properties file.
*
* @throws FileNotFoundException
* @throws IOException
*/
private static void loadConfig() throws FileNotFoundException, IOException {
try (InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE)) {
if (configStream == null) {
throw new FileNotFoundException();
}
properties = new Properties();
properties.load(configStream);
}
// Read properties
accountId = properties.getProperty("customerAccountId");
createS3Bucket = Boolean.valueOf(properties.getProperty("createS3Bucket"));
s3RegionName = properties.getProperty("s3RegionName");
s3BucketName = properties.getProperty("s3BucketName").trim();
s3BucketARN = getBucketARN(s3BucketName);
s3ObjectPrefix = properties.getProperty("s3ObjectPrefix").trim();
String sizeInMBsProperty = properties.getProperty("destinationSizeInMBs");
s3DestinationSizeInMBs = StringUtils.isNullOrEmpty(sizeInMBsProperty) ? null : Integer.parseInt(sizeInMBsProperty.trim());
String intervalInSecondsProperty = properties.getProperty("destinationIntervalInSeconds");
s3DestinationIntervalInSeconds = StringUtils.isNullOrEmpty(intervalInSecondsProperty) ? null : Integer.parseInt(intervalInSecondsProperty.trim());
clusterJDBCUrl = properties.getProperty("clusterJDBCUrl");
username = properties.getProperty("username");
password = properties.getProperty("password");
dataTableName = properties.getProperty("dataTableName");
copyOptions = properties.getProperty("copyOptions");
deliveryStreamName = properties.getProperty("deliveryStreamName");
firehoseRegion = properties.getProperty("firehoseRegion");
iamRoleName = properties.getProperty("iamRoleName");
iamRegion = properties.getProperty("iamRegion");
// Update Delivery Stream Destination related properties
enableUpdateDestination = Boolean.valueOf(properties.getProperty("updateDestination"));
updatedCopyOptions = properties.getProperty("updatedCopyOptions");
}
public static void main(String[] args) throws Exception {
init();
try {
// Create S3 bucket for DeliveryStream to deliver data
createS3Bucket();
// Create the DeliveryStream
createDeliveryStream();
// Print the list of delivery streams
printDeliveryStreams();
// Put records into DeliveryStream
LOG.info("Putting records in DeliveryStream : " + deliveryStreamName + " via Put Record method.");
putRecordIntoDeliveryStream();
// Batch Put records into DeliveryStream
LOG.info("Putting records in DeliveryStream : " + deliveryStreamName
+ " via Put Record Batch method. Now you can check your S3 bucket " + s3BucketName
+ " for the data delivered by DeliveryStream.");
putRecordBatchIntoDeliveryStream();
// Wait for some interval for the firehose to write data to redshift destination
int waitTimeSecs = s3DestinationIntervalInSeconds == null ? DEFAULT_WAIT_INTERVAL_FOR_DATA_DELIVERY_SECS : s3DestinationIntervalInSeconds;
waitForDataDelivery(waitTimeSecs);
// Update the DeliveryStream and Put records into updated DeliveryStream, only if the flag is set
if (enableUpdateDestination) {
// Update the DeliveryStream
updateDeliveryStream();
// Wait for some interval to propagate the updated configuration options before ingesting data
LOG.info("Waiting for few seconds to propagate the updated configuration options.");
TimeUnit.SECONDS.sleep(60);
// Put records into updated DeliveryStream.
LOG.info("Putting records in updated DeliveryStream : " + deliveryStreamName + " via Put Record method.");
putRecordIntoDeliveryStream();
// Batch Put records into updated DeliveryStream.
LOG.info("Putting records in updated DeliveryStream : " + deliveryStreamName + " via Put Record Batch method.");
putRecordBatchIntoDeliveryStream();
// Wait for some interval for the DeliveryStream to write data to redshift destination
waitForDataDelivery(waitTimeSecs);
}
} catch (AmazonServiceException ase) {
LOG.error("Caught Amazon Service Exception");
LOG.error("Status Code " + ase.getErrorCode());
LOG.error("Message: " + ase.getErrorMessage(), ase);
} catch (AmazonClientException ace) {
LOG.error("Caught Amazon Client Exception");
LOG.error("Exception Message " + ace.getMessage(), ace);
}
}
/**
* Method to create delivery stream with Redshift destination configuration.
*
* @throws Exception
*/
private static void createDeliveryStream() throws Exception {
boolean deliveryStreamExists = false;
LOG.info("Checking if " + deliveryStreamName + " already exits");
List<String> deliveryStreamNames = listDeliveryStreams();
if (deliveryStreamNames != null && deliveryStreamNames.contains(deliveryStreamName)) {
deliveryStreamExists = true;
LOG.info("DeliveryStream " + deliveryStreamName + " already exists. Not creating the new delivery stream");
} else {
LOG.info("DeliveryStream " + deliveryStreamName + " does not exist");
}
if (!deliveryStreamExists) {
// Create DeliveryStream
CreateDeliveryStreamRequest createDeliveryStreamRequest = new CreateDeliveryStreamRequest();
createDeliveryStreamRequest.setDeliveryStreamName(deliveryStreamName);
S3DestinationConfiguration redshiftS3Configuration = new S3DestinationConfiguration();
redshiftS3Configuration.setBucketARN(s3BucketARN);
redshiftS3Configuration.setPrefix(s3ObjectPrefix);
BufferingHints bufferingHints = null;
if (s3DestinationSizeInMBs != null || s3DestinationIntervalInSeconds != null) {
bufferingHints = new BufferingHints();
bufferingHints.setSizeInMBs(s3DestinationSizeInMBs);
bufferingHints.setIntervalInSeconds(s3DestinationIntervalInSeconds);
}
redshiftS3Configuration.setBufferingHints(bufferingHints);
// Create and set IAM role so that firehose service has access to the S3Buckets to put data.
// Please check the trustPolicyDocument.json and permissionsPolicyDocument.json files
// for the trust and permissions policies set for the role.
String iamRoleArn = createIamRole(s3ObjectPrefix);
redshiftS3Configuration.setRoleARN(iamRoleArn);
CopyCommand copyCommand = new CopyCommand();
copyCommand.withCopyOptions(copyOptions)
.withDataTableName(dataTableName);
RedshiftDestinationConfiguration redshiftDestinationConfiguration = new RedshiftDestinationConfiguration();
redshiftDestinationConfiguration.withClusterJDBCURL(clusterJDBCUrl)
.withRoleARN(iamRoleArn)
.withUsername(username)
.withPassword(password)
.withCopyCommand(copyCommand)
.withS3Configuration(redshiftS3Configuration);
createDeliveryStreamRequest.setRedshiftDestinationConfiguration(redshiftDestinationConfiguration);
firehoseClient.createDeliveryStream(createDeliveryStreamRequest);
// The Delivery Stream is now being created.
LOG.info("Creating DeliveryStream : " + deliveryStreamName);
waitForDeliveryStreamToBecomeAvailable(deliveryStreamName);
}
}
/**
* Method to update redshift destination with updated copy options.
*/
private static void updateDeliveryStream() {
DeliveryStreamDescription deliveryStreamDescription = describeDeliveryStream(deliveryStreamName);
LOG.info("Updating DeliveryStream Destination: " + deliveryStreamName + " with new configuration options");
// get(0) -> DeliveryStream currently supports only one destination per DeliveryStream
UpdateDestinationRequest updateDestinationRequest =
new UpdateDestinationRequest()
.withDeliveryStreamName(deliveryStreamName)
.withCurrentDeliveryStreamVersionId(deliveryStreamDescription.getVersionId())
.withDestinationId(deliveryStreamDescription.getDestinations().get(0).getDestinationId());
CopyCommand updatedCopyCommand = new CopyCommand()
.withDataTableName(dataTableName)
.withCopyOptions(updatedCopyOptions);
RedshiftDestinationUpdate redshiftDestinationUpdate = new RedshiftDestinationUpdate()
.withCopyCommand(updatedCopyCommand);
updateDestinationRequest.setRedshiftDestinationUpdate(redshiftDestinationUpdate);
// Update DeliveryStream destination with new configuration options such as s3Prefix and Buffering Hints.
// Can also update Compression format, KMS key values and IAM Role.
firehoseClient.updateDestination(updateDestinationRequest);
}
}
| 7,288 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesisFirehose/AmazonKinesisFirehoseToS3Sample.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.kinesisfirehose.model.BufferingHints;
import com.amazonaws.services.kinesisfirehose.model.CompressionFormat;
import com.amazonaws.services.kinesisfirehose.model.CreateDeliveryStreamRequest;
import com.amazonaws.services.kinesisfirehose.model.DeliveryStreamDescription;
import com.amazonaws.services.kinesisfirehose.model.EncryptionConfiguration;
import com.amazonaws.services.kinesisfirehose.model.KMSEncryptionConfig;
import com.amazonaws.services.kinesisfirehose.model.NoEncryptionConfig;
import com.amazonaws.services.kinesisfirehose.model.S3DestinationConfiguration;
import com.amazonaws.services.kinesisfirehose.model.S3DestinationUpdate;
import com.amazonaws.services.kinesisfirehose.model.UpdateDestinationRequest;
import com.amazonaws.util.StringUtils;
/**
* Amazon Kinesis Firehose is a fully managed service for real-time streaming data delivery
* to destinations such as Amazon S3 and Amazon Redshift. Firehose is part of the Amazon Kinesis
* streaming data family, along with Amazon Kinesis Streams. With Firehose, you do not need to
* write any applications or manage any resources. You configure your data producers to send data
* to Firehose and it automatically delivers the data to the destination that you specified.
*
* Detailed Amazon Kinesis Firehose documentation can be found here:
* https://aws.amazon.com/documentation/firehose/
*
* This is a sample java application to deliver data to Amazon S3 destination.
*/
public class AmazonKinesisFirehoseToS3Sample extends AbstractAmazonKinesisFirehoseDelivery {
/*
* Before running the code:
*
* Step 1: Please check you have AWS access credentials set under
* (~/.aws/credentials). If not, fill in your AWS access credentials in the
* provided credentials file template, and be sure to move the file to the
* default location (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING: To avoid accidental leakage of your credentials, DO NOT keep the
* credentials file in your source directory.
*
* Step 2: Update the firehosetos3sample.properties file with the required parameters.
*/
// DeliveryStream properties
private static String updateS3ObjectPrefix;
private static Integer updateSizeInMBs;
private static Integer updateIntervalInSeconds;
// Properties File
private static final String CONFIG_FILE = "firehosetos3sample.properties";
// Logger
private static final Log LOG = LogFactory.getLog(AmazonKinesisFirehoseToS3Sample.class);
/**
* Initialize the parameters.
*
* @throws Exception
*/
private static void init() throws Exception {
// Load the parameters from properties file
loadConfig();
// Initialize the clients
initClients();
// Validate AccountId parameter is set
if (StringUtils.isNullOrEmpty(accountId)) {
throw new IllegalArgumentException("AccountId is empty. Please enter the accountId in "
+ CONFIG_FILE + " file");
}
}
/**
* Load the input parameters from properties file.
*
* @throws FileNotFoundException
* @throws IOException
*/
private static void loadConfig() throws FileNotFoundException, IOException {
try (InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE)) {
if (configStream == null) {
throw new FileNotFoundException();
}
properties = new Properties();
properties.load(configStream);
}
// Read properties
accountId = properties.getProperty("customerAccountId");
createS3Bucket = Boolean.valueOf(properties.getProperty("createS3Bucket"));
s3RegionName = properties.getProperty("s3RegionName");
s3BucketName = properties.getProperty("s3BucketName").trim();
s3BucketARN = getBucketARN(s3BucketName);
s3ObjectPrefix = properties.getProperty("s3ObjectPrefix").trim();
String sizeInMBsProperty = properties.getProperty("destinationSizeInMBs");
s3DestinationSizeInMBs = StringUtils.isNullOrEmpty(sizeInMBsProperty) ? null : Integer.parseInt(sizeInMBsProperty.trim());
String intervalInSecondsProperty = properties.getProperty("destinationIntervalInSeconds");
s3DestinationIntervalInSeconds = StringUtils.isNullOrEmpty(intervalInSecondsProperty) ? null : Integer.parseInt(intervalInSecondsProperty.trim());
deliveryStreamName = properties.getProperty("deliveryStreamName");
s3DestinationAWSKMSKeyId = properties.getProperty("destinationAWSKMSKeyId");
firehoseRegion = properties.getProperty("firehoseRegion");
iamRoleName = properties.getProperty("iamRoleName");
iamRegion = properties.getProperty("iamRegion");
// Update Delivery Stream Destination related properties
enableUpdateDestination = Boolean.valueOf(properties.getProperty("updateDestination"));
updateS3ObjectPrefix = properties.getProperty("updateS3ObjectPrefix").trim();
String updateSizeInMBsProperty = properties.getProperty("updateSizeInMBs");
updateSizeInMBs = StringUtils.isNullOrEmpty(updateSizeInMBsProperty) ? null : Integer.parseInt(updateSizeInMBsProperty.trim());
String updateIntervalInSecondsProperty = properties.getProperty("updateIntervalInSeconds");
updateIntervalInSeconds = StringUtils.isNullOrEmpty(updateIntervalInSecondsProperty) ? null : Integer.parseInt(updateIntervalInSecondsProperty.trim());
}
public static void main(String[] args) throws Exception {
init();
try {
// Create S3 bucket for deliveryStream to deliver data
createS3Bucket();
// Create the DeliveryStream
createDeliveryStream();
// Print the list of delivery streams
printDeliveryStreams();
// Put records into deliveryStream
LOG.info("Putting records in deliveryStream : " + deliveryStreamName + " via Put Record method.");
putRecordIntoDeliveryStream();
// Batch Put records into deliveryStream
LOG.info("Putting records in deliveryStream : " + deliveryStreamName
+ " via Put Record Batch method. Now you can check your S3 bucket " + s3BucketName
+ " for the data delivered by deliveryStream.");
putRecordBatchIntoDeliveryStream();
// Wait for some interval for the firehose to write data to the S3 bucket
int waitTimeSecs = s3DestinationIntervalInSeconds == null ? DEFAULT_WAIT_INTERVAL_FOR_DATA_DELIVERY_SECS : s3DestinationIntervalInSeconds;
waitForDataDelivery(waitTimeSecs);
// Update the deliveryStream and Put records into updated deliveryStream, only if the flag is set
if (enableUpdateDestination) {
// Update the deliveryStream
updateDeliveryStream();
// Wait for some interval to propagate the updated configuration options before ingesting data
LOG.info("Waiting for few seconds to propagate the updated configuration options.");
TimeUnit.SECONDS.sleep(60);
// Put records into updated deliveryStream. Records will be delivered to new S3 prefix location
LOG.info("Putting records in updated deliveryStream : " + deliveryStreamName + " via Put Record method.");
putRecordIntoDeliveryStream();
// Batch Put records into updated deliveryStream. Records will be delivered to new S3 prefix location
LOG.info("Putting records in updated deliveryStream : " + deliveryStreamName + " via Put Record Batch method.");
putRecordBatchIntoDeliveryStream();
// Wait for some interval for the deliveryStream to write data to new prefix location in S3 bucket
waitTimeSecs = updateIntervalInSeconds == null ? waitTimeSecs : updateIntervalInSeconds;
waitForDataDelivery(waitTimeSecs);
}
} catch (AmazonServiceException ase) {
LOG.error("Caught Amazon Service Exception");
LOG.error("Status Code " + ase.getErrorCode());
LOG.error("Message: " + ase.getErrorMessage(), ase);
} catch (AmazonClientException ace) {
LOG.error("Caught Amazon Client Exception");
LOG.error("Exception Message " + ace.getMessage(), ace);
}
}
/**
* Method to create delivery stream for S3 destination configuration.
*
* @throws Exception
*/
private static void createDeliveryStream() throws Exception {
boolean deliveryStreamExists = false;
LOG.info("Checking if " + deliveryStreamName + " already exits");
List<String> deliveryStreamNames = listDeliveryStreams();
if (deliveryStreamNames != null && deliveryStreamNames.contains(deliveryStreamName)) {
deliveryStreamExists = true;
LOG.info("DeliveryStream " + deliveryStreamName + " already exists. Not creating the new delivery stream");
} else {
LOG.info("DeliveryStream " + deliveryStreamName + " does not exist");
}
if (!deliveryStreamExists) {
// Create deliveryStream
CreateDeliveryStreamRequest createDeliveryStreamRequest = new CreateDeliveryStreamRequest();
createDeliveryStreamRequest.setDeliveryStreamName(deliveryStreamName);
S3DestinationConfiguration s3DestinationConfiguration = new S3DestinationConfiguration();
s3DestinationConfiguration.setBucketARN(s3BucketARN);
s3DestinationConfiguration.setPrefix(s3ObjectPrefix);
// Could also specify GZIP or ZIP
s3DestinationConfiguration.setCompressionFormat(CompressionFormat.UNCOMPRESSED);
// Encryption configuration is optional
EncryptionConfiguration encryptionConfiguration = new EncryptionConfiguration();
if (!StringUtils.isNullOrEmpty(s3DestinationAWSKMSKeyId)) {
encryptionConfiguration.setKMSEncryptionConfig(new KMSEncryptionConfig()
.withAWSKMSKeyARN(s3DestinationAWSKMSKeyId));
} else {
encryptionConfiguration.setNoEncryptionConfig(NoEncryptionConfig.NoEncryption);
}
s3DestinationConfiguration.setEncryptionConfiguration(encryptionConfiguration);
BufferingHints bufferingHints = null;
if (s3DestinationSizeInMBs != null || s3DestinationIntervalInSeconds != null) {
bufferingHints = new BufferingHints();
bufferingHints.setSizeInMBs(s3DestinationSizeInMBs);
bufferingHints.setIntervalInSeconds(s3DestinationIntervalInSeconds);
}
s3DestinationConfiguration.setBufferingHints(bufferingHints);
// Create and set IAM role so that firehose service has access to the S3Buckets to put data
// and KMS keys (if provided) to encrypt data. Please check the trustPolicyDocument.json and
// permissionsPolicyDocument.json files for the trust and permissions policies set for the role.
String iamRoleArn = createIamRole(s3ObjectPrefix);
s3DestinationConfiguration.setRoleARN(iamRoleArn);
createDeliveryStreamRequest.setS3DestinationConfiguration(s3DestinationConfiguration);
firehoseClient.createDeliveryStream(createDeliveryStreamRequest);
// The Delivery Stream is now being created.
LOG.info("Creating DeliveryStream : " + deliveryStreamName);
waitForDeliveryStreamToBecomeAvailable(deliveryStreamName);
}
}
/**
* Method to update s3 destination with updated s3Prefix, and buffering hints values.
*
* @throws Exception
*/
private static void updateDeliveryStream() throws Exception {
DeliveryStreamDescription deliveryStreamDescription = describeDeliveryStream(deliveryStreamName);
LOG.info("Updating DeliveryStream Destination: " + deliveryStreamName + " with new configuration options");
// get(0) -> DeliveryStream currently supports only one destination per DeliveryStream
UpdateDestinationRequest updateDestinationRequest =
new UpdateDestinationRequest()
.withDeliveryStreamName(deliveryStreamName)
.withCurrentDeliveryStreamVersionId(deliveryStreamDescription.getVersionId())
.withDestinationId(deliveryStreamDescription.getDestinations().get(0).getDestinationId());
S3DestinationUpdate s3DestinationUpdate = new S3DestinationUpdate();
s3DestinationUpdate.withPrefix(updateS3ObjectPrefix);
BufferingHints bufferingHints = null;
if (updateSizeInMBs != null || updateIntervalInSeconds != null) {
bufferingHints = new BufferingHints();
bufferingHints.setSizeInMBs(updateSizeInMBs);
bufferingHints.setIntervalInSeconds(updateIntervalInSeconds);
}
s3DestinationUpdate.setBufferingHints(bufferingHints);
// Update the role policy with new s3Prefix configuration
putRolePolicy(updateS3ObjectPrefix);
updateDestinationRequest.setS3DestinationUpdate(s3DestinationUpdate);
// Update deliveryStream destination with new configuration options such as s3Prefix and Buffering Hints.
// Can also update Compression format, KMS key values and IAM Role.
firehoseClient.updateDestination(updateDestinationRequest);
}
}
| 7,289 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonKinesisFirehose/AbstractAmazonKinesisFirehoseDelivery.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagementClientBuilder;
import com.amazonaws.services.identitymanagement.model.CreateRoleRequest;
import com.amazonaws.services.identitymanagement.model.EntityAlreadyExistsException;
import com.amazonaws.services.identitymanagement.model.GetRoleRequest;
import com.amazonaws.services.identitymanagement.model.MalformedPolicyDocumentException;
import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest;
import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehose;
import com.amazonaws.services.kinesisfirehose.AmazonKinesisFirehoseClientBuilder;
import com.amazonaws.services.kinesisfirehose.model.DeliveryStreamDescription;
import com.amazonaws.services.kinesisfirehose.model.DescribeDeliveryStreamRequest;
import com.amazonaws.services.kinesisfirehose.model.DescribeDeliveryStreamResult;
import com.amazonaws.services.kinesisfirehose.model.ListDeliveryStreamsRequest;
import com.amazonaws.services.kinesisfirehose.model.ListDeliveryStreamsResult;
import com.amazonaws.services.kinesisfirehose.model.PutRecordBatchRequest;
import com.amazonaws.services.kinesisfirehose.model.PutRecordBatchResult;
import com.amazonaws.services.kinesisfirehose.model.PutRecordRequest;
import com.amazonaws.services.kinesisfirehose.model.Record;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.util.IOUtils;
import com.amazonaws.util.StringUtils;
/**
* Abstract class that contains all the common methods used in samples for
* Amazon S3 and Amazon Redshift destination.
*/
public abstract class AbstractAmazonKinesisFirehoseDelivery {
// S3 properties
protected static AmazonS3 s3Client;
protected static boolean createS3Bucket;
protected static String s3BucketARN;
protected static String s3BucketName;
protected static String s3ObjectPrefix;
protected static String s3RegionName;
// DeliveryStream properties
protected static AmazonKinesisFirehose firehoseClient;
protected static String accountId;
protected static String deliveryStreamName;
protected static String firehoseRegion;
protected static boolean enableUpdateDestination;
// S3Destination Properties
protected static String iamRoleName;
protected static String s3DestinationAWSKMSKeyId;
protected static Integer s3DestinationSizeInMBs;
protected static Integer s3DestinationIntervalInSeconds;
// Properties Reader
protected static Properties properties;
// IAM Permissions Policy Document with KMS Resources. If KMS key ARN is
// specified, role will be created with KMS resources permission
private static final String IAM_ROLE_PERMISSIONS_POLICY_WITH_KMS_RESOURCES_DOCUMENT =
"permissionsPolicyDocument.json";
// IAM Permissions Policy Document without KMS Resources.
private static final String IAM_ROLE_PERMISSIONS_POLICY_WITHOUT_KMS_RESOURCES_DOCUMENT =
"permissionsPolicyWithoutKMSResourcesDocument.json";
// IAM Trust Policy Document
private static final String IAM_ROLE_TRUST_POLICY_DOCUMENT = "trustPolicyDocument.json";
// IAM Role Policy Name
private static final String FIREHOSE_ROLE_POLICY_NAME = "Firehose_Delivery_Permissions_Policy";
// Put Data Source File
private static final String PUT_RECORD_STREAM_SOURCE = "putRecordInput.txt";
private static final String BATCH_PUT_STREAM_SOURCE = "batchPutInput.txt";
private static final int BATCH_PUT_MAX_SIZE = 500;
// Default wait interval for data to be delivered in specified destination.
protected static final int DEFAULT_WAIT_INTERVAL_FOR_DATA_DELIVERY_SECS = 300;
// S3 Bucket ARN
private static final String S3_ARN_PREFIX = "arn:aws:s3:::";
// IAM Role
protected static String iamRegion;
protected static AmazonIdentityManagement iamClient;
// Logger
private static final Log LOG = LogFactory.getLog(AbstractAmazonKinesisFirehoseDelivery.class);
/**
* Method to initialize the clients using the specified AWSCredentials.
*
* @param Exception
*/
protected static void initClients() throws Exception {
/*
* The ProfileCredentialsProvider will return your [default] credential
* profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.", e);
}
// S3 client
s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(s3RegionName)
.build();
// Firehose client
firehoseClient = AmazonKinesisFirehoseClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(firehoseRegion)
.build();
// IAM client
iamClient = AmazonIdentityManagementClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion(iamRegion)
.build();
}
/**
* Method to create the S3 bucket in specified region.
*
* @throws Exception
*/
protected static void createS3Bucket() throws Exception {
if (StringUtils.isNullOrEmpty(s3BucketName.trim())) {
throw new IllegalArgumentException("Bucket name is empty. Please enter a bucket name "
+ "in firehosetos3sample.properties file");
}
// Create S3 bucket if specified in the properties
if (createS3Bucket) {
s3Client.createBucket(s3BucketName);
LOG.info("Created bucket " + s3BucketName + " in S3 to deliver Firehose records");
}
}
/**
* Method to print all the delivery streams in the customer account.
*/
protected static void printDeliveryStreams() {
// list all of my DeliveryStreams
List<String> deliveryStreamNames = listDeliveryStreams();
LOG.info("Printing my list of DeliveryStreams : ");
if (deliveryStreamNames.isEmpty()) {
LOG.info("There are no DeliveryStreams for account: " + accountId);
} else {
LOG.info("List of my DeliveryStreams: ");
}
for (int i = 0; i < deliveryStreamNames.size(); i++) {
LOG.info(deliveryStreamNames.get(i));
}
}
/**
* Method to list all the delivery streams in the customer account.
*
* @return the collection of delivery streams
*/
protected static List<String> listDeliveryStreams() {
ListDeliveryStreamsRequest listDeliveryStreamsRequest = new ListDeliveryStreamsRequest();
ListDeliveryStreamsResult listDeliveryStreamsResult =
firehoseClient.listDeliveryStreams(listDeliveryStreamsRequest);
List<String> deliveryStreamNames = listDeliveryStreamsResult.getDeliveryStreamNames();
while (listDeliveryStreamsResult.isHasMoreDeliveryStreams()) {
if (deliveryStreamNames.size() > 0) {
listDeliveryStreamsRequest.setExclusiveStartDeliveryStreamName(deliveryStreamNames.get(deliveryStreamNames.size() - 1));
}
listDeliveryStreamsResult = firehoseClient.listDeliveryStreams(listDeliveryStreamsRequest);
deliveryStreamNames.addAll(listDeliveryStreamsResult.getDeliveryStreamNames());
}
return deliveryStreamNames;
}
/**
* Method to put records in the specified delivery stream by reading
* contents from sample input file using PutRecord API.
*
* @throws IOException
*/
protected static void putRecordIntoDeliveryStream() throws IOException {
try (InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream(PUT_RECORD_STREAM_SOURCE)) {
if (inputStream == null) {
throw new FileNotFoundException("Could not find file " + PUT_RECORD_STREAM_SOURCE);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
PutRecordRequest putRecordRequest = new PutRecordRequest();
putRecordRequest.setDeliveryStreamName(deliveryStreamName);
String data = line + "\n";
Record record = createRecord(data);
putRecordRequest.setRecord(record);
// Put record into the DeliveryStream
firehoseClient.putRecord(putRecordRequest);
}
}
}
}
/**
* Method to put records in the specified delivery stream by reading
* contents from sample input file using PutRecordBatch API.
*
* @throws IOException
*/
protected static void putRecordBatchIntoDeliveryStream() throws IOException {
try (InputStream inputStream =
Thread.currentThread().getContextClassLoader().getResourceAsStream(BATCH_PUT_STREAM_SOURCE)) {
if (inputStream == null) {
throw new FileNotFoundException("Could not find file " + BATCH_PUT_STREAM_SOURCE);
}
List<Record> recordList = new ArrayList<Record>();
int batchSize = 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
String data = line + "\n";
Record record = createRecord(data);
recordList.add(record);
batchSize++;
if (batchSize == BATCH_PUT_MAX_SIZE) {
putRecordBatch(recordList);
recordList.clear();
batchSize = 0;
}
}
if (batchSize > 0) {
putRecordBatch(recordList);
}
}
}
}
/**
* Method to create the IAM role.
*
* @param s3Prefix the s3Prefix to be specified in role policy (only when KMS key ARN is specified)
* @return the role ARN
* @throws InterruptedException
*/
protected static String createIamRole(String s3Prefix) throws InterruptedException {
try {
//set trust policy for the role
iamClient.createRole(new CreateRoleRequest()
.withRoleName(iamRoleName)
.withAssumeRolePolicyDocument(getTrustPolicy()));
} catch (EntityAlreadyExistsException e) {
LOG.info("IAM role with name " + iamRoleName + " already exists");
} catch (MalformedPolicyDocumentException policyDocumentException){
LOG.error(String.format("Please check the trust policy document for malformation: %s",
IAM_ROLE_TRUST_POLICY_DOCUMENT));
throw policyDocumentException;
}
// Update the role policy with permissions so that principal can access the resources
// with necessary conditions
putRolePolicy(s3Prefix);
String roleARN = iamClient.getRole(new GetRoleRequest().withRoleName(iamRoleName)).getRole().getArn();
// Sleep for 5 seconds because IAM role creation takes some time to propagate
Thread.sleep(5000);
return roleARN;
}
/**
* Method to wait until the delivery stream becomes active.
*
* @param deliveryStreamName the delivery stream
* @throws Exception
*/
protected static void waitForDeliveryStreamToBecomeAvailable(String deliveryStreamName) throws Exception {
LOG.info("Waiting for " + deliveryStreamName + " to become ACTIVE...");
long startTime = System.currentTimeMillis();
long endTime = startTime + (10 * 60 * 1000);
while (System.currentTimeMillis() < endTime) {
try {
Thread.sleep(1000 * 20);
} catch (InterruptedException e) {
// Ignore interruption (doesn't impact deliveryStream creation)
}
DeliveryStreamDescription deliveryStreamDescription = describeDeliveryStream(deliveryStreamName);
String deliveryStreamStatus = deliveryStreamDescription.getDeliveryStreamStatus();
LOG.info(" - current state: " + deliveryStreamStatus);
if (deliveryStreamStatus.equals("ACTIVE")) {
return;
}
}
throw new AmazonServiceException("DeliveryStream " + deliveryStreamName + " never went active");
}
/**
* Method to describe the delivery stream.
*
* @param deliveryStreamName the delivery stream
* @return the delivery description
*/
protected static DeliveryStreamDescription describeDeliveryStream(String deliveryStreamName) {
DescribeDeliveryStreamRequest describeDeliveryStreamRequest = new DescribeDeliveryStreamRequest();
describeDeliveryStreamRequest.withDeliveryStreamName(deliveryStreamName);
DescribeDeliveryStreamResult describeDeliveryStreamResponse =
firehoseClient.describeDeliveryStream(describeDeliveryStreamRequest);
return describeDeliveryStreamResponse.getDeliveryStreamDescription();
}
/**
* Method to wait for the specified buffering interval seconds so that data
* will be delivered to corresponding destination.
*
* @param waitTimeSecs the buffering interval seconds to wait upon
* @throws InterruptedException
*/
protected static void waitForDataDelivery(int waitTimeSecs) throws InterruptedException {
LOG.info("Since the Buffering Hints IntervalInSeconds parameter is specified as: " + waitTimeSecs
+ " seconds. Waiting for " + waitTimeSecs + " seconds for the data to be written to S3 bucket");
TimeUnit.SECONDS.sleep(waitTimeSecs);
LOG.info("Data delivery to S3 bucket " + s3BucketName + " is complete");
}
/**
* Method to return the bucket ARN.
*
* @param bucketName the bucket name to be formulated as ARN
* @return the bucket ARN
* @throws IllegalArgumentException
*/
protected static String getBucketARN(String bucketName) throws IllegalArgumentException {
return new StringBuilder().append(S3_ARN_PREFIX).append(bucketName).toString();
}
/**
* Method to perform PutRecordBatch operation with the given record list.
*
* @param recordList the collection of records
* @return the output of PutRecordBatch
*/
private static PutRecordBatchResult putRecordBatch(List<Record> recordList) {
PutRecordBatchRequest putRecordBatchRequest = new PutRecordBatchRequest();
putRecordBatchRequest.setDeliveryStreamName(deliveryStreamName);
putRecordBatchRequest.setRecords(recordList);
// Put Record Batch records. Max No.Of Records we can put in a
// single put record batch request is 500
return firehoseClient.putRecordBatch(putRecordBatchRequest);
}
/**
* Method to put the role policy with permissions document. Permission document would change
* based on KMS Key ARN specified in properties file. If KMS Key ARN is specified, permissions
* document will contain KMS resource.
*
* @param s3Prefix the s3Prefix which will be included in KMS Condition (only if KMS Key is provided)
*/
protected static void putRolePolicy(String s3Prefix) {
try {
// set permissions policy for the role
String permissionsPolicyDocument =
containsKMSKeyARN() ? getPermissionsPolicyWithKMSResources(s3Prefix)
: getPermissionsPolicyWithoutKMSResources();
iamClient.putRolePolicy(new PutRolePolicyRequest()
.withRoleName(iamRoleName)
.withPolicyName(FIREHOSE_ROLE_POLICY_NAME)
.withPolicyDocument(permissionsPolicyDocument));
} catch (MalformedPolicyDocumentException policyDocumentException){
LOG.error(String.format("Please check the permissions policy document for malformation: %s",
containsKMSKeyARN() ? IAM_ROLE_PERMISSIONS_POLICY_WITH_KMS_RESOURCES_DOCUMENT
: IAM_ROLE_PERMISSIONS_POLICY_WITHOUT_KMS_RESOURCES_DOCUMENT));
throw policyDocumentException;
}
}
/**
* Method to return the trust policy document to create a role.
*
* @return the trust policy document
*/
private static String getTrustPolicy() {
return readResource(IAM_ROLE_TRUST_POLICY_DOCUMENT)
.replace("{{CUSTOMER_ACCOUNT_ID}}", accountId);
}
/**
* Method to return the permissions policy document with KMS resource.
*
* @param s3Prefix the s3Prefix to be specified in KMS Condition
* @return the permissions policy document
*/
private static String getPermissionsPolicyWithKMSResources(String s3Prefix) {
return readResource(IAM_ROLE_PERMISSIONS_POLICY_WITH_KMS_RESOURCES_DOCUMENT)
.replace("{{S3_BUCKET_NAME}}", s3BucketName)
.replace("{{KMS_KEY_ARN}}", s3DestinationAWSKMSKeyId)
.replace("{{S3_REGION}}", s3RegionName)
.replace("{{S3_PREFIX}}", s3Prefix);
}
/**
* Method to return the permissions policy document without KMS resource.
*
* @return the permissions policy document
*/
private static String getPermissionsPolicyWithoutKMSResources() {
return readResource(IAM_ROLE_PERMISSIONS_POLICY_WITHOUT_KMS_RESOURCES_DOCUMENT)
.replace("{{S3_BUCKET_NAME}}", s3BucketName);
}
/**
* Method to read the resource for the given filename.
*
* @param name the file name
* @return the input stream as string
*/
private static String readResource(String name) {
try {
return IOUtils.toString(AmazonKinesisFirehoseToRedshiftSample.class.getResourceAsStream(name));
} catch (IOException e) {
throw new RuntimeException("Failed to read document resource: " + name, e);
}
}
/**
* Returns true if the KMS Key ARN is specified in properties file.
*
* @return true, if KMS Key is specified
*/
private static boolean containsKMSKeyARN() {
return !StringUtils.isNullOrEmpty(s3DestinationAWSKMSKeyId);
}
/**
* Method to create the record object for given data.
*
* @param data the content data
* @return the Record object
*/
private static Record createRecord(String data) {
return new Record().withData(ByteBuffer.wrap(data.getBytes()));
}
}
| 7,290 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonS3/S3Sample.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.UUID;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
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.S3ObjectSummary;
/**
* This sample demonstrates how to make basic requests to Amazon S3 using the
* AWS SDK for Java.
* <p>
* <b>Prerequisites:</b> You must have a valid Amazon Web Services developer
* account, and be signed up to use Amazon S3. For more information on Amazon
* S3, see http://aws.amazon.com/s3.
* <p>
* Fill in your AWS access credentials in the provided credentials file
* template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the credentials from.
* <p>
* <b>WARNING:</b> To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*
* http://aws.amazon.com/security-credentials
*/
public class S3Sample {
public static void main(String[] args) throws IOException {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().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 (~/.aws/credentials), and is in valid format.",
e);
}
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion("us-west-2")
.build();
String bucketName = "my-first-s3-bucket-" + UUID.randomUUID();
String key = "MyObjectKey";
System.out.println("===========================================");
System.out.println("Getting Started with Amazon S3");
System.out.println("===========================================\n");
try {
/*
* Create a new S3 bucket - Amazon S3 bucket names are globally unique,
* so once a bucket name has been taken by any user, you can't create
* another bucket with that same name.
*
* You can optionally specify a location for your bucket if you want to
* keep your data closer to your applications or users.
*/
System.out.println("Creating bucket " + bucketName + "\n");
s3.createBucket(bucketName);
/*
* List the buckets in your account
*/
System.out.println("Listing buckets");
for (Bucket bucket : s3.listBuckets()) {
System.out.println(" - " + bucket.getName());
}
System.out.println();
/*
* Upload an object to your bucket - You can easily upload a file to
* S3, or upload directly an InputStream if you know the length of
* the data in the stream. You can also specify your own metadata
* when uploading to S3, which allows you set a variety of options
* like content-type and content-encoding, plus additional metadata
* specific to your applications.
*/
System.out.println("Uploading a new object to S3 from a file\n");
s3.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
/*
* Download an object - When you download an object, you get all of
* the object's metadata and a stream from which to read the contents.
* It's important to read the contents of the stream as quickly as
* possibly since the data is streamed directly from Amazon S3 and your
* network connection will remain open until you read all the data or
* close the input stream.
*
* GetObjectRequest also supports several other options, including
* conditional downloading of objects based on modification times,
* ETags, and selectively downloading a range of an object.
*/
System.out.println("Downloading an object");
S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
displayTextInputStream(object.getObjectContent());
/*
* List objects in your bucket by prefix - There are many options for
* listing the objects in your bucket. Keep in mind that buckets with
* many objects might truncate their results when listing their objects,
* so be sure to check if the returned object listing is truncated, and
* use the AmazonS3.listNextBatchOfObjects(...) operation to retrieve
* additional results.
*/
System.out.println("Listing objects");
ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("My"));
for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {
System.out.println(" - " + objectSummary.getKey() + " " +
"(size = " + objectSummary.getSize() + ")");
}
System.out.println();
/*
* Delete an object - Unless versioning has been turned on for your bucket,
* there is no way to undelete an object, so use caution when deleting objects.
*/
System.out.println("Deleting an object\n");
s3.deleteObject(bucketName, key);
/*
* Delete a bucket - A bucket must be completely empty before it can be
* deleted, so remember to delete any objects from your buckets before
* you try to delete them.
*/
System.out.println("Deleting bucket " + bucketName + "\n");
s3.deleteBucket(bucketName);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to Amazon S3, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with S3, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
/**
* Creates a temporary file with text data to demonstrate uploading a file
* to Amazon S3
*
* @return A newly created temporary file with text data.
*
* @throws IOException
*/
private static File createSampleFile() throws IOException {
File file = File.createTempFile("aws-java-sdk-", ".txt");
file.deleteOnExit();
try (Writer writer = new OutputStreamWriter(new FileOutputStream(file))) {
writer.write("abcdefghijklmnopqrstuvwxyz\n");
writer.write("01234567890112345678901234\n");
writer.write("!@#$%^&*()-=[]{};':',.<>/?\n");
writer.write("01234567890112345678901234\n");
writer.write("abcdefghijklmnopqrstuvwxyz\n");
}
return file;
}
/**
* Displays the contents of the specified input stream as text.
*
* @param input
* The input stream to display as text.
*
* @throws IOException
*/
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println(" " + line);
}
System.out.println();
}
}
| 7,291 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDB/AmazonDynamoDBSample.java | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.HashMap;
import java.util.Map;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.dynamodbv2.model.ComparisonOperator;
import com.amazonaws.services.dynamodbv2.model.Condition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.PutItemRequest;
import com.amazonaws.services.dynamodbv2.model.PutItemResult;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.ScanRequest;
import com.amazonaws.services.dynamodbv2.model.ScanResult;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
import com.amazonaws.services.dynamodbv2.util.TableUtils;
/**
* This sample demonstrates how to perform a few simple operations with the
* Amazon DynamoDB service.
*/
public class AmazonDynamoDBSample {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
static AmazonDynamoDB dynamoDB;
/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.ProfilesConfigFile
* @see com.amazonaws.ClientConfiguration
*/
private static void init() throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
dynamoDB = AmazonDynamoDBClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
}
public static void main(String[] args) throws Exception {
init();
try {
String tableName = "my-favorite-movies-table";
// Create a table with a primary hash key named 'name', which holds a string
CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName)
.withKeySchema(new KeySchemaElement().withAttributeName("name").withKeyType(KeyType.HASH))
.withAttributeDefinitions(new AttributeDefinition().withAttributeName("name").withAttributeType(ScalarAttributeType.S))
.withProvisionedThroughput(new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L));
// Create table if it does not exist yet
TableUtils.createTableIfNotExists(dynamoDB, createTableRequest);
// wait for the table to move into ACTIVE state
TableUtils.waitUntilActive(dynamoDB, tableName);
// Describe our new table
DescribeTableRequest describeTableRequest = new DescribeTableRequest().withTableName(tableName);
TableDescription tableDescription = dynamoDB.describeTable(describeTableRequest).getTable();
System.out.println("Table Description: " + tableDescription);
// Add an item
Map<String, AttributeValue> item = newItem("Bill & Ted's Excellent Adventure", 1989, "****", "James", "Sara");
PutItemRequest putItemRequest = new PutItemRequest(tableName, item);
PutItemResult putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);
// Add another item
item = newItem("Airplane", 1980, "*****", "James", "Billy Bob");
putItemRequest = new PutItemRequest(tableName, item);
putItemResult = dynamoDB.putItem(putItemRequest);
System.out.println("Result: " + putItemResult);
// Scan items for movies with a year attribute greater than 1985
HashMap<String, Condition> scanFilter = new HashMap<String, Condition>();
Condition condition = new Condition()
.withComparisonOperator(ComparisonOperator.GT.toString())
.withAttributeValueList(new AttributeValue().withN("1985"));
scanFilter.put("year", condition);
ScanRequest scanRequest = new ScanRequest(tableName).withScanFilter(scanFilter);
ScanResult scanResult = dynamoDB.scan(scanRequest);
System.out.println("Result: " + scanResult);
} catch (AmazonServiceException ase) {
System.out.println("Caught an AmazonServiceException, which means your request made it "
+ "to AWS, but was rejected with an error response for some reason.");
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
System.out.println("Caught an AmazonClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with AWS, "
+ "such as not being able to access the network.");
System.out.println("Error Message: " + ace.getMessage());
}
}
private static Map<String, AttributeValue> newItem(String name, int year, String rating, String... fans) {
Map<String, AttributeValue> item = new HashMap<String, AttributeValue>();
item.put("name", new AttributeValue(name));
item.put("year", new AttributeValue().withN(Integer.toString(year)));
item.put("rating", new AttributeValue(rating));
item.put("fans", new AttributeValue().withSS(fans));
return item;
}
}
| 7,292 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AwsConsoleApp/AwsConsoleApp.java | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
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.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClientBuilder;
import com.amazonaws.services.simpledb.model.DomainMetadataRequest;
import com.amazonaws.services.simpledb.model.DomainMetadataResult;
import com.amazonaws.services.simpledb.model.ListDomainsRequest;
import com.amazonaws.services.simpledb.model.ListDomainsResult;
/**
* Welcome to your new AWS Java SDK based project!
*
* This class is meant as a starting point for your console-based application that
* makes one or more calls to the AWS services supported by the Java SDK, such as EC2,
* SimpleDB, and S3.
*
* In order to use the services in this sample, you need:
*
* - A valid Amazon Web Services account. You can register for AWS at:
* https://aws-portal.amazon.com/gp/aws/developer/registration/index.html
*
* - Your account's Access Key ID and Secret Access Key:
* http://aws.amazon.com/security-credentials
*
* - A subscription to Amazon EC2. You can sign up for EC2 at:
* http://aws.amazon.com/ec2/
*
* - A subscription to Amazon SimpleDB. You can sign up for Simple DB at:
* http://aws.amazon.com/simpledb/
*
* - A subscription to Amazon S3. You can sign up for S3 at:
* http://aws.amazon.com/s3/
*/
public class AwsConsoleApp {
/*
* Before running the code:
* Fill in your AWS access credentials in the provided credentials
* file template, and be sure to move the file to the default location
* (~/.aws/credentials) where the sample code will load the
* credentials from.
* https://console.aws.amazon.com/iam/home?#security_credential
*
* WARNING:
* To avoid accidental leakage of your credentials, DO NOT keep
* the credentials file in your source directory.
*/
static AmazonEC2 ec2;
static AmazonS3 s3;
static AmazonSimpleDB sdb;
/**
* The only information needed to create a client are security credentials
* consisting of the AWS Access Key ID and Secret Access Key. All other
* configuration, such as the service endpoints, are performed
* automatically. Client parameters, such as proxies, can be specified in an
* optional ClientConfiguration object when constructing a client.
*
* @see com.amazonaws.auth.BasicAWSCredentials
* @see com.amazonaws.auth.PropertiesCredentials
* @see com.amazonaws.ClientConfiguration
*/
private static void init() throws Exception {
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file located at
* (~/.aws/credentials).
*/
ProfileCredentialsProvider credentialsProvider = new ProfileCredentialsProvider();
try {
credentialsProvider.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 (~/.aws/credentials), and is in valid format.",
e);
}
ec2 = AmazonEC2ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
s3 = AmazonS3ClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
sdb = AmazonSimpleDBClientBuilder.standard()
.withCredentials(credentialsProvider)
.withRegion("us-west-2")
.build();
}
public static void main(String[] args) throws Exception {
System.out.println("===========================================");
System.out.println("Welcome to the AWS Java SDK!");
System.out.println("===========================================");
init();
/*
* Amazon EC2
*
* The AWS EC2 client allows you to create, delete, and administer
* instances programmatically.
*
* In this sample, we use an EC2 client to get a list of all the
* availability zones, and all instances sorted by reservation id.
*/
try {
DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
" Availability Zones.");
DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
Set<Instance> instances = new HashSet<Instance>();
for (Reservation reservation : reservations) {
instances.addAll(reservation.getInstances());
}
System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
/*
* Amazon SimpleDB
*
* The AWS SimpleDB client allows you to query and manage your data
* stored in SimpleDB domains (similar to tables in a relational DB).
*
* In this sample, we use a SimpleDB client to iterate over all the
* domains owned by the current user, and add up the number of items
* (similar to rows of data in a relational DB) in each domain.
*/
try {
ListDomainsRequest sdbRequest = new ListDomainsRequest().withMaxNumberOfDomains(100);
ListDomainsResult sdbResult = sdb.listDomains(sdbRequest);
int totalItems = 0;
for (String domainName : sdbResult.getDomainNames()) {
DomainMetadataRequest metadataRequest = new DomainMetadataRequest().withDomainName(domainName);
DomainMetadataResult domainMetadata = sdb.domainMetadata(metadataRequest);
totalItems += domainMetadata.getItemCount();
}
System.out.println("You have " + sdbResult.getDomainNames().size() + " Amazon SimpleDB domain(s)" +
"containing a total of " + totalItems + " items.");
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
/*
* Amazon S3
*
* The AWS S3 client allows you to manage buckets and programmatically
* put and get objects to those buckets.
*
* In this sample, we use an S3 client to iterate over all the buckets
* owned by the current user, and all the object metadata in each
* bucket, to obtain a total object and space usage count. This is done
* without ever actually downloading a single object -- the requests
* work with object metadata only.
*/
try {
List<Bucket> buckets = s3.listBuckets();
long totalSize = 0;
int totalItems = 0;
for (Bucket bucket : buckets) {
/*
* In order to save bandwidth, an S3 object listing does not
* contain every object in the bucket; after a certain point the
* S3ObjectListing is truncated, and further pages must be
* obtained with the AmazonS3Client.listNextBatchOfObjects()
* method.
*/
ObjectListing objects = s3.listObjects(bucket.getName());
do {
for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
totalSize += objectSummary.getSize();
totalItems++;
}
objects = s3.listNextBatchOfObjects(objects);
} while (objects.isTruncated());
}
System.out.println("You have " + buckets.size() + " Amazon S3 bucket(s), " +
"containing " + totalItems + " objects with a total size of " + totalSize + " bytes.");
} catch (AmazonServiceException ase) {
/*
* AmazonServiceExceptions represent an error response from an AWS
* services, i.e. your request made it to AWS, but the AWS service
* either found it invalid or encountered an error trying to execute
* it.
*/
System.out.println("Error Message: " + ase.getMessage());
System.out.println("HTTP Status Code: " + ase.getStatusCode());
System.out.println("AWS Error Code: " + ase.getErrorCode());
System.out.println("Error Type: " + ase.getErrorType());
System.out.println("Request ID: " + ase.getRequestId());
} catch (AmazonClientException ace) {
/*
* AmazonClientExceptions represent an error that occurred inside
* the client on the local host, either while trying to send the
* request to AWS or interpret the response. For example, if no
* network connection is available, the client won't be able to
* connect to AWS to execute a request and will throw an
* AmazonClientException.
*/
System.out.println("Error Message: " + ace.getMessage());
}
}
}
| 7,293 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/utils/AbstractQuickStart.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.utils;
import java.io.File;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.quickstart.A_CreateTableTest;
/**
* Common base class used to initialize and shutdown the DynamoDB instance.
*/
public class AbstractQuickStart {
protected static DynamoDB dynamo;
protected static String TABLE_NAME = "myTableForMidLevelApi";
protected static String HASH_KEY_NAME = "myHashKey";
protected static String RANGE_KEY_NAME = "myRangeKey";
// local secondary index
protected static String LSI_NAME = "myLSI";
protected static String LSI_RANGE_KEY_NAME = "myLsiRangeKey";
// global secondary index
protected static String RANGE_GSI_NAME = "myRangeGSI";
protected static String GSI_HASH_KEY_NAME = "myGsiHashKey";
protected static String GSI_RANGE_KEY_NAME = "myGsiRangeKey";
@BeforeClass
public static void setup() throws InterruptedException {
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsTestCredentials());
dynamo = new DynamoDB(client);
new A_CreateTableTest().howToCreateTable();
}
@AfterClass
public static void tearDown() {
dynamo.shutdown();
}
protected static AWSCredentials awsTestCredentials() {
try {
return new PropertiesCredentials(new File(
System.getProperty("user.home")
+ "/.aws/awsTestAccount.properties"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 7,294 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/B_PutItemTest.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.quickstart;
import org.junit.Test;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.PutItemOutcome;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
/**
* Sample code to put items to a DynamoDB table.
*/
public class B_PutItemTest extends AbstractQuickStart {
@Test
public void howToPutItems() {
Table table = dynamo.getTable(TABLE_NAME);
Item item = newItem();
int intAttrVal = item.getInt("intAttr");
// Creates 10 items of range key values from 1 to 10
for (int i=1; i <= 10; i++) {
PutItemOutcome result = table.putItem(
item.withInt(RANGE_KEY_NAME, i)
.withInt("intAttr", intAttrVal+i)
);
System.out.println(result);
}
}
private Item newItem() {
Item item = new Item()
.withString(HASH_KEY_NAME, "foo")
.withBinary("binary", new byte[]{1,2,3,4})
.withBinarySet("binarySet", new byte[]{5,6}, new byte[]{7,8})
.withBoolean("booleanTrue", true)
.withBoolean("booleanFalse", false)
.withInt("intAttr", 1234)
.withList("listAtr","abc", "123")
.withMap("mapAttr",
new ValueMap()
.withString("key1", "value1")
.withInt("key2", 999))
.withNull("nullAttr")
.withNumber("numberAttr", 999.1234)
.withString("stringAttr", "bla")
.withStringSet("stringSetAttr", "da","di","foo","bar","bazz")
;
return item;
}
}
| 7,295 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/C_GetItemTest.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.quickstart;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
/**
* Sample code to get item from DynamoDB table.
*/
public class C_GetItemTest extends AbstractQuickStart {
@Before
public void before() {
new B_PutItemTest().howToPutItems();
}
@Test
public void howToGetItems() {
Table table = dynamo.getTable(TABLE_NAME);
for (int i=1; i <= 10; i++) {
Item item = table.getItem(
HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i);
System.out.println("========== item " + i + " ==========");
System.out.println(item);
byte[] binary = item.getBinary("binary");
System.out.println("binary: " + Arrays.toString(binary));
Set<byte[]> binarySet = item.getBinarySet("binarySet");
for (byte[] ba: binarySet) {
System.out.println("binary set element: " + Arrays.toString(ba));
}
boolean bTrue = item.getBoolean("booleanTrue");
System.out.println("booleanTrue: " + bTrue);
int intval = item.getInt("intAttr");
System.out.println("intAttr: " + intval);
List<Object> listval = item.getList("listAtr");
System.out.println("listAtr: " + listval);
Map<String,Object> mapval = item.getMap("mapAttr");
System.out.println("mapAttr: " + mapval);
Object nullval = item.get("nullAttr");
System.out.println("nullAttr: " + nullval);
BigDecimal numval = item.getNumber("numberAttr");
System.out.println("numberAttr: " + numval);
String strval = item.getString("stringAttr");
System.out.println("stringAttr: " + strval);
Set<String> strset = item.getStringSet("stringSetAttr");
System.out.println("stringSetAttr: " + strset);
}
}
@Test
public void howToUseProjectionExpression() {
Table table = dynamo.getTable(TABLE_NAME);
for (int i=1; i <= 10; i++) {
Item item = table.getItem(
HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i,
// Here is the projection expression to select 3 attributes
// to be returned.
// This expression requires attribute name substitution for
// "binary" which is a reserved word in DynamoDB
"#binary, intAttr, stringAttr",
new NameMap().with("#binary", "binary"));
System.out.println("========== item " + i + " ==========");
System.out.println(item);
byte[] binary = item.getBinary("binary");
System.out.println("binary: " + Arrays.toString(binary));
int intval = item.getInt("intAttr");
System.out.println("intAttr: " + intval);
Set<String> strset = item.getStringSet("stringSetAttr");
System.out.println("stringSetAttr: " + strset);
}
}
@Test
public void howToUseGetItemSpec() {
Table table = dynamo.getTable(TABLE_NAME);
for (int i=1; i <= 10; i++) {
Item item = table.getItem(new GetItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "foo", RANGE_KEY_NAME, i)
.withProjectionExpression("#binary, intAttr, stringAttr")
.withNameMap(new NameMap().with("#binary", "binary")));
System.out.println("========== item " + i + " ==========");
System.out.println(item);
byte[] binary = item.getBinary("binary");
System.out.println("binary: " + Arrays.toString(binary));
int intval = item.getInt("intAttr");
System.out.println("intAttr: " + intval);
Set<String> strset = item.getStringSet("stringSetAttr");
System.out.println("stringSetAttr: " + strset);
}
}
@Test
public void getNonExistentItem() {
Table table = dynamo.getTable(TABLE_NAME);
Item item = table.getItem(
HASH_KEY_NAME, "bar", RANGE_KEY_NAME, 99);
Assert.assertNull(item);
}
}
| 7,296 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/I_BatchWriteItemTest.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.quickstart;
import java.util.List;
import java.util.Map;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.amazonaws.services.dynamodbv2.document.BatchWriteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemCollection;
import com.amazonaws.services.dynamodbv2.document.RangeKeyCondition;
import com.amazonaws.services.dynamodbv2.document.TableWriteItems;
import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart;
import com.amazonaws.services.dynamodbv2.model.WriteRequest;
/**
* Sample code to perform batch write item to DynamoDB.
*/
public class I_BatchWriteItemTest extends AbstractQuickStart {
@Before
public void before() throws InterruptedException {
F_UpdateItemTest.setupData(dynamo);
new B_PutItemTest().howToPutItems();
ItemCollection<?> itemCol = dynamo.getTable(TABLE_NAME)
.query(HASH_KEY_NAME, "foo",
new RangeKeyCondition(RANGE_KEY_NAME).between(1, 5));
int count = 0;
for (Item item: itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 5);
}
@Test
public void howToBatchWrite_ToOneTable() {
TableWriteItems tableWriteItems =
new TableWriteItems(TABLE_NAME)
// you can add a bunch of keys to delete in one go
.withHashAndRangeKeysToDelete(HASH_KEY_NAME, RANGE_KEY_NAME,
"foo", 1,
"foo", 2,
"foo", 3)
// you can add a bunch of items to put in one go
.withItemsToPut(
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 111)
.withString("someStringAttr", "someStrVal1")
.withInt("someIntAttr", 111),
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 222)
.withString("someStringAttr", "someStrVal2")
.withInt("someIntAttr", 222),
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 333)
.withString("someStringAttr", "someStrVal3")
.withInt("someIntAttr", 333))
// or you can take it slow and add one key to delete at a time
.addHashAndRangePrimaryKeyToDelete(
HASH_KEY_NAME, "foo", RANGE_KEY_NAME, 4)
.addHashAndRangePrimaryKeyToDelete(
HASH_KEY_NAME, "foo", RANGE_KEY_NAME, 5)
// or you can take it slow and add one item to put at a time
.addItemToPut(new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 444)
.withString("someStringAttr", "someStrVal4")
.withInt("someIntAttr", 444))
.addItemToPut(new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 555)
.withString("someStringAttr", "someStrVal5")
.withInt("someIntAttr", 555))
;
BatchWriteItemOutcome outcome = dynamo.batchWriteItem(tableWriteItems);
System.out.println(outcome);
verify_BatchWrite_ToOneTable();
}
private void verify_BatchWrite_ToOneTable() {
{ // Verify the 5 items put via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(TABLE_NAME)
.query(HASH_KEY_NAME, "TestingPutItemInBatch",
new RangeKeyCondition(RANGE_KEY_NAME).between(111, 555));
int count = 0;
for (Item item: itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 5);
}
{ // Verify the 5 keys deleted via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(TABLE_NAME)
.query(HASH_KEY_NAME, "foo",
new RangeKeyCondition(RANGE_KEY_NAME).between(1, 5));
int count = 0;
for (Item item : itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 0);
}
}
@Test
public void howToBatchWrite_ToMultiTables() {
BatchWriteItemOutcome outcome = dynamo.batchWriteItem(
// 1st table
new TableWriteItems(TABLE_NAME)
.withHashAndRangeKeysToDelete(HASH_KEY_NAME, RANGE_KEY_NAME,
"foo", 1,
"foo", 2)
.withItemsToPut(
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 666)
.withString("someStringAttr", "someStrVal6")
.withInt("someIntAttr", 666),
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 777)
.withString("someStringAttr", "someStrVal7")
.withInt("someIntAttr", 777)),
// 2nd table
new TableWriteItems(F_UpdateItemTest.TABLE_NAME)
.withHashAndRangeKeysToDelete(F_UpdateItemTest.HASH_KEY, F_UpdateItemTest.RANGE_KEY,
F_UpdateItemTest.FIRST_CUSTOMER_ID, F_UpdateItemTest.ADDRESS_TYPE_HOME,
F_UpdateItemTest.FIRST_CUSTOMER_ID, F_UpdateItemTest.ADDRESS_TYPE_WORK)
.withItemsToPut(
new Item()
.withPrimaryKey(F_UpdateItemTest.HASH_KEY, 111,
F_UpdateItemTest.RANGE_KEY, F_UpdateItemTest.ADDRESS_TYPE_HOME)
.withString("AddressLine1", "crazy ave")
.withString("city", "crazy city")
.withString("state", "XX")
.withInt("zipcode", 99199),
new Item()
.withPrimaryKey(F_UpdateItemTest.HASH_KEY, 111,
F_UpdateItemTest.RANGE_KEY, F_UpdateItemTest.ADDRESS_TYPE_WORK)
.withString("AddressLine1", "silly ave")
.withString("city", "silly city")
.withString("state", "YY")
.withInt("zipcode", 11911)));
System.out.println(outcome);
verify_BatchWrite_ToMultiTables();
}
private void verify_BatchWrite_ToMultiTables() {
{ // Verify the 2 items put to the 1st table via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(TABLE_NAME)
.query(HASH_KEY_NAME, "TestingPutItemInBatch",
new RangeKeyCondition(RANGE_KEY_NAME).between(666, 777));
int count = 0;
for (Item item: itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 2);
}
{ // Verify the 2 keys deleted from the 1st table via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(TABLE_NAME)
.query(HASH_KEY_NAME, "foo",
new RangeKeyCondition(RANGE_KEY_NAME).between(1, 2));
int count = 0;
for (Item item : itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 0);
}
{ // Verify the 2 items put to the 2nd table via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(F_UpdateItemTest.TABLE_NAME)
.query(F_UpdateItemTest.HASH_KEY, 111);
int count = 0;
for (Item item: itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 2);
}
{ // Verify the 2 keys deleted from the 1st table via the batch operation
ItemCollection<?> itemCol = dynamo.getTable(F_UpdateItemTest.TABLE_NAME)
.query(F_UpdateItemTest.HASH_KEY, F_UpdateItemTest.FIRST_CUSTOMER_ID);
int count = 0;
for (Item item : itemCol) {
System.out.println(item);
count++;
}
Assert.assertTrue(count == 0);
}
}
@Test
public void howToHandle_UnprocessedItems() throws InterruptedException {
TableWriteItems tableWriteItems =
new TableWriteItems(TABLE_NAME)
// you can add a bunch of keys to delete in one go
.withHashAndRangeKeysToDelete(HASH_KEY_NAME, RANGE_KEY_NAME,
"foo", 1,
"foo", 2,
"foo", 3)
// you can add a bunch of items to put in one go
.withItemsToPut(
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 111)
.withString("someStringAttr", "someStrVal1")
.withInt("someIntAttr", 111),
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 222)
.withString("someStringAttr", "someStrVal2")
.withInt("someIntAttr", 222),
new Item()
.withPrimaryKey(HASH_KEY_NAME, "TestingPutItemInBatch", RANGE_KEY_NAME, 333)
.withString("someStringAttr", "someStrVal3")
.withInt("someIntAttr", 333));
// unprocessed items from DynamoDB
Map<String, List<WriteRequest>> unprocessed = null ;
int attempts = 0;
do {
if (attempts > 0) {
// exponential backoff per DynamoDB recommendation
Thread.sleep((1 << attempts) * 1000);
}
attempts++;
BatchWriteItemOutcome outcome;
if (unprocessed == null || unprocessed.size() > 0) {
// handle initial request
outcome = dynamo.batchWriteItem(tableWriteItems);
} else {
// handle unprocessed items
outcome = dynamo.batchWriteItemUnprocessed(unprocessed);
}
System.out.println("outcome: " + outcome);
unprocessed = outcome.getUnprocessedItems();
System.out.println("unprocessed: " + unprocessed);
} while (unprocessed.size() > 0);
}
}
| 7,297 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/B_PutItemJacksonTest.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.quickstart;
import org.junit.Test;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.AbstractQuickStart;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
public class B_PutItemJacksonTest extends AbstractQuickStart {
@Test
public void howToPutItems_withJSONDoc() {
String json = "{"
+ "\"person_id\" : 123 ,"
+ "\"last_name\" : \"Barr\" ,"
+ "\"first_name\" : \"Jeff\" ,"
+ "\"current_city\" : \"Tokyo\" ,"
+ "\"next_haircut\" : {"
+ "\"year\" : 2014 ,"
+ "\"month\" : 10 ,"
+ "\"day\" : 30"
+ "} ,"
+ "\"children\" :"
+ "[ \"SJB\" , \"ASB\" , \"CGB\" , \"BGB\" , \"GTB\" ]"
+ "}"
;
Table table = dynamo.getTable(TABLE_NAME);
Item item = new Item()
.withPrimaryKey(HASH_KEY_NAME, "howToPutItems_withJSONDoc", RANGE_KEY_NAME, 1)
// Store JSON document
.withJSON("document", json);
table.putItem(item);
// Retrieve the entire document and the entire document only
Item documentItem = table.getItem(new GetItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPutItems_withJSONDoc", RANGE_KEY_NAME, 1)
.withAttributesToGet("document"));
System.out.println(documentItem.getJSON("document"));
// Output: {"last_name":"Barr","children":["SJB","ASB","CGB","BGB","GTB"],"first_name":"Jeff","person_id":123,"current_city":"Tokyo","next_haircut":{"month":10,"year":2014,"day":30}}
System.out.println(documentItem.getJSONPretty("document"));
// Output:
// {
// "last_name" : "Barr",
// "children" : [ "SJB", "ASB", "CGB", "BGB", "GTB" ],
// "first_name" : "Jeff",
// "person_id" : 123,
// "current_city" : "Tokyo",
// "next_haircut" : {
// "month" : 10,
// "year" : 2014,
// "day" : 30
// }
// } // Retrieve part of a document. Perhaps I need the next_haircut and nothing else
Item partialDocItem = table.getItem(new GetItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPutItems_withJSONDoc", RANGE_KEY_NAME, 1)
.withProjectionExpression("document.next_haircut"))
;
System.out.println(partialDocItem);
// Output: { Item: {document={next_haircut={month=10, year=2014, day=30}}} }
// I can update part of a document. Here's how I would change my current_city back to Seattle:
table.updateItem(new UpdateItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPutItems_withJSONDoc", RANGE_KEY_NAME, 1)
.withUpdateExpression("SET document.current_city = :city")
.withValueMap(new ValueMap().withString(":city", "Seattle"))
);
// Retrieve the entire item
Item itemUpdated = table.getItem(HASH_KEY_NAME, "howToPutItems_withJSONDoc", RANGE_KEY_NAME, 1);
System.out.println(itemUpdated);
// Output: { Item: {document={last_name=Bar, children=[SJB, ASB, CGB, BGB, GTB], first_name=Jeff, current_city=Seattle, next_haircut={month=10, year=2014, day=30}}, myRangeKey=1, myHashKey=B_PutItemJsonTest} }
System.out.println(itemUpdated.getJSONPretty("document"));
// Output:
// {
// "last_name" : "Barr",
// "children" : [ "SJB", "ASB", "CGB", "BGB", "GTB" ],
// "first_name" : "Jeff",
// "current_city" : "Seattle",
// "person_id" : 123,
// "next_haircut" : {
// "month" : 10,
// "year" : 2014,
// "day" : 30
// }
// }
}
@Test
public void howToPut_TopLevelJSON() {
String json = "{"
+ "\"person_id\" : 123 ,"
+ "\"last_name\" : \"Barr\" ,"
+ "\"first_name\" : \"Jeff\" ,"
+ "\"current_city\" : \"Tokyo\" ,"
+ "\"next_haircut\" : {"
+ "\"year\" : 2014 ,"
+ "\"month\" : 10 ,"
+ "\"day\" : 30"
+ "} ,"
+ "\"children\" :"
+ "[ \"SJB\" , \"ASB\" , \"CGB\" , \"BGB\" , \"GTB\" ]"
+ "}"
;
Table table = dynamo.getTable(TABLE_NAME);
Item item = Item.fromJSON(json)
// We don't even need to set the primary key if it's already included in the JSON document
.withPrimaryKey(HASH_KEY_NAME, "howToPut_TopLevelJSON", RANGE_KEY_NAME, 1);
table.putItem(item);
// Retrieve the entire document and the entire document only
Item documentItem = table.getItem(new GetItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPut_TopLevelJSON", RANGE_KEY_NAME, 1));
System.out.println(documentItem.toJSON());
// Output: {"first_name":"Jeff","myRangeKey":1,"person_id":123,"current_city":"Tokyo","next_haircut":{"month":10,"year":2014,"day":30},"last_name":"Barr","children":["SJB","ASB","CGB","BGB","GTB"],"myHashKey":"howToPut_TopLevelJSON"}
System.out.println(documentItem.toJSONPretty());
// Output:
// {
// "first_name" : "Jeff",
// "myRangeKey" : 1,
// "person_id" : 123,
// "current_city" : "Tokyo",
// "next_haircut" : {
// "month" : 10,
// "year" : 2014,
// "day" : 30
// },
// "last_name" : "Barr",
// "children" : [ "SJB", "ASB", "CGB", "BGB", "GTB" ],
// "myHashKey" : "howToPut_TopLevelJSON"
// }
// Retrieve part of a document. Perhaps I need the next_haircut and nothing else
Item partialDocItem = table.getItem(new GetItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPut_TopLevelJSON", RANGE_KEY_NAME, 1)
.withProjectionExpression("next_haircut"))
;
System.out.println(partialDocItem);
// Output: { Item: {next_haircut={month=10, year=2014, day=30}} }
// I can update part of a document. Here's how I would change my current_city back to Seattle:
table.updateItem(new UpdateItemSpec()
.withPrimaryKey(HASH_KEY_NAME, "howToPut_TopLevelJSON", RANGE_KEY_NAME, 1)
.withUpdateExpression("SET current_city = :city")
.withValueMap(new ValueMap().withString(":city", "Seattle"))
);
// Retrieve the entire item
Item itemUpdated = table.getItem(HASH_KEY_NAME, "howToPut_TopLevelJSON", RANGE_KEY_NAME, 1);
System.out.println(itemUpdated);
// Output: { Item: {first_name=Jeff, myRangeKey=1, person_id=123, current_city=Seattle, next_haircut={month=10, year=2014, day=30}, last_name=Barr, children=[SJB, ASB, CGB, BGB, GTB], myHashKey=howToPut_TopLevelJSON} }
System.out.println(itemUpdated.toJSONPretty());
// Output:
// {
// "first_name" : "Jeff",
// "myRangeKey" : 1,
// "person_id" : 123,
// "current_city" : "Seattle",
// "next_haircut" : {
// "month" : 10,
// "year" : 2014,
// "day" : 30
// },
// "last_name" : "Barr",
// "children" : [ "SJB", "ASB", "CGB", "BGB", "GTB" ],
// "myHashKey" : "howToPut_TopLevelJSON"
// }
}
}
| 7,298 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.sdk.ui/samples/AmazonDynamoDBDocumentAPI/quick-start/com/amazonaws/services/dynamodbv2/document/quickstart/F_UpdateItemTest.java | /*
* Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.document.quickstart;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.Arrays;
import java.util.Set;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.AttributeUpdate;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Expected;
import com.amazonaws.services.dynamodbv2.document.GetItemOutcome;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.document.spec.GetItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.FluentHashSet;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
/**
* Sample code to update items to a dynamo table.
*/
public class F_UpdateItemTest {
private static DynamoDB dynamo;
public static final String TABLE_NAME = "F_UpdateItemTest";
public static final String HASH_KEY = "customer_id";
public static final String RANGE_KEY = "address_type";
private static final long READ_CAPACITY = 1;
private static final long WRITE_CAPACITY = 1;
public static final long FIRST_CUSTOMER_ID = 1000L;
public static final String ADDRESS_TYPE_HOME = "home";
public static final String ADDRESS_TYPE_WORK = "work";
@BeforeClass
public static void setUp() throws Exception {
AmazonDynamoDBClient client = new AmazonDynamoDBClient(awsTestCredentials());
dynamo = new DynamoDB(client);
setupData(dynamo);
}
static void setupData(DynamoDB dynamo) throws InterruptedException {
createTable(dynamo);
fillInData(dynamo);
}
private static void createTable(DynamoDB dynamo) throws InterruptedException {
Table table = dynamo.getTable(TABLE_NAME);
TableDescription desc = table.waitForActiveOrDelete();
if (desc == null) {
// table doesn't exist; let's create it
KeySchemaElement hashKey =
new KeySchemaElement(HASH_KEY, KeyType.HASH);
KeySchemaElement rangeKey =
new KeySchemaElement(RANGE_KEY, KeyType.RANGE);
CreateTableRequest createTableRequest =
new CreateTableRequest(TABLE_NAME, Arrays.asList(hashKey, rangeKey))
.withAttributeDefinitions(
new AttributeDefinition(HASH_KEY, ScalarAttributeType.N),
new AttributeDefinition(RANGE_KEY, ScalarAttributeType.S))
.withProvisionedThroughput(
new ProvisionedThroughput(READ_CAPACITY, WRITE_CAPACITY));
table = dynamo.createTable(createTableRequest);
table.waitForActive();
}
}
private static void fillInData(DynamoDB dynamo) {
Table table = dynamo.getTable(TABLE_NAME);
table.putItem(new Item().withLong(HASH_KEY, FIRST_CUSTOMER_ID)
.withString(RANGE_KEY, ADDRESS_TYPE_WORK)
.withString("AddressLine1", "1918 8th Aven")
.withString("city", "seattle")
.withString("state", "WA")
.withInt("zipcode", 98104));
table.putItem(new Item().withLong(HASH_KEY, FIRST_CUSTOMER_ID)
.withString(RANGE_KEY, ADDRESS_TYPE_HOME)
.withString("AddressLine1", "15606 NE 40th ST")
.withString("city", "redmond")
.withString("state", "WA")
.withInt("zipcode", 98052));
}
@Test
public void howToAddElementsToSet() {
Table table = dynamo.getTable(TABLE_NAME);
// Add a set of phone numbers to the attribute "phone"
final String phoneNumber1 = "123-456-7890";
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("phone").put(new FluentHashSet<String>(phoneNumber1)));
GetItemOutcome outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true)
);
Item item = outcome.getItem();
Set<String> phoneNumbers = item.getStringSet("phone");
assertTrue(1 == phoneNumbers.size());
System.out.println(phoneNumbers);
// Add a 2nd phone number to the set
final String phoneNumber2 = "987-654-3210";
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("phone").addElements(phoneNumber2));
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
phoneNumbers = item.getStringSet("phone");
System.out.println(phoneNumbers);
assertTrue(2== phoneNumbers.size());
// removes the 2nd phone number from the set
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("phone").removeElements(phoneNumber2));
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
phoneNumbers = item.getStringSet("phone");
System.out.println(phoneNumbers);
assertTrue(1 == phoneNumbers.size());
// deletes the phone attribute
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("phone").delete());
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
phoneNumbers = item.getStringSet("phone");
assertNull(phoneNumbers);
}
@Test
public void howToAddNumerically() {
Table table = dynamo.getTable(TABLE_NAME);
GetItemOutcome outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true)
);
Item item = outcome.getItem();
final int oldZipCode = item.getInt("zipcode");
// Increments the zip code attribute
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("zipcode").addNumeric(1));
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
int newZipCode = item.getInt("zipcode");
assertEquals(oldZipCode + 1, newZipCode);
// Decrements the zip code attribute
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
new AttributeUpdate("zipcode").addNumeric(-1));
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
newZipCode = item.getInt("zipcode");
assertEquals(oldZipCode, newZipCode);
}
@Test
public void howToSpecifyUpdateConditions() {
final String phoneNumberToAdd = "987-654-3210";
Table table = dynamo.getTable(TABLE_NAME);
System.out.println(table.getItemOutcome(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK));
try {
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
// Specifies the criteria that the "phone" attribute must exist
// as a precondition to adding the phone number
Arrays.asList(new Expected("phone").exists()),
// Adds the phone number if the expectation is satisfied
new AttributeUpdate("phone").addElements(phoneNumberToAdd));
fail("Update Should fail as the phone number attribute is not present in the row");
} catch (AmazonServiceException expected) {
// Failed the criteria as expected
}
}
@Test
public void howToUseUpdateExpression() {
Table table = dynamo.getTable(TABLE_NAME);
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
// update expression
"set #phoneAttributeName = :phoneAtributeValue",
new NameMap().with("#phoneAttributeName", "phone"),
new ValueMap().withStringSet(":phoneAtributeValue",
"123-456-7890", "987-654-3210")
);
GetItemOutcome outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
Item item = outcome.getItem();
Set<String> phoneNumbers = item.getStringSet("phone");
assertTrue(phoneNumbers.size() == 2);
System.out.println(phoneNumbers);
}
@Test
public void howToUseConditionExpression() {
Table table = dynamo.getTable(TABLE_NAME);
GetItemOutcome outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
Item item = outcome.getItem();
System.out.println(item);
table.updateItem(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK,
// update expression (list_append: concatenate two lists.)
"set phone = list_append(:a, :b)",
// condition expression
"zipcode = :zipcode",
null,
new ValueMap()
.withInt(":zipcode", 98104)
.withList(":a", "phone-1", "phone-2")
.withList(":b", "phone-3", "phone-4")
);
outcome = table.getItemOutcome(new GetItemSpec()
.withPrimaryKey(HASH_KEY, FIRST_CUSTOMER_ID, RANGE_KEY, ADDRESS_TYPE_WORK)
.withConsistentRead(true));
item = outcome.getItem();
System.out.println(item);
}
@AfterClass
public static void shutDown() {
// Table table = dynamo.getTable(TABLE_NAME);
// table.delete();
dynamo.shutdown();
}
protected static AWSCredentials awsTestCredentials() {
try {
return new PropertiesCredentials(new File(
System.getProperty("user.home")
+ "/.aws/awsTestAccount.properties"));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 7,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.