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.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/TextWizardPageInput.java | /*
* Copyright 2008-2013 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.core.ui.wizards;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.ui.swt.Colors;
import com.amazonaws.eclipse.core.ui.swt.CompositeBuilder;
import com.amazonaws.eclipse.core.ui.swt.LabelBuilder;
import com.amazonaws.eclipse.core.ui.swt.PostBuildHook;
import com.amazonaws.eclipse.core.ui.swt.TextBuilder;
import com.amazonaws.eclipse.core.ui.swt.WidgetUtils;
/**
* A text input for a CompositeWizardPage. Generates UI for taking a single
* text input, runs pluggable validation strategies whenever the value in the
* text box changes, and generates UI decorations indicating whether the
* value is valid or not.
*/
public class TextWizardPageInput implements WizardPageInput {
private final String labelText;
private final String descriptionText;
private final IObservableValue observableValue;
private final TwoPhaseValidator validator;
/**
* Construct a new TextWizardPageInput.
*
* @param labelText the text for the label describing the input field
* @param syncValidator optional synchronous validation strategy
* @param asyncValidator optional async validation strategy
*/
public TextWizardPageInput(final String labelText,
final String descriptionText,
final InputValidator syncValidator,
final InputValidator asyncValidator) {
if (labelText == null) {
throw new IllegalArgumentException("labelText cannot be null");
}
this.labelText = labelText;
this.descriptionText = descriptionText;
this.observableValue = new WritableValue();
this.validator = new TwoPhaseValidator(
observableValue,
syncValidator,
asyncValidator
);
}
/** {@inheritDoc} */
@Override
public void init(final Composite parent,
final DataBindingContext context) {
createLabelColumn(parent);
PostBuildHook<Text> bindInputHook = new PostBuildHook<Text>() {
@Override
public void run(final Text value) {
context.bindValue(
observableValue,
SWTObservables.observeText(value, SWT.Modify)
);
context.addValidationStatusProvider(validator);
ErrorDecorator.bind(value, validator.getValidationStatus());
}
};
createInputColumn(parent, bindInputHook);
}
/** {@inheritDoc} */
@Override
public Object getValue() {
return observableValue.getValue();
}
/** {@inheritDoc} */
@Override
public void dispose() {
// Nothing to do here.
}
/**
* Create the label column, containing a basic description of each input
* field. Indent the label down a couple pixels from the top of the row so
* it lines up better with the center of the text box in the input column.
*
* @param parent the parent composite to add to
*/
private void createLabelColumn(final Composite parent) {
WidgetUtils.indentDown(
new LabelBuilder(labelText),
5 // pixels of indent
)
.build(parent);
}
/**
* Create the input column, containing the input text box and the long
* description text (if applicable) stacked on top of one another. Extend
* this column to take up any space in the wizard page not claimed by
* the label column.
*
* @param parent the parent composite to add to
* @return the input text box that was created
*/
private void createInputColumn(final Composite parent,
final PostBuildHook<Text> inputHook) {
CompositeBuilder column = WidgetUtils.column(
new TextBuilder()
.withFullHorizontalFill()
.withPostBuildHook(inputHook)
);
if (descriptionText != null) {
column.withChild(WidgetUtils.indentRight(
new LabelBuilder(descriptionText, Colors.GRAY),
5 // pixels of indent
));
}
column.build(parent);
}
}
| 7,600 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/wizards/WizardWidgetFactory.java | package com.amazonaws.eclipse.core.ui.wizards;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class WizardWidgetFactory {
public static ControlDecoration newControlDecoration(Control control, String message) {
ControlDecoration decoration = new ControlDecoration(control, SWT.LEFT | SWT.TOP);
decoration.setDescriptionText(message);
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault()
.getFieldDecoration(FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
return decoration;
}
public static Group newGroup(Composite parent, String text) {
return newGroup(parent, text, 1);
}
public static Group newGroup(Composite parent, String text, int colspan) {
return newGroup(parent, text, colspan, 1);
}
public static Group newGroup(Composite parent, String text, int colspan, int cols) {
Group group = new Group(parent, SWT.NONE);
group.setText(text);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.horizontalSpan = colspan;
group.setLayoutData(gridData);
group.setLayout(new GridLayout(cols, false));
return group;
}
public static Composite newComposite(Composite parent, int colspan, int cols) {
return newComposite(parent, colspan, cols, false);
}
public static Composite newComposite(Composite parent, int colspan, int cols, boolean columnsEqualWidth) {
Composite composite = new Composite(parent, SWT.NONE);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.horizontalSpan = colspan;
composite.setLayoutData(gridData);
composite.setLayout(new GridLayout(cols, columnsEqualWidth));
return composite;
}
public static SashForm newSashForm(Composite parent, int colspan, int cols) {
SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL);
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true);
gridData.horizontalSpan = colspan;
gridData.widthHint = 300;
gridData.heightHint = 200;
sashForm.setLayoutData(gridData);
sashForm.setLayout(new GridLayout(cols, false));
return sashForm;
}
public static Text newText(Composite parent) {
return newText(parent, "");
}
public static Text newText(Composite parent, String value) {
return newText(parent, value, 1);
}
public static Text newText(Composite parent, String value, int colspan) {
Text text = new Text(parent, SWT.BORDER);
GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
gridData.horizontalSpan = colspan;
text.setLayoutData(gridData);
text.setText(value);
return text;
}
public static Label newLabel(Composite parent, String text) {
return newLabel(parent, text, 1);
}
public static Label newFillingLabel(Composite parent, String text) {
return newFillingLabel(parent, text, 1);
}
public static Label newFillingLabel(Composite parent, String text, int colspan) {
Label label = new Label(parent, SWT.WRAP);
label.setText(text);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.horizontalSpan = colspan;
gridData.widthHint = 100;
label.setLayoutData(gridData);
return label;
}
public static Label newLabel(Composite parent, String text, int colspan) {
Label label = new Label(parent, SWT.WRAP);
label.setText(text);
GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gridData.horizontalSpan = colspan;
label.setLayoutData(gridData);
return label;
}
public static Link newLink(Composite composite, Listener linkListener, String linkText, int colspan, int widthHint, int heightHint) {
Link link = new Link(composite, SWT.WRAP);
link.setText(linkText);
link.addListener(SWT.Selection, linkListener);
GridData data = new GridData(SWT.FILL, SWT.TOP, true, false);
data.horizontalSpan = colspan;
data.widthHint = widthHint;
data.heightHint = heightHint;
link.setLayoutData(data);
return link;
}
public static Link newLink(Composite composite, Listener linkListener, String linkText, int colspan) {
return newLink(composite, linkListener, linkText, colspan, 100, SWT.DEFAULT);
}
public static Combo newCombo(Composite parent) {
return newCombo(parent, 1);
}
public static List newList(Composite parent) {
return newList(parent, 1);
}
public static Combo newCombo(Composite parent, int colspan) {
Combo combo = new Combo(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
gridData.horizontalSpan = colspan;
combo.setLayoutData(gridData);
return combo;
}
public static ComboViewer newComboViewer(Composite parent) {
return newComboViewer(parent, 1);
}
public static ComboViewer newComboViewer(Composite parent, int colspan) {
ComboViewer comboViewer = new ComboViewer(parent, SWT.DROP_DOWN | SWT.READ_ONLY);
GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
gridData.horizontalSpan = colspan;
comboViewer.getCombo().setLayoutData(gridData);
return comboViewer;
}
public static Button newCheckbox(Composite parent, String text, int colspan) {
Button button = new Button(parent, SWT.CHECK);
button.setText(text);
GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gridData.horizontalSpan = colspan;
button.setLayoutData(gridData);
return button;
}
public static Button newRadioButton(Composite parent, String text, int colspan,
boolean selected, SelectionListener selectionListener) {
Button radioButton = new Button(parent, SWT.RADIO);
radioButton.setText(text);
GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gridData.horizontalSpan = colspan;
radioButton.setLayoutData(gridData);
radioButton.addSelectionListener(selectionListener);
radioButton.setSelection(selected);
return radioButton;
}
public static Button newPushButton(Composite parent, String text) {
return newPushButton(parent, text, 1);
}
public static Button newPushButton(Composite parent, String text, int colspan) {
Button pushButton = new Button(parent, SWT.PUSH);
pushButton.setText(text);
GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false);
gridData.horizontalSpan = colspan;
pushButton.setLayoutData(gridData);
return pushButton;
}
public static List newList(Composite parent, int colspan) {
List list = new List(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL);
GridData gridData = new GridData(SWT.FILL, SWT.CENTER, true, false);
gridData.horizontalSpan = colspan;
gridData.verticalSpan = 1;
gridData.heightHint = 150;
list.setLayoutData(gridData);
return list;
}
}
| 7,601 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/setupwizard/InitialSetupWizardDataModel.java | /*
* Copyright 2013 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.core.ui.setupwizard;
/**
* Simple data model to hold the data collected by the initial setup wizard.
*/
public final class InitialSetupWizardDataModel {
public static final String ACCESS_KEY_ID = "accessKeyId";
public static final String SECRET_ACCESS_KEY = "secretAccessKey";
public static final String OPEN_EXPLORER = "openExplorer";
/** Hold the users AWS access key once it's entered into the UI */
private String accessKeyId;
/** Hold the users AWS secret key once it's entered into the UI */
private String secretAccessKey;
/**
* True (the default setting) if the AWS Explorer view should be opened
* after the wizard is completed.
*/
private boolean openExplorer = true;
public boolean isOpenExplorer() {
return openExplorer;
}
public void setOpenExplorer(boolean openExplorer) {
this.openExplorer = openExplorer;
}
public String getAccessKeyId() {
return accessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
}
public String getSecretAccessKey() {
return secretAccessKey;
}
public void setSecretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
}
} | 7,602 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/setupwizard/InitialSetupUtils.java | /*
* Copyright 2013 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.core.ui.setupwizard;
import java.io.File;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Utilities for running the initial setup wizard to help users get the toolkit configured.
*/
public class InitialSetupUtils {
private static final String ACCOUNT_INITIALIZATION_FLAG_FILE = ".toolkitInitialized";
private static final String ANALYTICS_INITIALIZATION_FLAG_FILE = ".analyticsInitialized";
private static final int INIT_SETUP_WIZARD_DIALOG_WIDTH = 550;
private static final int INIT_SETUP_WIZARD_DIALOG_HEIGHT = 250;
public static void runInitialSetupWizard() {
final boolean showAccountInitPage = shouldShowAccountInitPage();
final boolean showAnalyticsInitPage = shouldShowAnalyticsInitPage();
final boolean runSetupWizard = showAccountInitPage || showAnalyticsInitPage;
if (runSetupWizard) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Shell shell = new Shell(Display.getDefault(), SWT.DIALOG_TRIM);
WizardDialog wizardDialog = new WizardDialog(shell,
new InitialSetupWizard(showAccountInitPage,
showAnalyticsInitPage, AwsToolkitCore
.getDefault().getPreferenceStore()));
wizardDialog.setPageSize(INIT_SETUP_WIZARD_DIALOG_WIDTH,
INIT_SETUP_WIZARD_DIALOG_HEIGHT);
wizardDialog.open();
if (showAccountInitPage) {
markAccountInitPageShown();
}
if (showAnalyticsInitPage) {
markAnalyticsInitPageShown();
}
}
});
}
}
private static boolean shouldShowAccountInitPage() {
boolean showAccountInitPage = !isCredentialsConfigured()
&& !doesFlagFileExist(ACCOUNT_INITIALIZATION_FLAG_FILE);
return showAccountInitPage;
}
private static boolean shouldShowAnalyticsInitPage() {
return !doesFlagFileExist(ANALYTICS_INITIALIZATION_FLAG_FILE);
}
private static void markAccountInitPageShown() {
writeFlagFile(ACCOUNT_INITIALIZATION_FLAG_FILE);
}
private static void markAnalyticsInitPageShown() {
writeFlagFile(ANALYTICS_INITIALIZATION_FLAG_FILE);
}
private static boolean isCredentialsConfigured() {
String accessKey = AwsToolkitCore.getDefault().getAccountInfo().getAccessKey();
boolean credentialsConfigured = (accessKey != null) && (accessKey.length() > 0);
return credentialsConfigured;
}
private static boolean doesFlagFileExist(String path) {
String userHome = System.getProperty("user.home");
if (userHome == null) return false;
File awsDirectory = new File(userHome, ".aws");
return new File(awsDirectory, path).exists();
}
private static void writeFlagFile(String path) {
try {
String userHome = System.getProperty("user.home");
if (userHome == null) return;
File awsDirectory = new File(userHome, ".aws");
if (!awsDirectory.exists() && awsDirectory.mkdir() == false) {
AwsToolkitCore.getDefault().logWarning("Unable to create ~/.aws directory to save toolkit initialization file", null);
} else {
File flagFile = new File(awsDirectory, path);
flagFile.createNewFile();
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logWarning("Unable to save toolkit initialization file", e);
}
}
} | 7,603 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/setupwizard/ConfigureAccountWizardPage.java | /*
* Copyright 2013 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.core.ui.setupwizard;
import java.io.IOException;
import java.util.UUID;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.preference.IPersistentPreferenceStore;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
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.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.profile.internal.BasicProfile;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesCredentialsConfiguration;
import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesFactory;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
final class ConfigureAccountWizardPage extends WizardPage {
private static final String GETTING_STARTED_GUIDE_URL = "http://docs.aws.amazon.com/AWSToolkitEclipse/latest/GettingStartedGuide/Welcome.html";
private static final String CREATE_ACCOUNT_URL = "https://portal.aws.amazon.com/gp/aws/developer/registration/index.html?ie=UTF8&utm_source=eclipse&utm_campaign=awstoolkitforeclipse&utm_medium=ide&";
private static final String SECURITY_CREDENTIALS_URL = "https://portal.aws.amazon.com/gp/aws/securityCredentials";
private final InitialSetupWizardDataModel dataModel;
private final IPreferenceStore preferenceStore;
private final DataBindingContext bindingContext = new DataBindingContext();
// Finally provide aggregate status reporting for the entire wizard page
private final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(
bindingContext, AggregateValidationStatus.MAX_SEVERITY);
private Button openExplorerCheckBox;
ConfigureAccountWizardPage(InitialSetupWizardDataModel dataModel,
IPreferenceStore preferenceStore) {
super("initialSetupWizard");
this.dataModel = dataModel;
this.preferenceStore = preferenceStore;
setTitle("Welcome to the AWS Toolkit for Eclipse");
setDescription("Configure the toolkit with your AWS account credentials");
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
setControl(composite);
WebLinkListener linkListener = new WebLinkListener();
GridDataFactory fullRowGridDataFactory = GridDataFactory.swtDefaults().align(SWT.LEFT, SWT.TOP).grab(true, false).span(2, 1);
GridDataFactory firstColumnGridDataFactory = GridDataFactory.swtDefaults().align(SWT.LEFT, SWT.CENTER);
GridDataFactory secondColumnGridDataFactory = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false);
Label label = new Label(composite, SWT.WRAP);
label.setText("Before you can start using the toolkit, you need to configure an AWS account.");
fullRowGridDataFactory.applyTo(label);
Link link = new Link(composite, SWT.WRAP);
link.addListener(SWT.Selection, linkListener);
link.setText("Use your <a href=\"" + SECURITY_CREDENTIALS_URL + "\">existing credentials</a> or " +
"<a href=\"" + CREATE_ACCOUNT_URL + "\">create a new AWS account</a>.");
fullRowGridDataFactory.applyTo(link);
// AWS Access Key ID row
Label accessKeyLabel = new Label(composite, SWT.NONE);
accessKeyLabel.setText("Access Key ID:");
firstColumnGridDataFactory.copy().indent(10, 5).applyTo(accessKeyLabel);
Text accessKeyText = new Text(composite, SWT.BORDER);
secondColumnGridDataFactory.copy().indent(0, 5).applyTo(accessKeyText);
accessKeyText.setFocus();
IObservableValue accessKeyModelObservable = PojoObservables.observeValue(dataModel, dataModel.ACCESS_KEY_ID);
bindingContext.bindValue(SWTObservables.observeText(accessKeyText, SWT.Modify), accessKeyModelObservable);
bindingContext.addValidationStatusProvider(
new ChainValidator<String>(accessKeyModelObservable, new NotEmptyValidator("Please provide an AWS Access Key ID")));
// AWS Secret Key row
Label secretKeyLabel = new Label(composite, SWT.NONE);
secretKeyLabel.setText("Secret Access Key:");
firstColumnGridDataFactory.copy().indent(10, 0).applyTo(secretKeyLabel);
Text secretKeyText = new Text(composite, SWT.BORDER);
secondColumnGridDataFactory.applyTo(secretKeyText);
IObservableValue secretKeyModelObservable = PojoObservables.observeValue(dataModel, dataModel.SECRET_ACCESS_KEY);
bindingContext.bindValue(SWTObservables.observeText(secretKeyText, SWT.Modify), secretKeyModelObservable);
bindingContext.addValidationStatusProvider(
new ChainValidator<String>(secretKeyModelObservable, new NotEmptyValidator("Please provide an AWS Secret Access Key")));
// Open Explorer view row
openExplorerCheckBox = new Button(composite, SWT.CHECK);
openExplorerCheckBox.setText("Open the AWS Explorer view");
openExplorerCheckBox.setSelection(true);
fullRowGridDataFactory.indent(0, 5).applyTo(openExplorerCheckBox);
bindingContext.bindValue(SWTObservables.observeSelection(openExplorerCheckBox), PojoObservables.observeValue(dataModel, dataModel.OPEN_EXPLORER));
Composite spacer = new Composite(composite, SWT.NONE);
spacer.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 2, 1));
link = new Link(composite, SWT.WRAP);
link.addListener(SWT.Selection, linkListener);
link.setText("For a full walkthrough of the features available in the AWS Toolkit for Eclipse, " +
"see the <a href=\"" + GETTING_STARTED_GUIDE_URL + "\">AWS Toolkit for Eclipse Getting Started Guide</a>.");
fullRowGridDataFactory.applyTo(link);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false ) return;
IStatus status = (IStatus)value;
setPageComplete(status.isOK());
}
});
setPageComplete(false);
parent.getShell().pack(true);
Rectangle workbenchBounds = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getBounds();
Point dialogSize = this.getShell().getSize();
this.getShell().setLocation(
workbenchBounds.x + (workbenchBounds.width - dialogSize.x) / 2,
workbenchBounds.y + (workbenchBounds.height - dialogSize.y) / 2);
}
public boolean performFinish() {
String internalAccountId = UUID.randomUUID().toString();
saveToCredentialsFile(internalAccountId);
preferenceStore.setValue(PreferenceConstants.P_CURRENT_ACCOUNT, internalAccountId);
preferenceStore.setValue(PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT, internalAccountId);
if (preferenceStore instanceof IPersistentPreferenceStore) {
IPersistentPreferenceStore persistentPreferenceStore = (IPersistentPreferenceStore)preferenceStore;
try {
persistentPreferenceStore.save();
} catch (IOException e) {
AwsToolkitCore.getDefault().logError("Unable to write the account information to disk", e);
}
}
AwsToolkitCore.getDefault().getAccountManager().reloadAccountInfo();
if (dataModel.isOpenExplorer()) {
openAwsExplorer();
}
return true;
}
/**
* Persist the credentials entered in the wizard to the AWS credentials file
* @param internalAccountId - Newly generated UUID to identify the account in eclipse
*/
private void saveToCredentialsFile(String internalAccountId) {
BasicProfile emptyProfile = SdkProfilesFactory.newEmptyBasicProfile(PreferenceConstants.DEFAULT_ACCOUNT_NAME);
SdkProfilesCredentialsConfiguration credentialsConfig = new SdkProfilesCredentialsConfiguration(
preferenceStore, internalAccountId, emptyProfile);
credentialsConfig.setAccessKey(dataModel.getAccessKeyId());
credentialsConfig.setSecretKey(dataModel.getSecretAccessKey());
try {
credentialsConfig.save();
} catch (AmazonClientException e) {
AwsToolkitCore.getDefault().reportException("Could not write profile information to the credentials file", e);
}
}
private void openAwsExplorer() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView(AwsToolkitCore.EXPLORER_VIEW_ID);
} catch (PartInitException e) {
AwsToolkitCore.getDefault().reportException("Unable to open the AWS Explorer view", e);
}
}
});
}
} | 7,604 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/setupwizard/InitialSetupWizard.java | /*
* Copyright 2013 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.core.ui.setupwizard;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.wizard.Wizard;
import com.amazonaws.eclipse.core.AwsToolkitCore;
public class InitialSetupWizard extends Wizard {
private final InitialSetupWizardDataModel dataModel = new InitialSetupWizardDataModel();
private final IPreferenceStore preferenceStore;
private final boolean showAccountInitPage;
private final boolean showAnalyticsInitPage;
private ConfigureAccountWizardPage configureAccountWizardPage;
private ConfigureToolkitAnalyticsWizardPage configureAnalyticsWizardPage;
public InitialSetupWizard(boolean showAccountInitPage,
boolean showAnalyticsInitPage, IPreferenceStore preferenceStore) {
this.preferenceStore = preferenceStore;
this.showAccountInitPage = showAccountInitPage;
this.showAnalyticsInitPage = showAnalyticsInitPage;
setNeedsProgressMonitor(false);
setDefaultPageImageDescriptor(
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
}
@Override
public void addPages() {
if (showAccountInitPage && configureAccountWizardPage == null) {
configureAccountWizardPage = new ConfigureAccountWizardPage(dataModel, preferenceStore);
addPage(configureAccountWizardPage);
}
if (showAnalyticsInitPage && configureAnalyticsWizardPage == null) {
configureAnalyticsWizardPage = new ConfigureToolkitAnalyticsWizardPage();
addPage(configureAnalyticsWizardPage);
}
}
@Override
public boolean performFinish() {
boolean finished = true;
if (configureAccountWizardPage != null) {
finished = finished && configureAccountWizardPage.performFinish();
}
if (configureAnalyticsWizardPage != null) {
finished = finished && configureAnalyticsWizardPage.performFinish();
}
return finished;
}
} | 7,605 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/setupwizard/ConfigureToolkitAnalyticsWizardPage.java | /*
* Copyright 2015 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.core.ui.setupwizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
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.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
final class ConfigureToolkitAnalyticsWizardPage extends WizardPage {
private Button enableAnalyticsButton;
ConfigureToolkitAnalyticsWizardPage() {
super("initializeToolkitAnalyticsWizardPage");
setTitle("Collection of Analytics");
setDescription("Help us improve AWS Toolkit by enabling analytics data collection?");
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
composite.setLayout(gridLayout);
setControl(composite);
Text description = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP);
description.setText(
"By leaving this box checked, you agree that AWS may " +
"collect analytics about your usage of AWS Toolkit (such as " +
"service/feature usage and view, UI instrumentation usage, AWS " +
"Toolkit version and user platform). AWS will use this information " +
"to improve the AWS Toolkit and other Amazon products and services " +
"and will handle all information received in accordance with the " +
"AWS Privacy Policy (<http://aws.amazon.com/privacy/>)\n" +
"When available, an AWS Account ID is associated with this information.\n");
description.setEditable(false);
description.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
enableAnalyticsButton = new Button(composite, SWT.CHECK | SWT.MULTI | SWT.WRAP);
enableAnalyticsButton.setText(
"I acknowledge the legal notice above and agree to let AWS collect" +
" analytics about my AWS Toolkit usage.");
enableAnalyticsButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
enableAnalyticsButton.setSelection(true);
}
public boolean performFinish() {
AwsToolkitCore corePlugin = AwsToolkitCore.getDefault();
if (enableAnalyticsButton.getSelection()) {
corePlugin.getPreferenceStore()
.setValue(
PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED,
true);
corePlugin.getAnalyticsManager().setEnabled(true);
} else {
corePlugin.getPreferenceStore()
.setValue(
PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED,
false);
corePlugin.getAnalyticsManager().setEnabled(false);
}
return true;
}
}
| 7,606 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/HyperlinkHandler.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.core.ui.overview;
import java.net.URL;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.swt.program.Program;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Generic hyperlink handler that knows how to handle basic link href actions.
* <p>
* <b>HTTP/HTTPS web links</b> - Hyperlink hrefs starting with "http" will be
* treated as a web URL and opened in an external web browser.
* <p>
* <b>Eclipse preference page links</b> - Hyperlink hrefs starting with
* "preference:" will open Eclipse's preference dialog to the specified
* preference page (ex: 'preference:com.foo.bar.preference-id').
* <p>
* <b>Eclipse help links</b> - Hyperlink hrefs starting with "help:" will open
* Eclipse's help system to the specified help content (ex:
* 'help:com.foo.bar.preference-id').
* <p>
* <b>Email links</b> - Hyperlink hrefs starting with "mailto:" will open
* up a a new email message in the system's default email client.
*/
public final class HyperlinkHandler extends HyperlinkAdapter {
/* (non-Javadoc)
* @see org.eclipse.ui.forms.events.HyperlinkAdapter#linkActivated(org.eclipse.ui.forms.events.HyperlinkEvent)
*/
@Override
public void linkActivated(HyperlinkEvent event) {
String href = (String)event.getHref();
if (href == null) return;
String resource = href.substring(href.indexOf(":") + 1);
if (href.startsWith("http")) {
int browserStyle = IWorkbenchBrowserSupport.LOCATION_BAR
| IWorkbenchBrowserSupport.AS_EXTERNAL
| IWorkbenchBrowserSupport.STATUS
| IWorkbenchBrowserSupport.NAVIGATION_BAR;
IWorkbenchBrowserSupport browserSupport = PlatformUI.getWorkbench().getBrowserSupport();
try {
browserSupport.createBrowser(browserStyle, null, null, null)
.openURL(new URL(href));
} catch (Exception e) {
AwsToolkitCore.getDefault().reportException("Unable to open external web browser", e);
}
} else if (href.startsWith("preference:")) {
PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(
null, resource, new String[] {resource}, null);
dialog.open();
} else if (href.startsWith("help:")) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(resource);
} else if (href.startsWith("mailto:")) {
Program.launch(href);
}
}
}
| 7,607 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/OverviewEditor.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.core.ui.overview;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
/**
* Editor displaying the AWS Toolkit for Eclipse Overview page.
*/
public class OverviewEditor extends EditorPart {
private Composite overviewComposite;
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public void init(IEditorSite site, IEditorInput input)
throws PartInitException {
setSite(site);
setInput(input);
}
@Override
public boolean isDirty() {
return false;
}
@Override
public void dispose() {
if (overviewComposite != null)
overviewComposite.dispose();
super.dispose();
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
overviewComposite = new FormsOverviewComposite(parent);
}
@Override
public void setFocus() {}
}
| 7,608 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/OverviewSection.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.core.ui.overview;
import org.eclipse.swt.widgets.Composite;
/**
* Represents a contributed section in the AWS Toolkit Overview view. Components
* of the AWS Toolkit for Eclipse can extend this class and use the
* com.amazonaws.eclipse.core.overview extension point to register their
* overview section and have it appear in the AWS Toolkit Overview view.
*/
public abstract class OverviewSection {
/**
* Marker interface for overview sections that support version 2 of the AWS
* Toolkit for Eclipse overview page.
*/
public static interface V2 {}
/** AWS Toolkit for Eclipse UI toolkit for creating links, labels, etc. */
protected final Toolkit toolkit = new Toolkit();
/** Shared resources for all overview page components (images, fonts, colors, etc) */
protected OverviewResources resources;
/**
* Sets the shared overview page resources for this overview section.
*
* @param resources
* The shared overview page resources.
*/
public void setResources(OverviewResources resources) {
this.resources = resources;
toolkit.setResources(resources);
}
/**
* The AWS Toolkit Overview view will call this method on each overview
* section that has registered and overviewSection extension for the
* com.amazonaws.eclipse.core.overview extension point to allow the
* implementation to fill in it's content.
*
* @param parent
* The parent composite in which this OverviewSection
* implementation should create it's content.
*/
public abstract void createControls(Composite parent);
}
| 7,609 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/HeaderComposite.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.core.ui.overview;
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.Label;
import org.eclipse.ui.forms.widgets.TableWrapData;
/**
* Composite for creating the header on the AWS Toolkit for Eclipse overview
* page.
*/
class HeaderComposite extends Composite {
/**
* Constructs a new header composite for the AWS Toolkit for Eclipse
* overview page.
*
* @param parent
* The parent composite in which to create this header composite.
* @param resources
* The shared resources for creating this composite (colors,
* images, fonts, etc).
*/
public HeaderComposite(Composite parent, OverviewResources resources) {
super(parent, SWT.NONE);
setLayout(LayoutUtils.newSlimTableWrapLayout(2));
Image blueGradientImage = resources.getImage(OverviewResources.IMAGE_GRADIENT);
Image blueGradientLogoImage = resources.getImage(OverviewResources.IMAGE_GRADIENT_WITH_LOGO);
resources.getFormToolkit().createLabel(this, null)
.setImage(blueGradientLogoImage);
Composite composite = resources.getFormToolkit().createComposite(this);
composite.setBackgroundImage(blueGradientImage);
composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL_GRAB);
tableWrapData.heightHint = blueGradientImage.getImageData().height;
composite.setLayoutData(tableWrapData);
composite.setLayout(new GridLayout());
Label titleLabel = new Label(composite, SWT.NONE);
titleLabel.setText("AWS Toolkit for Eclipse");
titleLabel.setFont(resources.getFont("big-header"));
titleLabel.setForeground(resources.getColor("amazon-orange"));
titleLabel.setLayoutData(new GridData(SWT.END, SWT.END, true, true));
}
}
| 7,610 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/GettingStartedSection.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.core.ui.overview;
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.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.AwsUrls;
/**
* Getting started section for the AWS Toolkit overview page.
*/
class GettingStartedSection extends GradientBoxComposite {
/** Shared resources for the overview page components */
private final OverviewResources resources;
/**
* Constructs a new header composite for the AWS Toolkit for Eclipse
* overview page.
*
* @param parent
* The parent composite in which to create this header composite.
* @param resources
* The UI resources for creating this composite (images, colors,
* fonts, etc).
*/
public GettingStartedSection(Composite parent, OverviewResources resources) {
super(parent, resources.getFormToolkit());
this.resources = resources;
GridLayout gridLayout = new GridLayout();
gridLayout.marginBottom = 7;
headerComposite.setLayout(gridLayout);
// Header
Label headerLabel = new Label(headerComposite, SWT.NONE);
headerLabel.setText("Get Started");
headerLabel.setFont(resources.getFont("module-header"));
headerLabel.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
headerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, true, true));
// Main Body
TableWrapLayout layout = new TableWrapLayout();
layout.leftMargin = 10;
layout.rightMargin = 10;
layout.verticalSpacing = 2;
layout.topMargin = 10;
mainComposite.setLayout(layout);
mainComposite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
Label testLabel = resources.getFormToolkit().createLabel(mainComposite,
"Configure the toolkit with your access identifiers");
testLabel.setLayoutData(new TableWrapData(TableWrapData.CENTER));
testLabel.setFont(resources.getFont("text"));
Image configureButtonImage = resources.getImage(OverviewResources.IMAGE_CONFIGURE_BUTTON);
createImageHyperlink(mainComposite, configureButtonImage, null,
"preference:" + AwsToolkitCore.ACCOUNT_PREFERENCE_PAGE_ID)
.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
layout = LayoutUtils.newSlimTableWrapLayout(1);
layout.topMargin = 20;
footerComposite.setLayout(layout);
// Footer
createImageHyperlink(footerComposite,
AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_EXTERNAL_LINK),
"Sign up for Amazon Web Services", AwsUrls.SIGN_UP_URL)
.setFont(resources.getFont("text"));
}
/**
* Creates a new hyperlink, centered in the specified parent composite.
*
* @param parent
* The parent in which to create the new hyperlink.
* @param image
* Optional image to include in the hyperlink.
* @param text
* Optional text for the hyperlink.
* @param href
* Optional hyperlink href target.
*
* @return The new hyperlink widget.
*/
private ImageHyperlink createImageHyperlink(Composite parent, Image image, String text, String href) {
ImageHyperlink link = resources.getFormToolkit().createImageHyperlink(parent, SWT.RIGHT | SWT.NO_FOCUS);
link.setText(text);
link.setBackground(null);
link.setImage(image);
link.setHref(href);
link.setUnderlined(false);
link.addHyperlinkListener(new HyperlinkHandler());
TableWrapData layoutData = new TableWrapData(TableWrapData.CENTER);
layoutData.grabHorizontal = true;
link.setLayoutData(layoutData);
link.setFont(resources.getFont("text"));
return link;
}
}
| 7,611 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/GradientBoxComposite.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.core.ui.overview;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapData;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Composite that uses gradients for the top and bottom borders. Subclasses are
* expected to fill in the content through the header, main and footer
* composites in this class.
* <p>
* This composite manages its own images so that they can be released as soon as
* possible when this composite is disposed, so ensure that all instances are
* properly disposed and that subclasses correctly call super.dispose() if they
* override the dispose method.
*/
class GradientBoxComposite extends Composite {
/**
* Image registry so that any image resources are disposed of when this
* object is disposed. Assumes only one GradientBoxComposite will be used,
* so images aren't shared between multiple instances.
*/
private ImageRegistry imageRegistry = new ImageRegistry();
/** Form toolkit for creating the UI widgets */
private FormToolkit toolkit;
/** The header composite, for subclasses to populate */
protected Composite headerComposite;
/** The main composite, for subclasses to populate */
protected Composite mainComposite;
/** The footer composite, for subclasses to populate */
protected Composite footerComposite;
/**
* Creates a new GradientBoxComposite widget within the specified parent and
* using the specified form toolkit.
*
* @param parent
* The composite to contain the new GradientBoxComposite.
* @param toolkit
* The form toolkit to use for creating the UI.
*/
public GradientBoxComposite(Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.toolkit = toolkit;
initializeImageRegistry();
setLayout(LayoutUtils.newSlimTableWrapLayout(3));
createLabel("upper-left");
headerComposite = createHorizontalComposite("top");
createLabel("upper-right");
createVerticalComposite("left");
mainComposite = createHorizontalComposite(null);
createVerticalComposite("right");
createLabel("lower-left");
footerComposite = createHorizontalComposite("bottom");
createLabel("lower-right");
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
imageRegistry.dispose();
super.dispose();
}
/*
* Private Interface
*/
/**
* Creates a new label with a specified image, and sizes the label so that
* it is the same size as the image.
*
* @param imageKey
* The key of the image to use in the new label.
* @return The new label.
*/
private Label createLabel(String imageKey) {
Image image = imageRegistry.get(imageKey);
Label label = toolkit.createLabel(this, null);
label.setImage(image);
TableWrapData layoutData = new TableWrapData(TableWrapData.FILL);
layoutData.heightHint = image.getImageData().height;
layoutData.maxHeight = image.getImageData().height;
layoutData.maxWidth = image.getImageData().width;
label.setLayoutData(layoutData);
return label;
}
/**
* Creates a horizontal composite for this gradient box with the specified
* background image tiled repeatedly in the horizontal direction.
*
* @param imageKey
* The key of the image to use for the background.
* @return The new composite.
*/
private Composite createHorizontalComposite(String imageKey) {
Composite composite = toolkit.createComposite(this);
TableWrapData layoutData = new TableWrapData(TableWrapData.FILL);
if (imageKey != null) {
composite.setBackgroundImage(imageRegistry.get(imageKey));
composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
layoutData.heightHint = imageRegistry.get(imageKey).getImageData().height;
layoutData.maxWidth = imageRegistry.get(imageKey).getImageData().width;
}
composite.setLayoutData(layoutData);
return composite;
}
/**
* Creates a vertical composite for this gradient box with the specified
* background image tiled repeatedly in the vertical direction.
*
* @param imageKey
* The key of the image to use for the background.
* @return The new composite.
*/
private Composite createVerticalComposite(String imageKey) {
Composite composite = toolkit.createComposite(this);
composite.setBackgroundImage(imageRegistry.get(imageKey));
composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
TableWrapData layoutData = new TableWrapData(TableWrapData.FILL, TableWrapData.FILL);
layoutData.maxWidth = imageRegistry.get(imageKey).getImageData().width;
layoutData.grabVertical = true;
composite.setLayoutData(layoutData);
return composite;
}
/**
* Initializes the image resources used by this widget.
*/
private void initializeImageRegistry() {
imageRegistry.put("upper-left", createImageDescriptor("icons/gradient-box/upper-left.png"));
imageRegistry.put("top", createImageDescriptor("icons/gradient-box/top.png"));
imageRegistry.put("upper-right", createImageDescriptor("icons/gradient-box/upper-right.png"));
imageRegistry.put("left", createImageDescriptor("icons/gradient-box/left.png"));
imageRegistry.put("right", createImageDescriptor("icons/gradient-box/right.png"));
imageRegistry.put("lower-left", createImageDescriptor("icons/gradient-box/lower-left.png"));
imageRegistry.put("bottom", createImageDescriptor("icons/gradient-box/bottom.png"));
imageRegistry.put("lower-right", createImageDescriptor("icons/gradient-box/lower-right.png"));
}
/**
* Creates an ImageDescriptor from this plugin for the specified path.
*
* @param imagePath
* The path of the image to load.
* @return The new image descriptor.
*/
private ImageDescriptor createImageDescriptor(String imagePath) {
return ImageDescriptor.createFromURL(AwsToolkitCore.getDefault().getBundle().getEntry(imagePath));
}
}
| 7,612 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/LayoutUtils.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.core.ui.overview;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
/**
* General utilities for SWT layouts.
*/
public class LayoutUtils {
/**
* Creates a new TableWrapLayout with no margins or padding anywhere.
*
* @param numColumns
* The number of columns for the new TableWrapLayout.
*
* @return The new TableWrapLayout.
*/
public static TableWrapLayout newSlimTableWrapLayout(int numColumns) {
TableWrapLayout tableWrapLayout = new TableWrapLayout();
tableWrapLayout.numColumns = numColumns;
tableWrapLayout.bottomMargin = 0;
tableWrapLayout.horizontalSpacing = 0;
tableWrapLayout.leftMargin = 0;
tableWrapLayout.rightMargin = 0;
tableWrapLayout.topMargin = 0;
tableWrapLayout.verticalSpacing = 0;
return tableWrapLayout;
}
}
| 7,613 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/Toolkit.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.core.ui.overview;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.PreferenceLinkListener;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
/**
* UI toolkit for the AWS Toolkit Overview view components to facilitate
* creating links, labels, sections, etc.
*/
public class Toolkit {
/** Shared overview resources (images, fonts, colors, etc) */
private OverviewResources resources;
/**
* Sets the shared OverviewResources object this toolkit object will use for
* referencing shared resources like images, fonts, colors, etc.
*
* @param resources
* The shared overview resources object.
*/
void setResources(OverviewResources resources) {
this.resources = resources;
}
/**
* Creates and returns a new Label within the specified parent, with the
* specified text.
*
* @param parent
* The parent composite in which to create the new label.
* @param text
* The text to display in the label.
* @return The new label.
*/
public static Label newLabel(Composite parent, String text) {
Label l = new Label(parent, SWT.NONE);
l.setText(text);
l.setBackground(parent.getBackground());
return l;
}
/**
* Creates and returns a new Link, which when selected, will run the
* specified action.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display in the link.
* @param action
* The action to execute when the Link is selected.
* @return The new link.
*/
public static Link newActionLink(Composite parent, String text, final IAction action) {
Link link = new Link(parent, SWT.NONE);
link.setText(createAnchor(text, text));
link.setBackground(parent.getBackground());
link.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
action.run();
}
});
return link;
}
/**
* Creates and returns a new Link, which when selected, will open the
* specified preference page.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display in the link.
* @param target
* The ID of the preference page to display when this link is
* selected.
* @return The new link.
*/
public static Link newPreferenceLink(Composite parent, String text, String target) {
Link link = new Link(parent, SWT.NONE);
link.setText(createAnchor(text, target));
link.setBackground(parent.getBackground());
link.addListener(SWT.Selection, new PreferenceLinkListener());
return link;
}
/**
* Creates and returns a new Link, which when selected, will open a browser
* to a URL in the href attribute of an included anchor tag. Note that this
* method requires the caller to include an HTML anchor tag in the text they
* pass, and won't add the HTML anchor tag to the text like other methods in
* this class will.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display in the link, including an HTML anchor tag
* where the anchor's href attribute indicates what HTTP URL
* should be opened when selected.
* @return The new link.
*/
public static Link newWebLink(Composite parent, String text) {
Link link = new Link(parent, SWT.NONE);
link.setText(text);
link.setBackground(parent.getBackground());
link.addListener(SWT.Selection, new WebLinkListener());
return link;
}
/**
* Creates and returns a new Link, which when selected, will open the
* Eclipse help system to the specified target help topic of the form
* "/<plugin-id>/<path-to-help-doc>" (ex:
* "/com.amazonaws.eclipse.ec2/html/foo/help.html").
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display in the link.
* @param target
* The Eclipse help topic doc that should be opened when the link
* is selected.
* @return The new link.
*/
public static Link newHelpLink(Composite parent, String text, String target) {
Link link = new Link(parent, SWT.NONE);
link.setText(createAnchor(text, target));
link.setBackground(parent.getBackground());
link.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
PlatformUI.getWorkbench().getHelpSystem().displayHelpResource(event.text);
}
});
return link;
}
/**
* Creates and returns a link, which when selected, will open a browser to
* the specified URL.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display for the link.
* @param target
* The HTTP URL to open when the link is selected.
* @return The new link.
*/
public static Link newWebLink(Composite parent, String text, String target) {
return newWebLink(parent, createAnchor(text, target));
}
/**
* Creates and returns a link, which when selected, will run the specified
* IActionDelegate.
*
* @param parent
* The parent composite in which to create the new link.
* @param text
* The text to display for the link.
* @param delegate
* The delegate object to run when the link is selected.
* @return The new link.
*/
public static Link newActionDelegateLink(Composite parent, String text,
final IActionDelegate delegate) {
final Action proxy = new Action("runAction") {
@Override
public void run() {
delegate.run(this);
}
};
Link link = new Link(parent, SWT.NONE);
link.setText(createAnchor(text, text));
link.setBackground(parent.getBackground());
link.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
proxy.run();
}
});
return link;
}
/**
* Wraps the specified text in an HTML anchor tag, with the href attribute
* set to the specified target.
*
* @param text
* The text to wrap in an HTML anchor tag.
* @param target
* The URL to set in the href attribute of the anchor tag.
* @return The specified text wrapped in an anchor tag.
*/
public static String createAnchor(String text, String target) {
return "<a href=\"" + target + "\">" + text + "</a>";
}
/**
* Creates a new label with the image from AwsToolkitCore's ImageRegistry
* identified by the specified image ID.
*
* @param parent
* The parent composite in which to create the new label.
* @param imageId
* The ID of the image in AwsToolkitCore's ImageRegistry to
* display.
*/
public static Label newImageLabel(Composite parent, String imageId) {
Label label = new Label(parent, SWT.NONE);
label.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(imageId));
label.setBackground(parent.getBackground());
return label;
}
public ImageHyperlink newListItem(Composite parent, String text, String href) {
return newListItem(parent, text, href, null);
}
/**
* Creates a new list item in the specified parent composite. Displays a
* bulleted list item containing a hyperlink with the specified text and
* href target, and an optional associated default action to execute if the
* href target doesn't match any of the basic handlers for web links,
* Eclipse preference links, Eclipse help links, etc.
*
* @param parent
* The parent composite in which the new list item will be
* created.
* @param text
* The text for the list item hyperlink.
* @param href
* The hyperlink href target for the new list item.
* @param defaultAction
* The default action to run if the target href doesn't match any
* of the standard supported prefixes ('http', 'help:',
* 'preference:').
*
* @return The new link in the list item.
*/
public ImageHyperlink newListItem(Composite parent, String text,
String href, final IAction defaultAction) {
FormToolkit formToolkit = resources.getFormToolkit();
Composite composite = formToolkit.createComposite(parent);
TableWrapLayout layout = LayoutUtils.newSlimTableWrapLayout(2);
layout.leftMargin = 5;
composite.setLayout(layout);
composite.setLayoutData(new TableWrapData(TableWrapData.FILL));
Composite bulletComposite = formToolkit.createComposite(composite);
GridLayout bulletLayout = new GridLayout();
bulletLayout.marginTop = 8;
bulletLayout.marginHeight = 0;
bulletComposite.setLayout(bulletLayout);
Label bullet = formToolkit.createLabel(bulletComposite, null);
bullet.setImage(resources.getImage(OverviewResources.IMAGE_BULLET));
TableWrapData layoutData = new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE);
layoutData.grabVertical = true;
bullet.setLayoutData(new GridData());
ImageHyperlink link = formToolkit.createImageHyperlink(composite, SWT.RIGHT | SWT.NO_FOCUS | SWT.WRAP);
link.setText(text);
link.setHref(href);
link.setUnderlined(false);
link.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.TOP));
link.setFont(resources.getFont("text"));
// Any external links should be displayed with the external link image
if (href != null && href.startsWith("http")) {
link.setImage(OverviewResources.getExternalLinkImage());
}
/*
* Always add a hyperlink listener for the basic action prefixes
* ('http:', 'help:', 'preference:', etc.) and optionally add a default
* listener for a custom action.
*/
link.addHyperlinkListener(new HyperlinkHandler());
if (defaultAction != null) {
link.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
defaultAction.run();
}
});
}
return link;
}
/**
* Creates a new sub-section in the specified parent composite with the
* default sub section font and color.
*
* @param parent
* The parent composite for the new sub section.
* @param title
* The section title.
*
* @return The composite within the new section, ready for the caller to
* populate with widgets.
*/
public Composite newSubSection(Composite parent, String title) {
return newSubSection(parent, title,
resources.getColor("module-subheader"),
resources.getFont("module-subheader"));
}
/**
* Creates a new sub-section in the specified parent composite with
* explicitly specified font and color.
*
* @param parent
* The parent composite for the new sub section.
* @param title
* The section title.
* @param color
* The color for the sub-section title text.
* @param font
* The font for the sub-section title text.
*
* @return The composite within the new section, ready for the caller to
* populate with widgets.
*/
public Composite newSubSection(Composite parent, String title, Color color, Font font) {
FormToolkit formToolkit = resources.getFormToolkit();
Section section = formToolkit.createSection(parent, Section.EXPANDED);
section.setText(title);
section.setFont(font);
section.setForeground(color);
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL);
tableWrapData.grabHorizontal = true;
section.setLayoutData(tableWrapData);
Composite composite = formToolkit.createComposite(section);
TableWrapLayout layout = new TableWrapLayout();
layout.leftMargin = 2;
layout.rightMargin = 2;
layout.topMargin = 0;
layout.bottomMargin = 0;
layout.verticalSpacing = 0;
composite.setLayout(layout);
section.setClient(composite);
section.setLayoutData(new TableWrapData(TableWrapData.FILL));
return composite;
}
}
| 7,614 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/OverviewResources.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.core.ui.overview;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.HyperlinkSettings;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.services.IDisposable;
import org.osgi.framework.Bundle;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Manager for resources used in the AWS Toolkit for Eclipse overview page
* (fonts, colors, form toolkit, images, etc).
* <p>
* This class is intended to be constructed only once and shared among all the
* overview page components.
* <p>
* An instance of OverviewResources must be properly disposed of with the
* {@link #dispose()} method when is isn't needed anymore so that the underlying
* resources can be released.
*/
public class OverviewResources implements IDisposable {
/** Form toolkit for creating widgets */
private final FormToolkit toolkit;
/** Map of allocated fonts by ID for the overview components */
private Map<String, Font> managedFonts = new HashMap<>();
/**
* Map of shared fonts by ID - these fonts are allocated by the system and
* will _not_ be released with the rest of the overview resources.
*/
private Map<String, Font> sharedFonts = new HashMap<>();
/** Registry of shared images for the overview components */
private final ImageRegistry imageRegistry = new ImageRegistry();
/*
* ImageRegistry keys
*/
public static final String IMAGE_GRADIENT = "gradient";
public static final String IMAGE_GRADIENT_WITH_LOGO = "logo-gradient";
public static final String IMAGE_CONFIGURE_BUTTON = "configure-button";
public static final String IMAGE_BULLET = "orange-bullet";
/**
* Constructs a new OverviewResources instance, and prepares resources for
* use.
*/
public OverviewResources() {
toolkit = new FormToolkit(Display.getCurrent());
toolkit.getHyperlinkGroup().setHyperlinkUnderlineMode(HyperlinkSettings.UNDERLINE_NEVER);
initializeColors();
initializeFonts();
initializeImages();
}
/**
* Returns the FormToolkit resource for creating UI widgets in the overview
* page components.
*
* @return The FormToolkit resource for creating UI widgets in the overview
* page components.
*/
public FormToolkit getFormToolkit() {
return toolkit;
}
/**
* Returns the font resource with the specified ID.
*
* @param key
* The ID of the font resource to return.
*
* @return The font resource with the specified ID.
*/
public Font getFont(String key) {
if (managedFonts.containsKey(key)) {
return managedFonts.get(key);
} else {
return sharedFonts.get(key);
}
}
/**
* Returns the color resource with the specified ID.
*
* @param key
* The ID of the color resource to return.
*
* @return The color resource with the specified ID.
*/
public Color getColor(String key) {
return toolkit.getColors().getColor(key);
}
/**
* Returns the image resource with the specified ID.
*
* @param key
* The ID of the image resource to return.
*
* @return The image resource with the specified ID.
*/
public Image getImage(String key) {
return imageRegistry.get(key);
}
/**
* Returns the external link image.
*
* @return The external link image.
*/
public static Image getExternalLinkImage() {
ImageRegistry imageRegistry = AwsToolkitCore.getDefault().getImageRegistry();
return imageRegistry.get(AwsToolkitCore.IMAGE_EXTERNAL_LINK);
}
/* (non-Javadoc)
* @see org.eclipse.ui.services.IDisposable#dispose()
*/
@Override
public void dispose() {
toolkit.dispose();
imageRegistry.dispose();
for (Font font : managedFonts.values()) {
font.dispose();
}
}
/*
* Private Interface
*/
/** Initializes image resources */
private void initializeImages() {
Bundle bundle = AwsToolkitCore.getDefault().getBundle();
imageRegistry.put(IMAGE_GRADIENT, ImageDescriptor.createFromURL(bundle.getEntry("icons/overview/header-gradient.png")));
imageRegistry.put(IMAGE_GRADIENT_WITH_LOGO, ImageDescriptor.createFromURL(bundle.getEntry("icons/overview/logo-header-gradient.png")));
imageRegistry.put(IMAGE_CONFIGURE_BUTTON, ImageDescriptor.createFromURL(bundle.getEntry("icons/overview/configure-button.png")));
imageRegistry.put(IMAGE_BULLET, ImageDescriptor.createFromURL(bundle.getEntry("icons/overview/bullet.png")));
}
/** Initializes color resources */
private void initializeColors() {
toolkit.getColors().createColor("amazon-orange", 222, 123, 32);
toolkit.getColors().createColor("module-header", 94, 124, 169);
toolkit.getColors().createColor("module-subheader", 102, 102, 102);
}
/** Initializes font resources */
private void initializeFonts() {
managedFonts.put("big-header", newFont(new FontData[] {
new FontData("Verdana", 16, SWT.BOLD),
new FontData("Arial", 16, SWT.BOLD),
new FontData("Helvetica", 16, SWT.BOLD),
}));
managedFonts.put("resources-header", newFont(new FontData[] {
new FontData("Verdana", 18, SWT.NORMAL),
new FontData("Arial", 18, SWT.NORMAL),
new FontData("Helvetica", 18, SWT.NORMAL),
}));
managedFonts.put("module-header", newFont(new FontData[] {
new FontData("Verdana", 12, SWT.BOLD),
new FontData("Arial", 12, SWT.BOLD),
new FontData("Helvetica", 12, SWT.BOLD),
}));
managedFonts.put("module-subheader", newFont(new FontData[] {
new FontData("Verdana", 11, SWT.BOLD),
new FontData("Arial", 11, SWT.BOLD),
new FontData("Helvetica", 11, SWT.BOLD),
}));
sharedFonts.put("text", JFaceResources.getDialogFont());
}
/**
* Creates a new Font from the specified font data.
*
* @param fontData
* The font data for creating the new font.
*
* @return The new font.
*/
private Font newFont(FontData[] fontData) {
return new Font(Display.getCurrent(), fontData);
}
}
| 7,615 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/overview/FormsOverviewComposite.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.core.ui.overview;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
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.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.AwsUrls;
import com.amazonaws.eclipse.core.diagnostic.utils.EmailMessageLauncher;
import com.amazonaws.eclipse.core.util.RssFeed;
import com.amazonaws.eclipse.core.util.RssFeed.Item;
import com.amazonaws.eclipse.core.util.RssFeedParser;
/**
* Main composite displaying the AWS Toolkit for Eclipse overview page. This is
* the top level composite, responsible for allocating shared resources through
* the OverviewResources object, sharing those resources with all subcomponents,
* and eventually disposing shared resources along with all subcomponents when
* this composite is disposed.
*/
class FormsOverviewComposite extends Composite {
/** Preferred display order for overview sections */
private static final String[] PLUGIN_ORDER = new String[] {
"com.amazonaws.eclipse.sdk.ui",
"com.amazonaws.eclipse.elasticbeanstalk",
"com.amazonaws.eclipse.ec2",
"com.amazonaws.eclipse.datatools.enablement.simpledb.ui"
};
/** The main form displayed in the overview page */
private ScrolledForm form;
/** The shared resources for all overview page components */
private OverviewResources resources;
/**
* Constructs a new AWS Toolkit for Eclipse overview composite, allocating
* all shared resources. This class is not intended to be have more than one
* instance instantiated at a time.
*
* @param parent
* The parent composite in which to create the new overview page.
*/
public FormsOverviewComposite(Composite parent) {
super(parent, SWT.NONE);
setLayout(new FillLayout());
resources = new OverviewResources();
// Create the main form
form = resources.getFormToolkit().createScrolledForm(this);
TableWrapLayout tableWrapLayout = LayoutUtils.newSlimTableWrapLayout(2);
tableWrapLayout.verticalSpacing = 10;
tableWrapLayout.horizontalSpacing = 15;
form.getBody().setLayout(tableWrapLayout);
// Header
Composite headerComposite = new HeaderComposite(form.getBody(), resources);
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL_GRAB);
tableWrapData.colspan = 2;
headerComposite.setLayoutData(tableWrapData);
// Column of contributed overview sections and additional resources
Composite leftColumn = resources.getFormToolkit().createComposite(form.getBody());
TableWrapLayout leftHandColumnLayout = new TableWrapLayout();
leftHandColumnLayout.verticalSpacing = 20;
leftColumn.setLayout(leftHandColumnLayout);
TableWrapData tableWrapData2 = new TableWrapData(TableWrapData.FILL_GRAB);
leftColumn.setLayoutData(tableWrapData2);
createContributedOverviewSections(leftColumn);
createResourcesSection(leftColumn)
.setLayoutData(new TableWrapData(TableWrapData.FILL));
// Right column widgets
Composite rightColumn = resources.getFormToolkit().createComposite(form.getBody());
TableWrapLayout rightHandColumnLayout = new TableWrapLayout();
rightHandColumnLayout.verticalSpacing = 20;
rightColumn.setLayout(rightHandColumnLayout);
createJavaBlogSection(rightColumn).setLayoutData(new TableWrapData(TableWrapData.FILL));
}
private Composite createJavaBlogSection(Composite parent) {
Toolkit overviewToolkit = new Toolkit();
overviewToolkit.setResources(resources);
Section section = resources.getFormToolkit().createSection(parent,
Section.CLIENT_INDENT | Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
section.setText("AWS Java Developer Blog");
section.setLayout(new FillLayout());
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL, TableWrapData.FILL);
tableWrapData.grabHorizontal = true;
tableWrapData.grabVertical = true;
section.setLayoutData(tableWrapData);
Composite composite = new Composite(section, SWT.NONE);
composite.setLayout(new TableWrapLayout());
section.setClient(composite);
section.setFont(resources.getFont("module-header"));
section.setForeground(resources.getColor("module-header"));
section.setTitleBarForeground(resources.getColor("module-header"));
composite.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
Toolkit.newLabel(composite, "Loading...");
new LoadJavaDeveloperBlogJob(composite, overviewToolkit).schedule();
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Composite#setFocus()
*/
@Override
public boolean setFocus() {
return form.setFocus();
}
/* (non-Javadoc)
* @see org.eclipse.swt.widgets.Widget#dispose()
*/
@Override
public void dispose() {
resources.dispose();
super.dispose();
}
/*
* Private Interface
*/
/**
* Creates the Resources section, with links to general, external resources,
* in the specified parent composite.
*
* @param parent
* The parent composite in which to create the new UI widgets.
*
* @return The new composite containing the Resources section of the
* overview page.
*/
private Composite createResourcesSection(Composite parent) {
Toolkit overviewToolkit = new Toolkit();
overviewToolkit.setResources(resources);
Section section = resources.getFormToolkit().createSection(parent,
Section.CLIENT_INDENT | Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
section.setText("Additional Resources");
section.setLayout(new FillLayout());
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL, TableWrapData.FILL);
tableWrapData.grabHorizontal = true;
tableWrapData.grabVertical = true;
section.setLayoutData(tableWrapData);
Composite composite = new Composite(section, SWT.NONE);
composite.setLayout(new TableWrapLayout());
section.setClient(composite);
section.setFont(resources.getFont("module-header"));
section.setForeground(resources.getColor("module-header"));
section.setTitleBarForeground(resources.getColor("module-header"));
composite.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
overviewToolkit.newListItem(composite,
"AWS Toolkit for Eclipse Homepage",
AwsUrls.AWS_TOOLKIT_FOR_ECLIPSE_HOMEPAGE_URL);
overviewToolkit.newListItem(composite,
"AWS Java Development Forum",
AwsUrls.JAVA_DEVELOPMENT_FORUM_URL);
overviewToolkit.newListItem(composite,
"Frequently Asked Questions",
AwsUrls.AWS_TOOLKIT_FOR_ECLIPSE_FAQ_URL);
overviewToolkit.newListItem(composite,
"AWS Toolkit for Eclipse Source Code",
AwsUrls.AWS_TOOLKIT_FOR_ECLIPSE_GITHUB_URL);
overviewToolkit.newListItem(composite,
"AWS Management Console",
AwsUrls.AWS_MANAGEMENT_CONSOLE_URL);
overviewToolkit.newListItem(composite,
"Send Feedback to " + EmailMessageLauncher.AWS_ECLIPSE_FEEDBACK_AT_AMZN,
"mailto:" + EmailMessageLauncher.AWS_ECLIPSE_FEEDBACK_AT_AMZN);
return composite;
}
/**
* Simple Job for asynchronously retreiving a blog feed and updating the UI.
*/
private final class LoadJavaDeveloperBlogJob extends Job {
private static final String JAVA_DEVELOPER_BLOG_URL = "https://aws.amazon.com/blogs/developer/category/java/";
private static final String JAVA_DEVELOPER_BLOG_RSS_URL = "https://aws.amazon.com/blogs/developer/category/java/feed/";
private Composite composite;
private Toolkit toolkit;
private LoadJavaDeveloperBlogJob(Composite composite, Toolkit toolkit) {
super("Loading AWS Java Blog Feed");
this.composite = composite;
this.toolkit = toolkit;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
RssFeedParser parser = new RssFeedParser(JAVA_DEVELOPER_BLOG_RSS_URL);
RssFeed rssFeed = parser.parse();
final List<Item> items = rssFeed == null || rssFeed.getChannel() == null || rssFeed.getChannel().getItems() == null ?
null : rssFeed.getChannel().getItems().subList(0, 10);
Display.getDefault().syncExec(new Runnable () {
@Override
public void run() {
for (Control control : composite.getChildren()) control.dispose();
if (items == null || items.isEmpty()) {
toolkit.newListItem(composite, "AWS Java Developer Blog", JAVA_DEVELOPER_BLOG_URL);
} else {
for (Item message : items) {
toolkit.newListItem(composite, message.getTitle(), message.getLink());
}
}
form.reflow(true);
}
});
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, AwsToolkitCore.getDefault().getPluginId(), "Unable to load AWS Java Developer Blog feed", e);
}
}
}
/**
* Simple data container for the information about an OverviewSection
* contributor.
*/
private class OverviewContribution {
final String title;
final OverviewSection overviewSection;
OverviewContribution(String title, OverviewSection overviewSection) {
this.title = title;
this.overviewSection = overviewSection;
}
}
/**
* Loads the overview contribution data from the plugins that contribute
* overview sections, instantiates the OverviewSection subclass, and sorts
* the returned records in the preferred display order.
*
* @return The sorted OverviewContribution objects based on what AWS Toolkit
* plugins are installed and are supplying overview section
* implementations.
*/
private List<OverviewContribution> loadOverviewContributions() {
Map<String, OverviewContribution> overviewContributionsByPluginId = new HashMap<>();
IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(AwsToolkitCore.OVERVIEW_EXTENSION_ID);
for (IExtension extension : extensionPoint.getExtensions()) {
for (IConfigurationElement configurationElement : extension.getConfigurationElements()) {
String contributorName = configurationElement.getContributor().getName();
try {
OverviewContribution overviewContribution = new OverviewContribution(
configurationElement.getAttribute("title"),
(OverviewSection)configurationElement.createExecutableExtension("class"));
overviewContributionsByPluginId.put(contributorName, overviewContribution);
} catch (CoreException e) {
AwsToolkitCore.getDefault().logError("Unable to create AWS Toolkit Overview section for: " + contributorName, e);
}
}
}
ArrayList<OverviewContribution> overviewContributions = new ArrayList<>();
for (String pluginId : PLUGIN_ORDER) {
if (overviewContributionsByPluginId.containsKey(pluginId)) {
overviewContributions.add(overviewContributionsByPluginId.remove(pluginId));
}
}
overviewContributions.addAll(overviewContributionsByPluginId.values());
return overviewContributions;
}
/**
* Creates all the contributed overview sections from all the installed AWS
* Toolkit plugins that provide OverviewSection contributions.
*
* @param parent
* The parent composite in which to create the new contributed
* overview sections.
*/
private void createContributedOverviewSections(Composite parent) {
for (OverviewContribution overviewContribution : loadOverviewContributions()) {
OverviewSection overviewSection = overviewContribution.overviewSection;
Composite composite = createContributedOverviewSection(parent, overviewContribution.title);
if (overviewSection instanceof OverviewSection.V2) {
overviewSection.setResources(resources);
composite.setLayout(newV2SectionLayout());
} else {
composite.setLayout(newV1SectionLayout());
}
try {
overviewSection.createControls(composite);
} catch (Exception e) {
AwsToolkitCore.getDefault().logError("Unable to create AWS Toolkit Overview section for " + overviewContribution.title, e);
}
}
}
/**
* Creates a new, empty overview section in the given parent composite with
* the specified name, ready for a contributed OverviewSection to fill in
* its controls in the returned composite.
*
* @param parent
* The parent composite in which to create the new section.
* @param name
* The title for the new section.
*
* @return The new, empty composite in the new section, ready for the
* contributed OverviewSection to fill in its controls.
*/
private Composite createContributedOverviewSection(Composite parent, String name) {
Section section = resources.getFormToolkit().createSection(parent,
Section.CLIENT_INDENT | Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
section.setText(name);
TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL, TableWrapData.FILL);
tableWrapData.grabHorizontal = true;
tableWrapData.grabVertical = true;
section.setLayoutData(tableWrapData);
section.setFont(resources.getFont("module-header"));
section.setForeground(resources.getColor("module-header"));
section.setTitleBarForeground(resources.getColor("module-header"));
Composite composite = resources.getFormToolkit().createComposite(section);
tableWrapData = new TableWrapData(TableWrapData.FILL, TableWrapData.FILL);
tableWrapData.grabHorizontal = true;
tableWrapData.grabVertical = true;
composite.setLayoutData(tableWrapData);
section.setClient(composite);
return composite;
}
/**
* Creates a new layout for the composite containing a V1 OverviewSection.
* V1 OverviewSections use 2 column GridLayouts, as opposed to V2
* OverviewSections which use 1 column TableWrapLayouts.
*
* @return A new GridLayout suitable for containing a V1 OverviewSection's
* controls.
*/
private GridLayout newV1SectionLayout() {
return new GridLayout(2, false);
}
/**
* Creates a new layout for the composite containing a V2 OverviewSection.
* V2 OverviewSections use 1 column TableWrapLayouts, as opposed to the
* older 2 column grid layouts required by V1 OverviewSections.
*
* @return A new TableWrapLayout suitable for containing a V2
* OverviewSection's controls.
*/
private TableWrapLayout newV2SectionLayout() {
TableWrapLayout layout = new TableWrapLayout();
layout.bottomMargin = 0;
layout.topMargin = 0;
return layout;
}
}
| 7,616 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/AbstractWidgetBuilder.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.core.ui.swt;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
/**
* An abstract widget builder, adding setters for various GridData properties
* controlling the layout of the widget.
*
* @param <T> the runtime type of this object
*/
public abstract class AbstractWidgetBuilder<T> implements WidgetBuilder {
private int style;
private Color foregroundColor;
private GridData layoutData;
public int getStyle() {
return style;
}
public T withStyle(final int value) {
style = value;
return getThis();
}
public Color getForegroundColor() {
return foregroundColor;
}
public T withForegroundColor(final Color value) {
foregroundColor = value;
return getThis();
}
public GridData getLayoutData() {
return layoutData;
}
public GridData getOrCreateLayoutData() {
if (layoutData == null) {
layoutData = new GridData();
}
return layoutData;
}
public T withLayoutData(final GridData value) {
layoutData = value;
return getThis();
}
public T withVerticalAlignment(final VerticalAlignment value) {
getOrCreateLayoutData().verticalAlignment = value.getValue();
return getThis();
}
public T withHorizontalAlignment(final HorizontalAlignment value) {
getOrCreateLayoutData().horizontalAlignment = value.getValue();
return getThis();
}
public T withWidthHint(final int value) {
getOrCreateLayoutData().widthHint = value;
return getThis();
}
public T withHeightHint(final int value) {
getOrCreateLayoutData().heightHint = value;
return getThis();
}
public T withHorizontalIndent(final int value) {
getOrCreateLayoutData().horizontalIndent = value;
return getThis();
}
public T withVerticalIndent(final int value) {
getOrCreateLayoutData().verticalIndent = value;
return getThis();
}
public T withHorizontalSpan(final int value) {
getOrCreateLayoutData().horizontalSpan = value;
return getThis();
}
public T withVerticalSpan(final int value) {
getOrCreateLayoutData().verticalSpan = value;
return getThis();
}
public T withHorizontalLandGrab(final boolean value) {
getOrCreateLayoutData().grabExcessHorizontalSpace = value;
return getThis();
}
public T withVerticalLandGrab(final boolean value) {
getOrCreateLayoutData().grabExcessVerticalSpace = value;
return getThis();
}
public T withMinimumWidth(final int value) {
getOrCreateLayoutData().minimumWidth = value;
return getThis();
}
public T withMinimumHeight(final int value) {
getOrCreateLayoutData().minimumHeight = value;
return getThis();
}
public T withFullHorizontalFill() {
withHorizontalAlignment(HorizontalAlignment.FILL);
return withHorizontalLandGrab(true);
}
@SuppressWarnings("unchecked")
protected T getThis() {
return (T) this;
}
}
| 7,617 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/CompositeBuilder.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.core.ui.swt;
import java.util.ArrayList;
import java.util.Arrays;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
/**
* A builder for Composites, which group together several widgets with some
* rules for how to lay them out relative to each other.
*/
public final class CompositeBuilder
extends AbstractWidgetBuilder<CompositeBuilder> {
private final ArrayList<WidgetBuilder> children;
private GridLayout layout;
public CompositeBuilder() {
children = new ArrayList<>();
}
public GridLayout getLayout() {
return layout;
}
public GridLayout getOrCreateLayout() {
if (layout == null) {
layout = new GridLayout();
}
return layout;
}
public CompositeBuilder withLayout(final GridLayout value) {
layout = value;
return this;
}
public CompositeBuilder withColumns(final int value) {
getOrCreateLayout().numColumns = value;
return this;
}
public CompositeBuilder withEqualWidthColumns(final boolean value) {
getOrCreateLayout().makeColumnsEqualWidth = value;
return this;
}
public CompositeBuilder withMarginWidth(final int value) {
getOrCreateLayout().marginWidth = value;
return this;
}
public CompositeBuilder withMarginHeight(final int value) {
getOrCreateLayout().marginHeight = value;
return this;
}
public CompositeBuilder withLeftMargin(final int value) {
getOrCreateLayout().marginLeft = value;
return this;
}
public CompositeBuilder withRightMargin(final int value) {
getOrCreateLayout().marginRight = value;
return this;
}
public CompositeBuilder withTopMargin(final int value) {
getOrCreateLayout().marginTop = value;
return this;
}
public CompositeBuilder withBottomMargin(final int value) {
getOrCreateLayout().marginBottom = value;
return this;
}
public CompositeBuilder withMargins(final int width, final int height) {
return withMarginWidth(width).withMarginHeight(height);
}
public CompositeBuilder withoutMargins() {
return withMargins(0, 0);
}
public CompositeBuilder withHorizontalSpacing(final int value) {
getOrCreateLayout().horizontalSpacing = value;
return this;
}
public CompositeBuilder withVerticalSpacing(final int value) {
getOrCreateLayout().verticalSpacing = value;
return this;
}
public CompositeBuilder withChild(final WidgetBuilder value) {
if (value == null) {
throw new IllegalArgumentException("value cannot be null");
}
children.add(value);
return this;
}
public CompositeBuilder withChildren(
final WidgetBuilder... values
) {
children.addAll(Arrays.asList(values));
return this;
}
@Override
public Composite build(final Composite parent) {
Composite composite = new Composite(parent, getStyle());
if (layout != null) {
composite.setLayout(layout);
}
if (getLayoutData() != null) {
composite.setLayoutData(getLayoutData());
}
for (WidgetBuilder child : children) {
child.build(composite);
}
return composite;
}
} | 7,618 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/TextBuilder.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.core.ui.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
/**
* Builder for text boxes, which contain copyable (and potentially user-
* editable) text.
*/
public class TextBuilder extends AbstractWidgetBuilder<TextBuilder> {
private PostBuildHook<Text> postBuildHook;
private boolean readOnly;
private Color backgroundColor;
public TextBuilder() {
// Default to having a border.
super.withStyle(SWT.BORDER);
}
public TextBuilder withoutEditing() {
readOnly = true;
return this;
}
public TextBuilder withBackgroundColor(final Color value) {
backgroundColor = value;
return this;
}
public TextBuilder withPostBuildHook(
final PostBuildHook<Text> value
) {
postBuildHook = value;
return this;
}
@Override
public Text build(final Composite parent) {
Text text = new Text(parent, getStyle());
if (readOnly) {
text.setEditable(true);
}
if (backgroundColor != null) {
text.setBackground(backgroundColor);
}
if (getLayoutData() != null) {
text.setLayoutData(getLayoutData());
}
if (postBuildHook != null) {
postBuildHook.run(text);
}
return text;
}
}
| 7,619 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/Colors.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.core.ui.swt;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
/**
* Handy strongly-typed constants for colors, since SWT.COLOR_* is gross.
*/
public final class Colors {
public static final Color GRAY = getColor(SWT.COLOR_GRAY);
public static final Color DARK_GRAY = getColor(SWT.COLOR_DARK_GRAY);
// TODO: Add more colors here as needed.
private Colors() {
}
/**
* Get a strongly-typed representation of the given color id.
*
* @param id a color id (from SWT.COLOR_*)
* @return the strongly typed Color representation
*/
private static Color getColor(final int id) {
return Display.getCurrent().getSystemColor(id);
}
}
| 7,620 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/LabelBuilder.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.core.ui.swt;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
/**
* Builder for labels, which are non-editable and non-copyable text.
*/
public class LabelBuilder extends AbstractWidgetBuilder<LabelBuilder> {
private final String text;
public LabelBuilder(final String text) {
if (text == null) {
throw new IllegalArgumentException("text cannot be null");
}
this.text = text;
}
public LabelBuilder(final String text, final Color foregroundColor) {
this(text);
withForegroundColor(foregroundColor);
}
@Override
public Label build(final Composite parent) {
Label label = new Label(parent, getStyle());
label.setText(text);
if (getForegroundColor() != null) {
label.setForeground(getForegroundColor());
}
if (getLayoutData() != null) {
label.setLayoutData(getLayoutData());
}
return label;
}
} | 7,621 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/WidgetUtils.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.core.ui.swt;
/**
* Utility functions for making SWT slightly more palatable.
*/
public final class WidgetUtils {
/**
* Wrap a widget in a composite that indents it a number of
* pixels to the right.
*
* @param widget the widget to indent
* @param pixels the number of pixels to indent by
* @return a builder for the enclosing composite
*/
public static CompositeBuilder indentRight(
final WidgetBuilder widget,
final int pixels
) {
return new CompositeBuilder()
.withoutMargins()
.withLeftMargin(pixels)
.withHorizontalAlignment(HorizontalAlignment.FILL)
.withChild(widget);
}
/**
* Wrap a widget in a composite that indents it a number of
* pixels downwards.
*
* @param widget the widget to indent
* @param pixels teh number of pixels to indent by
* @return a builder for the enclosing composite
*/
public static CompositeBuilder indentDown(
final WidgetBuilder element,
final int pixels
) {
return new CompositeBuilder()
.withoutMargins()
.withTopMargin(pixels)
.withVerticalAlignment(VerticalAlignment.FILL)
.withChild(element);
}
/**
* Wrap a set of widgets into a vertical column.
*
* @param widgets the widgets to wrap
* @return a builder for the enclosing composite
*/
public static CompositeBuilder column(final WidgetBuilder... widgets) {
return new CompositeBuilder()
.withoutMargins()
.withFullHorizontalFill()
.withChildren(widgets);
}
/**
* Don't use me.
*/
private WidgetUtils() {
}
}
| 7,622 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/WidgetBuilder.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.core.ui.swt;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Widget;
/**
* A builder for widgets. This lets us write generic decorator methods (eg
* "wrap these two widgets together one on top of each other") even though
* SWT enforces a top-down UI creation model where each widget needs to know
* its parent at construction time. Instead of directly taking a widget,
* such methods can take a WidgetBuilder and create the wrapped widgets
* on demand after they've created the container.
*/
public interface WidgetBuilder {
/**
* Build a widget with the given parent
*
* @param parent the parent for the widget
* @return the new widget
*/
Widget build(final Composite parent);
} | 7,623 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/HorizontalAlignment.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.core.ui.swt;
import org.eclipse.swt.SWT;
/**
* SWT.* is a mess, spliting this out into an enum for things that are
* actually legal.
*/
public enum HorizontalAlignment {
LEFT(SWT.LEFT),
CENTER(SWT.CENTER),
RIGHT(SWT.RIGHT),
FILL(SWT.FILL);
private final int value;
private HorizontalAlignment(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
} | 7,624 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/PostBuildHook.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.core.ui.swt;
/**
* A callback allowing the creator to inject custom logic in after building a
* particular widget (ie to wire up data binding).
*
* @param <T> the type of the widget being built
*/
public interface PostBuildHook<T> {
/**
* A method which is called with the newly-created widget, allowing the
* callback to customize the object.
*
* @param value the newly-created value
*/
void run(T value);
}
| 7,625 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ui/swt/VerticalAlignment.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.core.ui.swt;
import org.eclipse.swt.SWT;
/**
* SWT.* is a mess, spliting this out into an enum for things that are
* actually legal.
*/
public enum VerticalAlignment {
TOP(SWT.TOP),
CENTER(SWT.CENTER),
BOTTOM(SWT.BOTTOM),
FILL(SWT.FILL);
private final int value;
private VerticalAlignment(final int value) {
this.value = value;
}
public int getValue() {
return value;
}
} | 7,626 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences/PreferenceInitializer.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.core.preferences;
import java.io.File;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.preferences.ScopedPreferenceStore;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.util.StringUtils;
/**
* Responsible for initializing the preference store for the AWS Toolkit Core
* plugin. When initializing the default values, this class will attempt to load
* the preferences from the Amazon EC2 Eclipse plugin and import the AWS account
* settings into this plugin's preference store.
*/
public class PreferenceInitializer extends AbstractPreferenceInitializer {
/**
* The preferences that should be imported from the Amazon EC2 Eclipse
* plugin preferences (if available). These preferences were originally
* stored in the EC2 plugin preference store, but need to be moved to the
* AWS Toolkit Core preference store now that they are stored there.
*/
private final String[] preferencesToImport = new String[] {
PreferenceConstants.P_ACCESS_KEY,
PreferenceConstants.P_SECRET_KEY,
PreferenceConstants.P_USER_ID,
PreferenceConstants.P_CERTIFICATE_FILE,
PreferenceConstants.P_PRIVATE_KEY_FILE,
};
/*
* @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
*/
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = getAwsToolkitCorePreferenceStore();
/* For backwards compatibility */
importEc2AccountPreferences();
bootstrapAccountPreferences();
/* System defaults */
store.setDefault(PreferenceConstants.P_DEFAULT_REGION, "us-west-2");
store.setDefault(PreferenceConstants.P_CONNECTION_TIMEOUT, 20 * 1000);
store.setDefault(PreferenceConstants.P_SOCKET_TIMEOUT, 20 * 1000);
String defaultCredentialsFile =
System.getProperty("user.home") + File.separator
+ ".aws" + File.separator
+ "credentials";
store.setDefault(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION, defaultCredentialsFile);
/* Toolkit analytics is enabled by default */
store.setDefault(
PreferenceConstants.P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED,
true);
}
/**
* Imports the AWS account preferences from the Amazon EC2 Eclipse plugin
* and stores them in the AWS Toolkit Core's preference store. This is
* necessary for backwards compatibility, so that users who already
* installed and configured the Amazon EC2 Eclipse plugin don't lose their
* AWS account information once the AWS Toolkit Core plugin is installed.
*/
private void importEc2AccountPreferences() {
IPreferenceStore awsToolkitPreferenceStore = getAwsToolkitCorePreferenceStore();
/*
* If the EC2 plugin preferences have already been imported, we don't
* want to overwrite anything, so just bail out.
*/
if (awsToolkitPreferenceStore.getBoolean(
PreferenceConstants.P_EC2_PREFERENCES_IMPORTED)) {
return;
}
IPreferenceStore ec2PluginPreferenceStore = getEc2PluginPreferenceStore();
for (String preferenceToImport : preferencesToImport) {
String value = ec2PluginPreferenceStore.getString(preferenceToImport);
awsToolkitPreferenceStore.setValue(preferenceToImport, value);
}
/*
* Record that we imported the pre-existing EC2 plugin preferences so
* that we know not to re-import them next time.
*/
awsToolkitPreferenceStore.setValue(
PreferenceConstants.P_EC2_PREFERENCES_IMPORTED, true);
}
/**
* Bootstraps the current account preferences for new customers or customers
* migrating from the legacy single-account or global-accounts-only preference
*/
private void bootstrapAccountPreferences() {
IPreferenceStore awsToolkitPreferenceStore = getAwsToolkitCorePreferenceStore();
// Bootstrap customers from the global-accounts-only preference
String globalDefaultAccount = awsToolkitPreferenceStore
.getString(PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT);
if (StringUtils.isNullOrEmpty(globalDefaultAccount)) {
awsToolkitPreferenceStore.putValue(
PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT,
awsToolkitPreferenceStore
.getString(PreferenceConstants.P_CURRENT_ACCOUNT));
}
}
/**
* Returns the preference store for the AWS Toolkit Core plugin. Primarily
* abstracted to facilitate testing.
*
* @return The preference store for the AWS Toolkit Core plugin.
*/
protected IPreferenceStore getAwsToolkitCorePreferenceStore() {
return AwsToolkitCore.getDefault().getPreferenceStore();
}
/**
* Returns the preference store for the EC2 plugin. Primarily abstracted to
* facilitate testing.
*
* @return The preference store for the EC2 plugin.
*/
protected IPreferenceStore getEc2PluginPreferenceStore() {
return new ScopedPreferenceStore(new InstanceScope(), "com.amazonaws.eclipse.ec2");
}
}
| 7,627 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences/AbstractPreferencePropertyMonitor.java | /*
* Copyright 2010-2014 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.core.preferences;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
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.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Abstract base class for monitors for changes on a set of preference properties and
* notifying listeners.
*/
public abstract class AbstractPreferencePropertyMonitor implements IPropertyChangeListener {
private List<PreferencePropertyChangeListener> listeners = new CopyOnWriteArrayList<>();
private final long notificationDelay;
private NotifyListenersJob job = null;
/**
* Create a preference monitor with the given notification delay
*
* @param notificationDelay
* If it's a positive value, then all notifications on the
* registered listeners will be executed asynchronously after the
* specified delay. Otherwise, the notification happens
* synchronously right after change events
*/
public AbstractPreferencePropertyMonitor(long notificationDelay) {
this.notificationDelay = notificationDelay;
if (notificationDelay > 0) {
job = new NotifyListenersJob();
}
}
/**
* Override this method to determine whether changes to the given preference
* key should be watched by this monitor.
*/
protected abstract boolean watchPreferenceProperty(String preferenceKey);
public void addChangeListener(PreferencePropertyChangeListener listener) {
listeners.add(listener);
}
public void removeChangeListener(PreferencePropertyChangeListener listener) {
listeners.remove(listener);
}
@Override
public void propertyChange(PropertyChangeEvent event) {
String property = event.getProperty();
if (watchPreferenceProperty(property)) {
if (job == null) {
notifyListeners();
} else {
job.schedule(notificationDelay);
}
}
}
private void notifyListeners() {
for ( PreferencePropertyChangeListener listener : listeners ) {
try {
listener.watchedPropertyChanged();
} catch ( Exception e ) {
AwsToolkitCore.getDefault().logError(
"Couldn't notify listener of preferece property change: " + listener.getClass(), e);
}
}
}
private final class NotifyListenersJob extends Job {
private NotifyListenersJob() {
super("AWS preference property update");
this.setSystem(true);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
AbstractPreferencePropertyMonitor.this.notifyListeners();
return Status.OK_STATUS;
}
}
}
| 7,628 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences/PreferenceConstants.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.core.preferences;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.ui.preferences.ObfuscatingStringFieldEditor;
/**
* Preference constants for the AWS Toolkit Core plugin.
*/
public class PreferenceConstants {
/* Preference store key for whether to save all the files before any deployment. */
public static final String P_SAVE_FILES_AND_PROCEED = "saveFilesAndProceed";
/* Preference keys that are used as suffix for a specific accountId */
/** Preference key for a user's AWS user ID. */
public static final String P_USER_ID = "userId";
/**
* Preference key for the user-visible name for an account; just a memento.
*
* @deprecated Only legacy accounts will use this preference key. Accounts
* loaded from the credential profiles use
* P_CREDENTIAL_PROFILE_NAME instead.
*/
@Deprecated
public static final String P_ACCOUNT_NAME = "accountName";
/** Preference key for a user's AWS secret key. */
@Deprecated
public static final String P_SECRET_KEY = "secretKey";
/** Preference key for a user's AWS access key. */
@Deprecated
public static final String P_ACCESS_KEY = "accessKey";
/** Preference key for a user's EC2 private key file. */
public static final String P_PRIVATE_KEY_FILE = "privateKeyFile";
/** Preference key for a user's EC2 certificate file. */
public static final String P_CERTIFICATE_FILE = "certificateFile";
/** Preference key for the profile name of an account that is loaded from credential prfiles file. */
public static final String P_CREDENTIAL_PROFILE_NAME = "credentialProfileName";
/* "Real" preference keys */
/**
* Preference key for the ID of the default region.
*/
public static final String P_DEFAULT_REGION = "defaultRegion";
/**
* Preference key for the "|"-separated String of all the regions configured
* with a region-specific default accounts (which corresponds to all the
* region tabs to be shown in account preference page).
*/
public static final String P_REGIONS_WITH_DEFAULT_ACCOUNTS = "regionsWithDefaultAccounts";
/**
* Preference key indicating whether the preferences from the EC2 plugin
* preference store have been imported yet.
*/
public static final String P_EC2_PREFERENCES_IMPORTED = "ec2PreferencesImported";
/**
* Preference key for the set of all account ids configured as *global*
* default accounts.
*
* @deprecated Only the ids of the legacy accounts are included in this
* preference value. Profile-based accountIds are added to
* P_CREDENTIAL_PROFILE_ACCOUNT_IDS instead.
*/
@Deprecated
public static final String P_ACCOUNT_IDS = "accountIds";
/**
* Returns the preference key for the set of all account ids configured as
* default accounts for the given region.
*/
@Deprecated
public static String P_ACCOUNT_IDS(Region region) {
return region == null ?
P_ACCOUNT_IDS
:
P_ACCOUNT_IDS + "-" + region.getId();
}
/**
* Preference key for the currently selected account id. Used to fetch all
* other account details.
*/
public static final String P_CURRENT_ACCOUNT = "currentAccount";
/**
* Preference key for the current global default account id. The value of
* this preference property will be initialized by the P_CURRENT_ACCOUNT
* property value, if the user migrates from global-accounts-only
* preferences.
*/
public static final String P_GLOBAL_CURRENT_DEFAULT_ACCOUNT = "currentDefaultAccount";
/**
* Preference key for the set of ids of all the accounts loaded from
* credential profile file.
*/
public static final String P_CREDENTIAL_PROFILE_ACCOUNT_IDS = "credentialProfileAccountIds";
/**
* Preference key for the location of the credentials file, from which the
* credential profiles are loaded.
*/
public static final String P_CREDENTIAL_PROFILE_FILE_LOCATION = "credentialProfileFileLocation";
/**
* Preference key for a boolean property that controls whether the plugin
* should automatically reload accounts when the credentials profile file is
* modified.
*/
public static final String P_ALWAYS_RELOAD_WHEN_CREDNENTIAL_PROFILE_FILE_MODIFIED = "alwaysReloadWhenCredentialProfileFileModified";
public static final String P_CONNECTION_TIMEOUT = "connectionTimeout";
public static final String P_SOCKET_TIMEOUT = "socketTimeout";
/**
* Preference key for the default user email to show in the error report form.
*/
public static final String P_ERROR_REPORT_DEFAULT_USER_EMAIL = "errorReportDefaultUserEmail";
/**
* Boolean type. Default is true.
*/
public static final String P_TOOLKIT_ANALYTICS_COLLECTION_ENABLED = "toolkitAnalyticsCollectionEnabled";
/**
* Returns the preference key for the selected default account for the given
* region.
*/
public static String P_REGION_CURRENT_DEFAULT_ACCOUNT(Region region) {
return region == null ?
P_GLOBAL_CURRENT_DEFAULT_ACCOUNT
:
P_GLOBAL_CURRENT_DEFAULT_ACCOUNT + "-" + region.getId();
}
/**
* Returns the preference key for whether region-default accounts are
* enabled for the given region.
*/
public static String P_REGION_DEFAULT_ACCOUNT_ENABLED(Region region) {
return "regionalAccountEnabled-" + region.getId();
}
/* Constants used for parsing/creating preference property values */
public static final String ACCOUNT_ID_SEPARATOR = "|";
public static final String ACCOUNT_ID_SEPARATOR_REGEX = "\\|";
public static final String REGION_ID_SEPARATOR = "|";
public static final String REGION_ID_SEPARATOR_REGEX = "\\|";
/** The default name for newly created global accounts */
public static final String DEFAULT_ACCOUNT_NAME = "default";
/** Returns the default name for newly created accounts for the given region */
public static String DEFAULT_ACCOUNT_NAME(Region region) {
return region == null ?
DEFAULT_ACCOUNT_NAME
:
DEFAULT_ACCOUNT_NAME + "-" + region.getId();
}
/** The B64-encoded default name for newly created global accounts */
public static final String DEFAULT_ACCOUNT_NAME_BASE_64 = ObfuscatingStringFieldEditor
.encodeString(DEFAULT_ACCOUNT_NAME);
/** Returns the B64-encoded default name for newly created accounts for the given region */
public static String DEFAULT_ACCOUNT_NAME_BASE_64(Region region) {
return ObfuscatingStringFieldEditor
.encodeString(DEFAULT_ACCOUNT_NAME(region));
}
}
| 7,629 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences/PreferencePropertyChangeListener.java | /*
* Copyright 2010-2014 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.core.preferences;
/**
* The interface for handling change events on the preference properties
* monitored by AbstractPreferencePropertyMonitor
*/
public interface PreferencePropertyChangeListener {
/**
* This method will be called upon changes to the preference properties
* watched by the monitor to which this listener is registered.
*/
public void watchedPropertyChanged();
}
| 7,630 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/preferences/regions/DefaultRegionMonitor.java | /*
* Copyright 2010-2014 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.core.preferences.regions;
import com.amazonaws.eclipse.core.preferences.AbstractPreferencePropertyMonitor;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
/**
* Responsible for monitoring for default region changes. We could use this
* monitor to update the plugin to use the correct region-specific default
* account.
*/
public class DefaultRegionMonitor extends AbstractPreferencePropertyMonitor {
public DefaultRegionMonitor() {
super(0); // no delay
}
@Override
protected boolean watchPreferenceProperty(String preferenceKey) {
return preferenceKey.equals(PreferenceConstants.P_DEFAULT_REGION);
}
}
| 7,631 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/RegionImpl.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.core.regions;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Standard, read-only implementation of region initialized from regions.xml
* at startup.
*/
class RegionImpl implements Region {
private final String name;
private final String id;
private final String flagIconPath;
private final String restriction;
private final Map<String, String> serviceEndpoints = new HashMap<>();
private final Map<String, Service> servicesByName = new HashMap<>();
public RegionImpl(String name, String id, String flagIconPath, String restriction) {
this.name = name;
this.id = id;
this.flagIconPath = flagIconPath;
this.restriction = restriction;
}
/**
* The display name for this region. This is the value that should be shown
* in UIs when this region is used.
*
* @return The display name for this region.
*/
@Override
public String getName() {
return name;
}
/**
* The unique system ID for this region; ex: us-east-1.
*
* @return The unique system ID for this region.
*/
@Override
public String getId() {
return id;
}
/**
* Returns a map of the available services in this region and their
* endpoints. The keys of the map are service abbreviations, as defined in
* {@link ServiceAbbreviations}, and the values are the endpoint URLs.
*
* @return A map of the available services in this region.
*/
@Override
public Map<String, String> getServiceEndpoints() {
return serviceEndpoints;
}
/**
* Returns a map of the available services in this region. THe keys of the
* map are service abbreviations, as defined in {@link ServiceAbbreviations},
* and the values are {@link Service} objects that provide information on
* connecting to the service.
*
* @return A map of the available services in this region.
*/
@Override
public Map<String, Service> getServicesByName() {
return servicesByName;
}
/**
* Returns the endpoint for the service given.
*
* @see ServiceAbbreviations
*/
@Override
public String getServiceEndpoint(String serviceName) {
return serviceEndpoints.get(serviceName);
}
/**
* Returns whether the given service is supported in this region.
*
* @see ServiceAbbreviations
*/
@Override
public boolean isServiceSupported(String serviceName) {
return serviceEndpoints.containsKey(serviceName);
}
/**
* Returns the relative path to a small flag icon representing this region.
*/
@Override
public String getFlagIconPath() {
return flagIconPath;
}
/**
* Returns the image for this region's flag.
*/
@Override
public Image getFlagImage() {
Image image = AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_FLAG_PREFIX + id);
if ( image == null ) {
image = AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON);
}
return image;
}
/**
* Returns the flag's image descriptor.
*/
@Override
public ImageDescriptor getFlagImageDescriptor() {
ImageDescriptor descriptor = AwsToolkitCore.getDefault().getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_FLAG_PREFIX + id);
if ( descriptor == null ) {
descriptor = AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON);
}
return descriptor;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof RegionImpl == false) {
return false;
}
RegionImpl region = (RegionImpl)obj;
return this.getId().equals(region.getId());
}
@Override
public String toString() {
return "Region: " + name + " (" + id + ")";
}
@Override
public String getRegionRestriction() {
return restriction;
}
}
| 7,632 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/LocalRegion.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.core.regions;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* The special local "region", comprised of test services running on the
* loopback adapter.
*/
class LocalRegion implements Region {
public static final LocalRegion INSTANCE = new LocalRegion();
private final Map<String, String> serviceEndpoints =
new ConcurrentHashMap<>();
private final Map<String, Service> servicesByName =
new ConcurrentHashMap<>();
private LocalRegion() {
}
/**
* The display name for this region. This is the value that should be shown
* in UIs when this region is used.
*
* @return The display name for this region.
*/
@Override
public String getName() {
return "Local (localhost)";
}
/**
* The unique system ID for this region; ex: us-east-1.
*
* @return The unique system ID for this region.
*/
@Override
public String getId() {
return "local";
}
/**
* Returns a map of the available services in this region and their
* endpoints. The keys of the map are service abbreviations, as defined in
* {@link ServiceAbbreviations}, and the values are the endpoint URLs.
*
* @return A map of the available services in this region.
*/
@Override
public Map<String, String> getServiceEndpoints() {
return serviceEndpoints;
}
/**
* Returns a map of the available services in this region. THe keys of the
* map are service abbreviations, as defined in {@link ServiceAbbreviations},
* and the values are {@link Service} objects that provide information on
* connecting to the service.
*
* @return A map of the available services in this region.
*/
@Override
public Map<String, Service> getServicesByName() {
return servicesByName;
}
/**
* Returns the endpoint for the service given.
*
* @see ServiceAbbreviations
*/
@Override
public String getServiceEndpoint(String serviceName) {
return serviceEndpoints.get(serviceName);
}
/**
* Returns whether the given service is supported in this region.
*
* @see ServiceAbbreviations
*/
@Override
public boolean isServiceSupported(String serviceName) {
return serviceEndpoints.containsKey(serviceName);
}
/**
* Returns the relative path to a small flag icon representing this region.
*/
@Override
public String getFlagIconPath() {
return null;
}
/**
* Returns the image for this region's flag.
*/
@Override
public Image getFlagImage() {
return AwsToolkitCore.getDefault().getImageRegistry()
.get(AwsToolkitCore.IMAGE_AWS_ICON);
}
/**
* Returns the flag's image descriptor.
*/
@Override
public ImageDescriptor getFlagImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON);
}
@Override
public String toString() {
return "Region: Local (localhost) (local)";
}
@Override
public String getRegionRestriction() {
return "IsLocalAccount";
}
}
| 7,633 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/Region.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.core.regions;
import java.util.Map;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
/**
* Metadata for an AWS region, including it's name, unique ID and what services
* are available.
*/
public interface Region {
/**
* The display name for this region. This is the value that should be shown
* in UIs when this region is used.
*
* @return The display name for this region.
*/
String getName();
/**
* The unique system ID for this region; ex: us-east-1.
*
* @return The unique system ID for this region.
*/
String getId();
/**
* Returns a map of the available services in this region and their
* endpoints. The keys of the map are service abbreviations, as defined in
* {@link ServiceAbbreviations}, and the values are the endpoint URLs.
*
* @return A map of the available services in this region.
*/
Map<String, String> getServiceEndpoints();
/**
* Returns a map of the available services in this region. THe keys of the
* map are service abbreviations, as defined in {@link ServiceAbbreviations},
* and the values are {@link Service} objects that provide information on
* connecting to the service.
*
* @return A map of the available services in this region.
*/
public Map<String, Service> getServicesByName();
/**
* Returns the endpoint for the service given.
*
* @see ServiceAbbreviations
*/
String getServiceEndpoint(String serviceName);
/**
* Returns whether the given service is supported in this region.
*
* @see ServiceAbbreviations
*/
boolean isServiceSupported(String serviceName);
/**
* Returns the relative path to a small flag icon representing this region.
*/
String getFlagIconPath();
/**
* Returns the image for this region's flag.
*/
Image getFlagImage();
/**
* Returns the flag's image descriptor.
*/
ImageDescriptor getFlagImageDescriptor();
String getRegionRestriction();
default String getGlobalRegionSigningRegion() {
RegionPartition partition = RegionPartition.fromValue(getRegionRestriction());
if (partition == null) {
return getId();
} else {
return partition.getGlobalSigningRegion();
}
}
public static enum RegionPartition {
US_GOV_CLOUD("IsGovCloudAccount", "us-gov-west-1"),
CHINA_CLOUD("IsChinaAccount", "cn-north-1"),
AWS_CLOUD("IsAwsAccount", "us-east-1")
;
private final String restriction;
private final String globalSigningRegion;
private RegionPartition(String restriction, String globalSigningRegion) {
this.restriction = restriction;
this.globalSigningRegion = globalSigningRegion;
}
public String getRestriction() {
return this.restriction;
}
public String getGlobalSigningRegion() {
return globalSigningRegion;
}
/**
* Find the {@link RegionPartition} by the provided restriction. If the restriction
* is null or empty, return the default AWS_CLOUD; Otherwise, return the corresponding
* {@link RegionPartition} if found in the enum or null if not.
*/
public static RegionPartition fromValue(String restriction) {
if (restriction == null || restriction.isEmpty()) {
return AWS_CLOUD;
}
for (RegionPartition partition : RegionPartition.values()) {
if (partition.getRestriction().equals(restriction)) {
return partition;
}
}
return null;
}
}
}
| 7,634 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/RegionUtils.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.core.regions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.AwsToolkitHttpClient;
import com.amazonaws.eclipse.core.HttpClientFactory;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.regions.Regions;
/**
* Utilities for loading and working with regions. The AWS regions loading priorities are:
*
* {@link #P_REGIONS_FILE_OVERRIDE} // Use the regions file from the provided system property - used for accessing private regions
* > {@link #P_USE_LOCAL_REGION_FILE} // Use the embedded regions file /etc/regions.xml explicitly - used for testing purpose
* > {@link #LOCAL_REGION_FILE_OVERRIDE} // Use the embedded regions file /etc/override.xml if exists - used for accessing private partitions
* > {@link #CLOUDFRONT_DISTRO} // Use the remote shared ServiceEndPoints.xml file - used in most cases for accessing public regions
* > /etc/regions.xml // Use the local embedded file if failed to download the remote file - fall back to the embedded version which could be outdated
*/
public class RegionUtils {
public static final String S3_US_EAST_1_REGIONAL_ENDPOINT = "https://s3-external-1.amazonaws.com";
private static final String CLOUDFRONT_DISTRO = "http://vstoolkit.amazonwebservices.com/";
private static final String REGIONS_METADATA_S3_OBJECT = "ServiceEndPoints.xml";
// System property name whose value is the path of the overriding file.
private static final String P_REGIONS_FILE_OVERRIDE = RegionUtils.class.getName() + ".fileOverride";
// System property name whose value is a boolean whether to use the embedded region file.
private static final String P_USE_LOCAL_REGION_FILE = RegionUtils.class.getName() + ".useLocalRegionFile";
// This file overrides the remote ServiceEndPoints.xml file if exists.
private static final String LOCAL_REGION_FILE_OVERRIDE = "/etc/regions-override.xml";
private static final String LOCAL_REGION_FILE = "/etc/regions.xml";
private static List<Region> regions;
/**
* Returns true if the specified service is available in the current/active
* region, otherwise returns false.
*
* @param serviceAbbreviation
* The abbreviation of the service to check.
* @return True if the specified service is available in the current/active
* region, otherwise returns false.
* @see ServiceAbbreviations
*/
public static boolean isServiceSupportedInCurrentRegion(String serviceAbbreviation) {
return getCurrentRegion().isServiceSupported(serviceAbbreviation);
}
/**
* Returns a list of the available AWS regions.
*/
public synchronized static List<Region> getRegions() {
if (regions == null) {
init();
}
return regions;
}
/**
* Add a service endpoint to the special "local" region, causing the
* service to show up in the AWS Explorer when the region is set to local
* and setting the port that the local service is expected to listen on.
*/
public synchronized static void addLocalService(
final String serviceName,
final String serviceId,
final int port) {
Region local = getRegion("local");
if (local == null) {
throw new IllegalStateException("No local region found!");
}
Service service = new Service(serviceName,
serviceId,
"http://localhost:" + port,
null);
local.getServicesByName().put(serviceName, service);
local.getServiceEndpoints().put(serviceName, service.getEndpoint());
}
/**
* Returns a list of the regions that support the service given.
*
* @see ServiceAbbreviations
*/
public synchronized static List<Region> getRegionsForService(String serviceAbbreviation) {
List<Region> regions = new LinkedList<>();
for (Region r : getRegions()) {
if (r.isServiceSupported(serviceAbbreviation)) {
regions.add(r);
}
}
return regions;
}
/**
* Returns the region with the id given, if it exists. Otherwise, returns null.
*/
public static Region getRegion(String regionId) {
for (Region r : getRegions()) {
if (r.getId().equals(regionId)) {
return r;
}
}
return null;
}
/**
* Returns the default/active region that the user previously selected.
*/
public static Region getCurrentRegion() {
IPreferenceStore preferenceStore = AwsToolkitCore.getDefault().getPreferenceStore();
String defaultRegion = preferenceStore.getString(PreferenceConstants.P_DEFAULT_REGION);
Region rval = getRegion(defaultRegion);
if (rval == null) {
throw new RuntimeException("Unable to determine default region");
}
return rval;
}
/**
* Searches through the defined services in all regions looking for a
* service running on the specified endpoint.
*
* @param endpoint
* The endpoint of the desired service.
* @return The service running on the specified endpoint.
*
* @throws IllegalArgumentException
* if no service is found with the specified endpoint.
*/
public static Service getServiceByEndpoint(String endpoint) {
for (Region region : regions) {
for (Service service : region.getServicesByName().values()) {
if (service.getEndpoint().equals(endpoint)) {
return service;
}
}
}
throw new IllegalArgumentException("Unknown service endpoint: " + endpoint);
}
/**
* Searches through all known regions to find one with any service at the
* specified endpoint. If no region is found with a service at that
* endpoint, an exception is thrown.
*
* @param endpoint
* The endpoint for any service residing in the desired region.
* @return The region containing any service running at the specified
* endpoint, otherwise an exception is thrown if no region is found
* with a service at the specified endpoint.
*/
public static Region getRegionByEndpoint(String endpoint) {
// The S3_US_EAST_1_REGIONAL_ENDPOINT region is not configured in the regions.xml file.
if (S3_US_EAST_1_REGIONAL_ENDPOINT.equals(endpoint)) {
return RegionUtils.getRegion(Regions.US_EAST_1.getName());
}
URL targetEndpointUrl = null;
try {
targetEndpointUrl = new URL(endpoint);
} catch (MalformedURLException e) {
throw new RuntimeException(
"Unable to parse service endpoint: " + e.getMessage());
}
String targetHost = targetEndpointUrl.getHost();
for (Region region : getRegions()) {
for (String serviceEndpoint
: region.getServiceEndpoints().values()) {
try {
URL serviceEndpointUrl = new URL(serviceEndpoint);
if (serviceEndpointUrl.getHost().equals(targetHost)) {
return region;
}
} catch (MalformedURLException e) {
AwsToolkitCore.getDefault().reportException("Unable to parse service endpoint: " + serviceEndpoint, e);
}
}
}
throw new RuntimeException(
"No region found with any service for endpoint " + endpoint);
}
/**
* Fetches the most recent version of the regions file from the remote
* source and caches it to the workspace metadata directory, then
* initializes the static list of regions with it.
*/
public static synchronized void init() {
// Use overriding file for testing unlaunched services.
if (System.getProperty(P_REGIONS_FILE_OVERRIDE) != null) {
loadRegionsFromOverrideFile();
// Use the local region override file
} else if (localRegionOverrideFileExists()) {
initBundledRegionsOverride();
// Use the remote ServiceEndpoints.xml file
} else if (!Boolean.valueOf(System.getProperty(P_USE_LOCAL_REGION_FILE))) {
initRegionsFromS3();
}
// Fall back onto the version we ship with the toolkit
if (regions == null) {
initBundledRegions();
}
// If the preference store references an unknown starting region,
// go ahead and set the starting region to any existing region
IPreferenceStore preferenceStore = AwsToolkitCore.getDefault().getPreferenceStore();
Region defaultRegion = getRegion(preferenceStore.getString(PreferenceConstants.P_DEFAULT_REGION));
if (defaultRegion == null) {
preferenceStore.setValue(PreferenceConstants.P_DEFAULT_REGION, regions.get(0).getId());
}
}
private static void loadRegionsFromOverrideFile() {
try {
System.setProperty("com.amazonaws.sdk.disableCertChecking", "true");
File regionsFile =
new File(System.getProperty(P_REGIONS_FILE_OVERRIDE));
try (InputStream override = new FileInputStream(regionsFile)) {
regions = parseRegionMetadata(override);
}
try {
cacheFlags(regionsFile.getParentFile());
} catch (Exception e) {
AwsToolkitCore.getDefault().logError(
"Couldn't cache flag icons", e);
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logError(
"Couldn't load regions override", e);
}
}
private static void initRegionsFromS3() {
IPath stateLocation = Platform.getStateLocation(AwsToolkitCore
.getDefault().getBundle());
File regionsDir = new File(stateLocation.toFile(), "regions");
File regionsFile = new File(regionsDir, "regions.xml");
cacheRegionsFile(regionsFile);
initCachedRegions(regionsFile);
}
/**
* Caches the regions file stored in cloudfront to the destination file
* given. Tries S3 if cloudfront is unavailable.
*
* If the file in s3 is older than the one on disk, does nothing.
*/
private static void cacheRegionsFile(File regionsFile) {
Date regionsFileLastModified = new Date(0);
if (!regionsFile.exists()) {
regionsFile.getParentFile().mkdirs();
} else {
regionsFileLastModified = new Date(regionsFile.lastModified());
}
try {
String url = CLOUDFRONT_DISTRO + REGIONS_METADATA_S3_OBJECT;
AwsToolkitHttpClient client = HttpClientFactory.create(AwsToolkitCore.getDefault(), url);
Date remoteFileLastModified = client.getLastModifiedDate(url);
if (remoteFileLastModified == null || remoteFileLastModified.after(regionsFileLastModified)) {
fetchFile(url, regionsFile);
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logError(
"Failed to cache regions file", e);
}
}
/**
* Tries to initialize the regions list from the file given. If the file
* doesn't exist or cannot, it is deleted so that it can be fetched cleanly
* on the next startup.
*/
private static void initCachedRegions(File regionsFile) {
try (InputStream inputStream = new FileInputStream(regionsFile)) {
regions = parseRegionMetadata(inputStream);
try {
cacheFlags(regionsFile.getParentFile());
} catch (Exception e) {
AwsToolkitCore.getDefault().logError(
"Couldn't cache flag icons", e);
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logError(
"Couldn't read regions file", e);
// Clear out the regions file so that it will get cached again at
// next startup
regionsFile.delete();
}
}
/**
* Failsafe method to initialize the regions list from the list bundled with
* the plugin, in case it cannot be fetched from the remote source.
*/
private static void initBundledRegions() {
try {
regions = loadRegionsFromLocalRegionFile();
registerRegionFlagsFromBundle(regions);
} catch (IOException e) {
// Do nothing, the regions remains null in this case.
}
}
private static void initBundledRegionsOverride() {
try {
regions = loadRegionsFromLocalRegionOverrideFile();
registerRegionFlagsFromBundle(regions);
} catch (IOException e) {
// Do nothing, the regions remains null in this case.
}
}
private static final void registerRegionFlagsFromBundle(List<Region> regions) {
if (regions == null) {
return;
}
for (Region r : regions) {
if (r == LocalRegion.INSTANCE) {
// No flag to load for the local region.
continue;
}
AwsToolkitCore
.getDefault()
.getImageRegistry()
.put(AwsToolkitCore.IMAGE_FLAG_PREFIX + r.getId(),
ImageDescriptor.createFromFile(RegionUtils.class,
"/icons/" + r.getFlagIconPath()));
}
}
private static final RegionMetadataParser PARSER =
new RegionMetadataParser();
/**
* Parses a list of regions from the given input stream. Adds in the
* special "local" region.
*/
private static List<Region> parseRegionMetadata(InputStream inputStream) {
if (inputStream == null) {
return null;
}
List<Region> list = PARSER.parseRegionMetadata(inputStream);
list.add(LocalRegion.INSTANCE);
replaceS3GlobalEndpointWithRegional(list);
return list;
}
/*
* A hacky way to replace the evil S3 global endpoint with the regional one.
*/
private static void replaceS3GlobalEndpointWithRegional(List<Region> regions) {
for (Region region : regions) {
if (Regions.US_EAST_1.getName().equals(region.getId())) {
region.getServiceEndpoints().put(ServiceAbbreviations.S3, S3_US_EAST_1_REGIONAL_ENDPOINT);
}
}
}
/**
* Caches flag icons as necessary, also registering images for them
*/
private static void cacheFlags(File regionsDir)
throws ClientProtocolException, IOException {
if (!regionsDir.exists()) {
return;
}
for (Region r : regions) {
if (r == LocalRegion.INSTANCE) {
// Local region has no flag to initialize.
continue;
}
File icon = new File(regionsDir, r.getFlagIconPath());
if (icon.exists() == false) {
icon.getParentFile().mkdirs();
String iconUrl = CLOUDFRONT_DISTRO + r.getFlagIconPath();
fetchFile(iconUrl, icon);
}
AwsToolkitCore
.getDefault()
.getImageRegistry()
.put(AwsToolkitCore.IMAGE_FLAG_PREFIX + r.getId(),
ImageDescriptor.createFromURL(
icon.getAbsoluteFile().toURI().toURL()));
}
}
/**
* Fetches a file from the URL given and writes it to the destination given.
*/
private static void fetchFile(String url, File destinationFile)
throws IOException, ClientProtocolException, FileNotFoundException {
AwsToolkitHttpClient httpClient = HttpClientFactory.create(
AwsToolkitCore.getDefault(), url);
try (FileOutputStream output = new FileOutputStream(destinationFile)) {
httpClient.outputEntityContent(url, output);
}
}
/**
* Load regions from remote CloudFront URL.
*/
public static List<Region> loadRegionsFromCloudFront() throws IOException {
String url = CLOUDFRONT_DISTRO + REGIONS_METADATA_S3_OBJECT;
AwsToolkitHttpClient httpClient = HttpClientFactory.create(AwsToolkitCore.getDefault(), url);
try (InputStream inputStream =
httpClient.getEntityContent(url)) {
return parseRegionMetadata(inputStream);
}
}
/**
* Load regions from local file.
*/
private static List<Region> loadRegionsFromLocalFile(String localFileName) throws IOException {
ClassLoader classLoader = RegionUtils.class.getClassLoader();
try (InputStream inputStream =
classLoader.getResourceAsStream(localFileName)) {
return parseRegionMetadata(inputStream);
}
}
private static boolean localRegionOverrideFileExists() {
ClassLoader classLoader = RegionUtils.class.getClassLoader();
return classLoader.getResource(LOCAL_REGION_FILE_OVERRIDE) != null;
}
private static List<Region> loadRegionsFromLocalRegionOverrideFile() throws IOException {
return loadRegionsFromLocalFile(LOCAL_REGION_FILE_OVERRIDE);
}
public static List<Region> loadRegionsFromLocalRegionFile() throws IOException {
return loadRegionsFromLocalFile(LOCAL_REGION_FILE);
}
}
| 7,635 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/RegionMetadataParser.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.core.regions;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* Parses the Eclipse toolkit region metadata file to pull out information about
* the available regions, names, IDs, and what service endpoints are available
* in each region.
*/
public class RegionMetadataParser {
private static final String FLAG_ICON_TAG = "flag-icon";
private static final String REGION_DISPLAY_NAME_TAG = "displayname";
private static final String REGION_SYSTEM_ID_TAG = "systemname";
private static final String REGION_TAG = "region";
private static final String SERVICE_TAG = "service";
private static final String SERVICE_ID_ATTRIBUTE = "serviceId";
private static final String SERVICE_NAME_ATTRIBUTE = "name";
private static final String SIGNER_ATTRIBUTE = "signer";
private static final String RESTRICTIONS = "restrictions";
/**
* Parses the specified input stream and returns a list of the regions
* declared in it.
*
* @param input
* The stream containing the region metadata to parse.
*
* @return The list of parsed regions.
*/
public List<Region> parseRegionMetadata(InputStream input) {
Document document;
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
document = documentBuilder.parse(input);
} catch (Exception e) {
throw new RuntimeException("Unable to parse region metadata file: " + e.getMessage(), e);
}
NodeList regionNodes = document.getElementsByTagName(REGION_TAG);
List<Region> regions = new ArrayList<>();
for (int i = 0; i < regionNodes.getLength(); i++) {
Node node = regionNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)node;
regions.add(parseRegionElement(element));
}
}
return regions;
}
private Region parseRegionElement(Element regionElement) {
String name = getTagValue(REGION_DISPLAY_NAME_TAG, regionElement);
String id = getTagValue(REGION_SYSTEM_ID_TAG, regionElement);
String flagIcon = getTagValue(FLAG_ICON_TAG, regionElement);
String restriction = getTagValue(RESTRICTIONS, regionElement);
Region region = new RegionImpl(name, id, flagIcon, restriction);
NodeList serviceNodes = regionElement.getElementsByTagName(SERVICE_TAG);
for (int i = 0; i < serviceNodes.getLength(); i++) {
Node node = serviceNodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element)node;
String serviceName = getAttributeValue(element, SERVICE_NAME_ATTRIBUTE);
String serviceId = getAttributeValue(element, SERVICE_ID_ATTRIBUTE);
String signer = getAttributeValue(element, SIGNER_ATTRIBUTE);
String endpoint = element.getTextContent();
region.getServiceEndpoints().put(serviceName, endpoint);
region.getServicesByName().put(serviceName,
new Service(serviceName, serviceId, endpoint, signer));
}
}
return region;
}
private static String getAttributeValue(Element element, String attribute) {
if (!element.hasAttribute(attribute)) {
return null;
}
return element.getAttribute(attribute);
}
private static String getTagValue(String tagName, Element element){
Node tagNode = element.getElementsByTagName(tagName).item(0);
if ( tagNode == null ) {
return null;
}
NodeList nodes= tagNode.getChildNodes();
Node node = nodes.item(0);
return node.getNodeValue();
}
}
| 7,636 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/Service.java | /*
* Copyright 2013 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.core.regions;
/**
* Details about a service available in a region.
*/
public class Service {
/** The abbreviated name of this service - see {@link ServiceAbbreviations} */
private final String serviceName;
/** The ID of this service, as used in AWS Signature V4 request signing. */
private final String serviceId;
/** The URL at which this service can be reached. */
private final String endpoint;
private final String signerOverride;
public Service(String serviceName,
String serviceId,
String endpoint,
String signerOverride) {
this.serviceName = serviceName;
this.serviceId = serviceId;
this.endpoint = endpoint;
this.signerOverride = signerOverride;
}
public String getServiceName() {
return serviceName;
}
public String getServiceId() {
return serviceId;
}
public String getEndpoint() {
return endpoint;
}
public String getSignerOverride() {
return signerOverride;
}
} | 7,637 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/regions/ServiceAbbreviations.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.core.regions;
/**
* Common abbreviations for looking up information about a specific service, for
* example, used in {@link Region#getServiceEndpoints()}.
*/
public final class ServiceAbbreviations {
public static final String AUTOSCALING = "AutoScaling";
public static final String ELB = "ELB";
public static final String CLOUDFRONT = "CloudFront";
public static final String EC2 = "EC2";
public static final String IAM = "IAM";
public static final String S3 = "S3";
public static final String SIMPLEDB = "SimpleDB";
public static final String SNS = "SNS";
public static final String SQS = "SQS";
public static final String BEANSTALK = "ElasticBeanstalk";
public static final String RDS = "RDS";
public static final String DYNAMODB = "DynamoDB";
public static final String STS = "STS";
public static final String CLOUD_FORMATION = "CloudFormation";
public static final String CODE_DEPLOY = "CodeDeploy";
public static final String OPSWORKS = "OpsWorks";
public static final String LAMBDA = "Lambda";
public static final String CODECOMMIT = "CodeCommit";
public static final String CODESTAR = "CodeStar";
public static final String LOGS = "Logs";
public static final String KMS = "KMS";
}
| 7,638 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/RegionalizedValidator.java | /*
* Copyright 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.eclipse.core.validator;
import org.eclipse.core.databinding.validation.IValidator;
import com.amazonaws.eclipse.core.regions.Region;
/**
* Validator that asks for a Region when validating data.
*/
public abstract class RegionalizedValidator implements IValidator {
protected Region region;
// Any additional error message to be shown.
protected String errorMessage;
public void setRegion(Region region) {
this.region = region;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
| 7,639 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/ProjectNameValidator.java | /*
* Copyright 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.eclipse.core.validator;
import java.io.IOException;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.util.StringUtils;
/**
* Project name validator. It validates project name that not null or empty,
* a valid naming without unsupported characters, does not exist neither in
* the workspace nor in the underlying root folder.
*/
public class ProjectNameValidator implements IValidator {
@Override
public IStatus validate(Object value) {
String name = (String)value;
final IWorkspace workspace= ResourcesPlugin.getWorkspace();
if (StringUtils.isNullOrEmpty(name)) {
return ValidationStatus.error("The project name must be provided!");
}
String errorMessage = checkProjectNameValid(workspace, name);
if (errorMessage != null) {
return ValidationStatus.error(errorMessage);
}
errorMessage = checkProjectAlreadyExist(workspace, name);
if (errorMessage != null) {
return ValidationStatus.error(errorMessage);
}
errorMessage = checkProjectPathAlreadyExist(workspace, name);
if (errorMessage != null) {
return ValidationStatus.error(errorMessage);
}
return ValidationStatus.ok();
}
private String checkProjectNameValid(IWorkspace workspace, String projectName) {
final IStatus nameStatus= workspace.validateName(projectName, IResource.PROJECT);
if (!nameStatus.isOK()) {
return nameStatus.getMessage();
}
return null;
}
private String checkProjectAlreadyExist(IWorkspace workspace, String projectName) {
final IProject handle = workspace.getRoot().getProject(projectName);
if (handle.exists()) {
return "A project with this name already exists.";
}
return null;
}
private String checkProjectPathAlreadyExist(IWorkspace workspace, String projectName) {
IPath projectLocation= workspace.getRoot().getLocation().append(projectName);
if (projectLocation.toFile().exists()) {
try {
//correct casing
String canonicalPath= projectLocation.toFile().getCanonicalPath();
projectLocation= new Path(canonicalPath);
} catch (IOException e) {
AwsToolkitCore.getDefault().logError(e.getMessage(), e);
}
String existingName= projectLocation.lastSegment();
if (!existingName.equals(projectName)) {
return "The name of the new project must be " + existingName;
}
}
return null;
}
}
| 7,640 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/IntegerRangeValidator.java | /*
* Copyright 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.eclipse.core.validator;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
public class IntegerRangeValidator implements IValidator {
private final String propertyName;
private final int min;
private final int max;
public IntegerRangeValidator(String propertyName, int min, int max) {
this.propertyName = propertyName;
this.min = min;
this.max = max;
}
@Override
public IStatus validate(final Object value) {
if (!(value instanceof String)) {
return ValidationStatus.error(propertyName + " value must be specified!");
}
int number;
try {
number = Integer.parseInt((String) value);
} catch (NumberFormatException exception) {
return ValidationStatus.error(propertyName + " value must be an integer!");
}
if (number < min || number > max) {
return ValidationStatus.error(String.format("%s value must be between %d and %d", propertyName, min, max));
}
return ValidationStatus.ok();
}
} | 7,641 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/JavaPackageName.java | /*
* Copyright 2016 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.eclipse.core.validator;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
/**
* Java package name model.
*/
public class JavaPackageName {
private static final String DOT = ".";
private static final String DOT_REGEX = "\\.";
private static final String VALID_JAVA_PACKAGE_NAME = "([a-z][a-z_0-9]*\\.)*[a-z][a-z_0-9]*";
private final List<String> components;
private JavaPackageName(List<String> components) {
this.components = new LinkedList<>(components);
}
public JavaPackageName append(String component) {
this.components.add(component);
return this;
}
public List<String> getComponents() {
return new LinkedList<>(this.components);
}
public boolean isEmpty() {
return this.components.isEmpty();
}
public String asDotDelimitedString() {
return join(components, DOT);
}
/**
* @param path
* dot-delimited representation of the classpath
*/
public static JavaPackageName parse(String path) {
if (path.isEmpty()) {
return new JavaPackageName(new LinkedList<String>());
}
if (!path.matches(VALID_JAVA_PACKAGE_NAME)) {
throw new IllegalArgumentException("Invalid classpath string " + path);
}
String[] components = path.split(DOT_REGEX);
return new JavaPackageName(Arrays.asList(components));
}
private static String join(Collection<String> components, String conjuction) {
if (components == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean isFirst = true;
for (String component : components) {
if (isFirst) {
isFirst = false;
} else {
sb.append(conjuction);
}
sb.append(component);
}
return sb.toString();
}
}
| 7,642 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/ResourcesLoadingValidator.java | /*
* Copyright 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.eclipse.core.validator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam;
import com.amazonaws.eclipse.core.model.AwsResourceMetadata;
public class ResourcesLoadingValidator<T, P extends AbstractAwsResourceScopeParam<P>> extends RegionalizedValidator {
private final AwsResourceMetadata<T, P> dataModel;
public ResourcesLoadingValidator(AwsResourceMetadata<T, P> loadableResourceModel) {
this.dataModel = loadableResourceModel;
}
@Override
public IStatus validate(Object value) {
if (value == dataModel.getLoadingItem()) {
return ValidationStatus.error(
String.format("Loading %s", dataModel.getResourceType().toLowerCase()
+ (region == null ? "..." : " from " + region.getName())));
} else if (value == dataModel.getNotFoundItem()) {
return ValidationStatus.error(
String.format("Can't find %s", dataModel.getResourceType().toLowerCase())
+ (region == null ? "." : " in " + region.getName()));
} else if (value == dataModel.getErrorItem()) {
return ValidationStatus.error(
String.format("Failed to load %s", dataModel.getResourceType().toLowerCase())
+ (region == null ? "" : " in " + region.getName())
+ (errorMessage == null ? "." : ": " + errorMessage + "."));
}
return ValidationStatus.ok();
}
} | 7,643 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/FilePathValidator.java | /*
* Copyright 2011-2017 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.core.validator;
import java.io.File;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
/**
* File exists and valid validator.
*/
public class FilePathValidator implements IValidator {
private final String propertyName;
public FilePathValidator(String propertyName) {
this.propertyName = propertyName;
}
/* (non-Javadoc)
* @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
*/
@Override
public IStatus validate(Object value) {
String filePath = (String) value;
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
return ValidationStatus.error("Property " + propertyName + " does not contain a valid file!");
}
return ValidationStatus.ok();
}
}
| 7,644 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/NoopValidator.java | /*
* Copyright 2011-2017 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.core.validator;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
*/
public class NoopValidator implements IValidator {
/* (non-Javadoc)
* @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
*/
@Override
public IStatus validate(Object value) {
return Status.OK_STATUS;
}
}
| 7,645 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/KeyNotDuplicateValidator.java | /*
* Copyright 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.eclipse.core.validator;
import java.util.List;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.eclipse.core.model.KeyValueSetDataModel.Pair;
public class KeyNotDuplicateValidator implements IValidator {
private final List<Pair> pairSet;
private final Pair pair;
private final String dupErrorMessage;
public KeyNotDuplicateValidator(List<Pair> pairSet, Pair pair, String dupErrorMessage) {
this.pairSet = pairSet;
this.pair = pair;
this.dupErrorMessage = dupErrorMessage;
}
@Override
public IStatus validate(Object value) {
String keyValue = (String) value;
for (Pair pairInSet : pairSet) {
if (pair != pairInSet && pairInSet.getKey().equals(keyValue)) {
return ValidationStatus.error(dupErrorMessage);
}
}
return ValidationStatus.ok();
}
}
| 7,646 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/WorkspacePathValidator.java | /*
* Copyright 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.eclipse.core.validator;
import java.io.File;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.eclipse.core.util.PluginUtils;
/**
* Validator that validates the provided path is valid and the underlying file exists.
*/
public class WorkspacePathValidator implements IValidator {
private final String propertyName;
private final boolean isEmptyAllowed;
public WorkspacePathValidator(String propertyName, boolean isEmptyAllowed) {
this.propertyName = propertyName;
this.isEmptyAllowed = isEmptyAllowed;
}
/* (non-Javadoc)
* @see org.eclipse.core.databinding.validation.IValidator#validate(java.lang.Object)
*/
@Override
public IStatus validate(Object value) {
try {
String filePath = (String) value;
if (filePath == null || filePath.isEmpty()) {
if (isEmptyAllowed) {
return ValidationStatus.ok();
} else {
return ValidationStatus.error(propertyName + " value must not be empty.");
}
}
filePath = PluginUtils.variablePluginReplace(filePath);
File file = new File(filePath);
if (!file.exists() || !file.isFile()) {
return ValidationStatus.error(propertyName + " value is not a valid file!");
}
return ValidationStatus.ok();
} catch (CoreException e) {
return ValidationStatus.error(propertyName + " value is not a valid file!");
}
}
}
| 7,647 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/PackageNameValidator.java | /*
* Copyright 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.eclipse.core.validator;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import com.amazonaws.util.StringUtils;
/**
* Package name validator. It validates package name not null or empty and a valid name string.
*/
public class PackageNameValidator implements IValidator {
private final String message;
public PackageNameValidator(String message) {
this.message = message;
}
@Override
public IStatus validate(Object value) {
String s = (String)value;
if (StringUtils.isNullOrEmpty(s)) {
return ValidationStatus.error(message);
}
try {
JavaPackageName.parse(s);
return ValidationStatus.ok();
} catch (Exception e) {
return ValidationStatus.error(e.getMessage(), e);
}
}
}
| 7,648 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/package-info.java | /*
* Copyright 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.
*/
/**
* Common Validators for validating project name, package name etc.
*/
package com.amazonaws.eclipse.core.validator; | 7,649 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/validator/StringLengthValidator.java | /*
* Copyright 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.eclipse.core.validator;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
public class StringLengthValidator implements IValidator {
private final int maxLength;
private final int minLength;
private final String errorMessage;
public StringLengthValidator(int minLength, int maxLength, String errorMessage) {
this.minLength = minLength;
this.maxLength = maxLength;
this.errorMessage = errorMessage;
}
@Override
public IStatus validate(Object value) {
String data = (String) value;
if (data.length() >= minLength && data.length() <= maxLength) {
return ValidationStatus.ok();
}
return ValidationStatus.error(errorMessage);
}
}
| 7,650 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/RadioButtonComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.util.ValidationUtils.assertNotNull;
import static com.amazonaws.util.ValidationUtils.assertStringNotEmpty;
import java.util.Iterator;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
/**
* A complex Radio Button widget including DataBinding, a Label and a Selection Listener.
*/
public class RadioButtonComplex {
private Button radio;
private ISWTObservableValue swtObservableValue;
public RadioButtonComplex(
final Composite composite,
final DataBindingContext dataBindingContext,
final IObservableValue pojoObservableValue,
final String labelValue,
final boolean defaultValue,
final SelectionListener selectionListener
) {
radio = new Button(composite, SWT.RADIO);
radio.setText(labelValue);
if (selectionListener != null) radio.addSelectionListener(selectionListener);
// When one Radio button is selected, Data Binding doesn't update other Radio buttons' status,
// although other Radio buttons would be automatically deselected. Add this listener to update
// Data Binding explicitly.
radio.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
Iterator<?> iterator = dataBindingContext.getBindings().iterator();
while (iterator.hasNext()) {
Binding binding = (Binding)iterator.next();
binding.updateTargetToModel();
}
}
});
swtObservableValue = SWTObservables.observeSelection(radio);
dataBindingContext.bindValue(swtObservableValue, pojoObservableValue);
swtObservableValue.setValue(defaultValue);
}
public void setValue(boolean value) {
swtObservableValue.setValue(value);
}
public Button getRadioButton() {
return radio;
}
public static RadioButtonComplexBuilder builder() {
return new RadioButtonComplexBuilder();
}
public static class RadioButtonComplexBuilder {
private Composite composite;
private DataBindingContext dataBindingContext;
private IObservableValue pojoObservableValue;
private String labelValue;
private boolean defaultValue;
private SelectionListener selectionListener;
public RadioButtonComplex build() {
validateParameters();
return new RadioButtonComplex(
composite, dataBindingContext, pojoObservableValue,
labelValue, defaultValue, selectionListener);
}
public RadioButtonComplexBuilder composite(Composite composite) {
this.composite = composite;
return this;
}
public RadioButtonComplexBuilder dataBindingContext(DataBindingContext dataBindingContext) {
this.dataBindingContext = dataBindingContext;
return this;
}
public RadioButtonComplexBuilder pojoObservableValue(IObservableValue pojoObservableValue) {
this.pojoObservableValue = pojoObservableValue;
return this;
}
public RadioButtonComplexBuilder labelValue(String labelValue) {
this.labelValue = labelValue;
return this;
}
public RadioButtonComplexBuilder defaultValue(boolean defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public RadioButtonComplexBuilder selectionListener(SelectionListener selectionListener) {
this.selectionListener = selectionListener;
return this;
}
private void validateParameters() {
assertNotNull(composite, "Composite");
assertNotNull(dataBindingContext, "DataBindingContext");
assertNotNull(pojoObservableValue, "PojoObservableValue");
assertStringNotEmpty(labelValue, "LabelValue");
}
}
}
| 7,651 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/CheckboxComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCheckbox;
import static com.amazonaws.util.ValidationUtils.assertNotNull;
import static com.amazonaws.util.ValidationUtils.assertStringNotEmpty;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
/**
* A complex Checkbox widget including a Label and DataBinding.
*/
public class CheckboxComplex {
private final Button checkbox;
private ISWTObservableValue swtObservableValue;
private CheckboxComplex(
Composite composite,
DataBindingContext dataBindingContext,
IObservableValue pojoObservableValue,
SelectionListener selectionListener,
String labelValue,
boolean defaultValue,
int colSpan) {
checkbox = newCheckbox(composite, labelValue, colSpan);
swtObservableValue = SWTObservables.observeSelection(checkbox);
dataBindingContext.bindValue(swtObservableValue, pojoObservableValue);
if (selectionListener != null) checkbox.addSelectionListener(selectionListener);
swtObservableValue.setValue(defaultValue);
}
public Button getCheckbox() {
return checkbox;
}
public static CheckboxComplexBuilder builder() {
return new CheckboxComplexBuilder();
}
public static class CheckboxComplexBuilder {
private Composite composite;
private DataBindingContext dataBindingContext;
private IObservableValue pojoObservableValue;
private SelectionListener selectionListener;
private String labelValue;
private boolean defaultValue = false;
private int colSpan = 1;
public CheckboxComplex build() {
validateParameters();
return new CheckboxComplex(composite, dataBindingContext, pojoObservableValue,
selectionListener, labelValue, defaultValue, colSpan);
}
public CheckboxComplexBuilder composite(Composite composite) {
this.composite = composite;
return this;
}
public CheckboxComplexBuilder dataBindingContext(DataBindingContext dataBindingContext) {
this.dataBindingContext = dataBindingContext;
return this;
}
public CheckboxComplexBuilder pojoObservableValue(IObservableValue pojoObservableValue) {
this.pojoObservableValue = pojoObservableValue;
return this;
}
public CheckboxComplexBuilder selectionListener(SelectionListener selectionListener) {
this.selectionListener = selectionListener;
return this;
}
public CheckboxComplexBuilder labelValue(String labelValue) {
this.labelValue = labelValue;
return this;
}
public CheckboxComplexBuilder defaultValue(boolean defaultValue) {
this.defaultValue = defaultValue;
return this;
}
public CheckboxComplexBuilder colSpan(int colSpan) {
this.colSpan = colSpan;
return this;
}
private void validateParameters() {
assertNotNull(composite, "Composite");
assertNotNull(dataBindingContext, "DataBindingContext");
assertNotNull(pojoObservableValue, "PojoObservableValue");
assertStringNotEmpty(labelValue, "LabelValue");
}
}
}
| 7,652 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/ComboComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newCombo;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLabel;
import static com.amazonaws.util.ValidationUtils.assertNotEmpty;
import static com.amazonaws.util.ValidationUtils.assertNotNull;
import static com.amazonaws.util.ValidationUtils.assertStringNotEmpty;
import java.util.Collection;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.core.model.ComboBoxItemData;
/**
* A complex Combo widget including a Label, DataBinding. The generic type T must be a #{@link com.amazonaws.eclipse.core.model.ComboBoxItemData} whose
* getName() method returns the text shown in the combo.
*/
public class ComboComplex<T extends ComboBoxItemData> {
private Combo combo;
private ISWTObservableValue swtObservableValue;
private ComboComplex(
Composite composite,
DataBindingContext dataBindingContext,
IObservableValue pojoObservableValue,
String label,
Collection<T> items,
T defaultItem,
SelectionListener selectionListener,
int comboColSpan) {
newLabel(composite, label);
combo = newCombo(composite, comboColSpan);
for (T type : items) {
combo.add(type.getComboBoxItemLabel());
combo.setData(type.getComboBoxItemLabel(), type);
}
int defaultIndex = defaultItem == null ? 0 : combo.indexOf(defaultItem.getComboBoxItemLabel());
if (defaultIndex < 0) defaultIndex = 0; // when defaultItem is not in List.
combo.select(defaultIndex);
swtObservableValue = SWTObservables.observeText(combo);
dataBindingContext.bindValue(swtObservableValue, pojoObservableValue);
swtObservableValue.setValue(combo.getText());
if (selectionListener != null) combo.addSelectionListener(selectionListener);
}
public Combo getCombo() {
return combo;
}
public static <T extends ComboBoxItemData> ComboComplexBuilder<T> builder() {
return new ComboComplexBuilder<>();
}
public static class ComboComplexBuilder<T extends ComboBoxItemData> {
private Composite composite;
private DataBindingContext dataBindingContext;
private IObservableValue pojoObservableValue;
private String labelValue;
private Collection<T> items;
private T defaultItem;
private String defaultItemName;
private SelectionListener selectionListener;
private int comboColSpan = 1;
public ComboComplex<T> build() {
validateParameters();
if (defaultItem == null && defaultItemName != null) {
defaultItem = findItemByName(defaultItemName);
}
return new ComboComplex<>(composite, dataBindingContext, pojoObservableValue,
labelValue, items, defaultItem, selectionListener, comboColSpan);
}
public ComboComplexBuilder<T> composite(Composite composite) {
this.composite = composite;
return this;
}
public ComboComplexBuilder<T> dataBindingContext(DataBindingContext dataBindingContext) {
this.dataBindingContext = dataBindingContext;
return this;
}
public ComboComplexBuilder<T> pojoObservableValue(IObservableValue pojoObservableValue) {
this.pojoObservableValue = pojoObservableValue;
return this;
}
public ComboComplexBuilder<T> labelValue(String labelValue) {
this.labelValue = labelValue;
return this;
}
public ComboComplexBuilder<T> items(Collection<T> items) {
this.items = items;
return this;
}
public ComboComplexBuilder<T> defaultItem(T defaultItem) {
this.defaultItem = defaultItem;
this.defaultItemName = null;
return this;
}
public ComboComplexBuilder<T> defaultItemName(String defaultItemName) {
this.defaultItemName = defaultItemName;
this.defaultItem = null;
return this;
}
public ComboComplexBuilder<T> selectionListener(SelectionListener selectionListener) {
this.selectionListener = selectionListener;
return this;
}
public ComboComplexBuilder<T> comboColSpan(int comboColSpan) {
this.comboColSpan = comboColSpan;
return this;
}
private T findItemByName(String itemName) {
if (items != null) {
for (T item : items) {
if (itemName.equals(item.getComboBoxItemLabel())) {
return item;
}
}
}
return null;
}
private void validateParameters() {
assertNotNull(composite, "Composite");
assertNotNull(dataBindingContext, "DataBindingContext");
assertNotNull(pojoObservableValue, "PojoObservableValue");
assertStringNotEmpty(labelValue, "LabelValue");
assertNotEmpty(items, "ComboBox items");
}
}
}
| 7,653 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/AwsResourceComboViewerComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.util.ValidationUtils.assertNotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.model.AbstractAwsResourceScopeParam;
import com.amazonaws.eclipse.core.model.AwsResourceMetadata;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.validator.ResourcesLoadingValidator;
/**
* A Combo viewer complex for showing AWS resources.
*
* @param T - The AWS Resource type, it is also the Combo Box data type.
* @param P - The AWS Resource scope for loading the AWS resources of type T.
*/
public class AwsResourceComboViewerComplex<T, P extends AbstractAwsResourceScopeParam<P>>
extends ComboViewerComplex<T> {
private CompletableFuture<List<T>> loadResourcesJob;
private P resourceScopeParam;
private String defaultResourceName;
private Map<P, List<T>> cache = new ConcurrentHashMap<>();
private final AwsResourceMetadata<T, P> dataModel;
private final ResourcesLoadingValidator<T, P> resourceLoadingValidator;
private final AwsResourceUiRefreshable<T> refresher;
protected AwsResourceComboViewerComplex(Composite parent, ILabelProvider labelProvider, Collection<T> items,
T defaultItem, DataBindingContext bindingContext, IObservableValue pojoObservableValue,
List<IValidator> validators, String labelValue, int comboSpan, List<ISelectionChangedListener> listeners,
AwsResourceMetadata<T, P> dataModel, ResourcesLoadingValidator<T, P> resourceLoadingValidator, AwsResourceUiRefreshable<T> refresher) {
super(parent, labelProvider, items, defaultItem, bindingContext, pojoObservableValue, validators, labelValue, comboSpan, listeners);
this.dataModel = dataModel;
this.resourceLoadingValidator = resourceLoadingValidator;
this.refresher = refresher;
}
public void refreshResources(P param, String defaultResourceName) {
this.resourceScopeParam = param;
this.defaultResourceName = defaultResourceName;
resourceLoadingValidator.setRegion(RegionUtils.getRegion(param.getRegionId()));
getComboViewer().setInput(Collections.singletonList(dataModel.getLoadingItem()));
getComboViewer().setSelection(new StructuredSelection(dataModel.getLoadingItem()));
getComboViewer().getCombo().setEnabled(false);
// Cancel previous resources loading job in favor of the new one.
if (loadResourcesJob != null && !loadResourcesJob.isDone()) {
loadResourcesJob.cancel(true);
}
loadResourcesJob = CompletableFuture.supplyAsync(this::getAwsResources);
loadResourcesJob.exceptionally(ex -> {
resourceLoadingValidator.setErrorMessage(ex.getMessage());
return null;
})
.thenAccept(this::refreshUI);
}
private List<T> getAwsResources() {
return cache.computeIfAbsent(resourceScopeParam, param -> dataModel.loadAwsResources(param.copy()));
}
private void refreshUI(List<T> resources) {
Display.getDefault().syncExec(() -> {
// Error occurs
if (resources == null) {
getComboViewer().setInput(Collections.singletonList(dataModel.getErrorItem()));
getComboViewer().setSelection(new StructuredSelection(dataModel.getErrorItem()));
refresher.refreshWhenLoadingError(resources);
} else if (resources.isEmpty()) {
getComboViewer().setInput(Collections.singletonList(dataModel.getNotFoundItem()));
getComboViewer().setSelection(new StructuredSelection(dataModel.getNotFoundItem()));
refresher.refreshWhenLoadingEmpty(resources);
} else {
T defaultResource = dataModel.findResourceByName(resources, defaultResourceName);
if (defaultResource == null) {
defaultResource = resources.get(0);
}
getComboViewer().setInput(resources);
getComboViewer().setSelection(new StructuredSelection(defaultResource));
refresher.refreshWhenLoadingSuccess(resources);
}
});
}
public P getCurrentResourceScope() {
return this.resourceScopeParam;
}
public void cacheNewResource(P param, T newResource) {
cache.putIfAbsent(param, new ArrayList<>()).add(newResource);
if (this.loadResourcesJob == null || this.loadResourcesJob.isDone()) {
getComboViewer().setInput(cache.get(param));
getComboViewer().setSelection(new StructuredSelection(newResource));
} else {
loadResourcesJob.cancel(true);
getComboViewer().setInput(Arrays.asList(newResource));
getComboViewer().setSelection(new StructuredSelection(newResource));
}
}
public static final class AwsResourceComboViewerComplexBuilder<T, P extends AbstractAwsResourceScopeParam<P>>
extends ComboViewerComplexBuilderBase<T, AwsResourceComboViewerComplex<T, P>, AwsResourceComboViewerComplexBuilder<T, P>> {
private AwsResourceMetadata<T, P> resourceMetadata;
private ResourcesLoadingValidator<T, P> resourceLoadingValidator;
private AwsResourceUiRefreshable<T> resourceRefresher;
@Override
protected AwsResourceComboViewerComplex<T, P> newType() {
resourceLoadingValidator = new ResourcesLoadingValidator<>(resourceMetadata);
validators.add(resourceLoadingValidator);
return new AwsResourceComboViewerComplex<>(
parent, labelProvider, items, defaultItem,
bindingContext, pojoObservableValue, validators,
labelValue, comboSpan, listeners, resourceMetadata, resourceLoadingValidator, resourceRefresher);
}
public AwsResourceComboViewerComplexBuilder<T, P> resourceMetadata(AwsResourceMetadata<T, P> resourceMetadata) {
this.resourceMetadata = resourceMetadata;
return this;
}
public AwsResourceComboViewerComplexBuilder<T, P> resourceUiRefresher(AwsResourceUiRefreshable<T> refresher) {
this.resourceRefresher = refresher;
return this;
}
@Override
protected void validateParameters() {
super.validateParameters();
assertNotNull(resourceMetadata, "Data model");
assertNotNull(resourceRefresher, "Resources refresher");
}
}
// Refresh UI when resources are updated.
public static interface AwsResourceUiRefreshable<T> {
void refreshWhenLoadingError(List<T> resources);
void refreshWhenLoadingEmpty(List<T> resources);
void refreshWhenLoadingSuccess(List<T> resources);
}
}
| 7,654 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/ComboViewerComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newComboViewer;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLabel;
import static com.amazonaws.util.ValidationUtils.assertNotNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.jface.databinding.viewers.IViewerObservableValue;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ComboViewer;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Composite;
import com.amazonaws.eclipse.databinding.ChainValidator;
/**
* A JFace ComboView widget along with a Label and data binding feature. Instead of
* observing the value of the combo box item, it observes the attached data directly
* and binds it to the model.
*/
public class ComboViewerComplex<T> {
private final ComboViewer comboViewer;
private final IObservableValue enabler = new WritableValue();
protected ComboViewerComplex(
Composite parent,
ILabelProvider labelProvider,
Collection<T> items,
T defaultItem,
DataBindingContext bindingContext,
IObservableValue pojoObservableValue,
List<IValidator> validators,
String labelValue,
int comboSpan,
List<ISelectionChangedListener> listeners) {
if (labelValue != null) {
newLabel(parent, labelValue);
}
comboViewer = newComboViewer(parent, comboSpan);
comboViewer.setContentProvider(ArrayContentProvider.getInstance());
comboViewer.setLabelProvider(labelProvider);
comboViewer.setInput(items);
IViewerObservableValue viewerObservableValue = ViewerProperties.singleSelection().observe(comboViewer);
Binding binding = bindingContext.bindValue(viewerObservableValue, pojoObservableValue);
enabler.setValue(true);
ChainValidator<T> validatorChain = new ChainValidator<>(viewerObservableValue, enabler, validators);
bindingContext.addValidationStatusProvider(validatorChain);
if (defaultItem != null && items.contains(defaultItem)) {
comboViewer.setSelection(new StructuredSelection(defaultItem));
} else if (!items.isEmpty()) {
comboViewer.setSelection(new StructuredSelection(items.iterator().next()));
}
for (ISelectionChangedListener listener : listeners) {
comboViewer.addSelectionChangedListener(listener);
}
comboViewer.getCombo().addDisposeListener(e -> {
bindingContext.removeBinding(binding);
bindingContext.removeValidationStatusProvider(validatorChain);
viewerObservableValue.dispose();
validatorChain.dispose();
});
}
public ComboViewer getComboViewer() {
return this.comboViewer;
}
public void setEnabled(boolean enabled) {
comboViewer.getCombo().setEnabled(enabled);
enabler.setValue(enabled);
}
public void selectItem(T item) {
Collection<T> items = (Collection<T>) comboViewer.getInput();
if (item != null && items.contains(item)) {
comboViewer.setSelection(new StructuredSelection(item));
}
}
public static <T> ComboViewerComplexBuilder<T> builder() {
return new ComboViewerComplexBuilder<>();
}
public static class ComboViewerComplexBuilder<T> extends ComboViewerComplexBuilderBase<T, ComboViewerComplex<T>, ComboViewerComplexBuilder<T>>{
@Override
protected ComboViewerComplex<T> newType() {
return new ComboViewerComplex<>(
parent, labelProvider, items, defaultItem,
bindingContext, pojoObservableValue, validators,
labelValue, comboSpan, listeners);
}
}
public static abstract class ComboViewerComplexBuilderBase<T, TypeToBuild extends ComboViewerComplex<T>, TypeBuilder extends ComboViewerComplexBuilderBase<T, TypeToBuild, TypeBuilder>> {
protected Composite parent;
protected ILabelProvider labelProvider;
protected Collection<T> items = new ArrayList<>();
protected T defaultItem;
protected DataBindingContext bindingContext;
protected IObservableValue pojoObservableValue;
protected List<IValidator> validators = new ArrayList<>();
protected String labelValue;
protected int comboSpan = 1;
protected List<ISelectionChangedListener> listeners = new ArrayList<>();
protected abstract TypeToBuild newType();
public TypeToBuild build() {
validateParameters();
return newType();
}
public TypeBuilder composite(Composite parent) {
this.parent = parent;
return getBuilder();
}
public TypeBuilder labelProvider(ILabelProvider labelProvider) {
this.labelProvider = labelProvider;
return getBuilder();
}
public TypeBuilder items(Collection<T> items) {
this.items.addAll(items);
return getBuilder();
}
public TypeBuilder defaultItem(T defaultItme) {
this.defaultItem = defaultItme;
return getBuilder();
}
public TypeBuilder bindingContext(DataBindingContext bindingContext) {
this.bindingContext = bindingContext;
return getBuilder();
}
public TypeBuilder addValidators(IValidator... validators) {
this.validators.addAll(Arrays.asList(validators));
return getBuilder();
}
public TypeBuilder pojoObservableValue(IObservableValue pojoObservableValue) {
this.pojoObservableValue = pojoObservableValue;
return getBuilder();
}
public TypeBuilder labelValue(String labelValue) {
this.labelValue = labelValue;
return getBuilder();
}
public TypeBuilder comboSpan(int comboSpan) {
this.comboSpan = comboSpan;
return getBuilder();
}
public TypeBuilder addListeners(ISelectionChangedListener... listeners) {
return addListeners(Arrays.asList(listeners));
}
public TypeBuilder addListeners(List<ISelectionChangedListener> listeners) {
this.listeners.addAll(listeners);
return getBuilder();
}
@SuppressWarnings("unchecked")
private TypeBuilder getBuilder() {
return (TypeBuilder)this;
}
protected void validateParameters() {
assertNotNull(parent, "Parent composite");
assertNotNull(labelProvider, "LabelProvider");
assertNotNull(pojoObservableValue, "PojoObservableValue");
}
}
}
| 7,655 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/TextComplex.java | /*
* Copyright 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.eclipse.core.widget;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newControlDecoration;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newLabel;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newText;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.DecorationChangeListener;
/**
* A complex Text widget including a Label, DataBinding, Validator and Decoration.
*/
public class TextComplex {
private final Text text;
private final IObservableValue enabler = new WritableValue();
private TextComplex(
Composite composite,
DataBindingContext dataBindingContext,
IObservableValue pojoObservableValue,
List<IValidator> validators,
ModifyListener modifyListener,
boolean createLabel,
String labelValue,
String defaultValue,
int textColSpan,
int labelColSpan,
String textMessage) {
if (createLabel) {
Label label = newLabel(composite, labelValue, labelColSpan);
label.setToolTipText(textMessage);
}
text = newText(composite, defaultValue, textColSpan);
text.setToolTipText(textMessage);
text.setMessage(textMessage);
ControlDecoration controlDecoration = newControlDecoration(text, "");
ISWTObservableValue swtObservableValue = WidgetProperties.text(SWT.Modify).observe(text);
Binding binding = dataBindingContext.bindValue(swtObservableValue, pojoObservableValue);
enabler.setValue(true);
ChainValidator<String> validatorChain = new ChainValidator<>(swtObservableValue, enabler, validators);
dataBindingContext.addValidationStatusProvider(validatorChain);
new DecorationChangeListener(controlDecoration, validatorChain.getValidationStatus());
swtObservableValue.setValue(defaultValue);
text.addDisposeListener(e -> {
dataBindingContext.removeBinding(binding);
dataBindingContext.removeValidationStatusProvider(validatorChain);
validatorChain.dispose();
controlDecoration.dispose();
swtObservableValue.dispose();
});
if (modifyListener != null) {
text.addModifyListener(modifyListener);
}
}
// Whether enable widget or not.
public void setEnabled(boolean enabled) {
text.setEnabled(enabled);
enabler.setValue(enabled);
}
public void setText(String textValue) {
text.setText(textValue);
}
public Text getText() {
return text;
}
@NonNull
public static TextComplexBuilder builder(
@NonNull Composite parent,
@NonNull DataBindingContext dataBindingContext,
@NonNull IObservableValue pojoObservableValue) {
return new TextComplexBuilder(parent, dataBindingContext, pojoObservableValue);
}
public static class TextComplexBuilder {
private final Composite composite;
private final DataBindingContext dataBindingContext;
private final IObservableValue pojoObservableValue;
private final List<IValidator> validators = new ArrayList<>();
private String labelValue = "Label: ";
private String textMessage = "";
private ModifyListener modifyListener;
private boolean createLabel = true;
private String defaultValue = "";
private int textColSpan = 1;
private int labelColSpan = 1;
private TextComplexBuilder(
@NonNull Composite parent,
@NonNull DataBindingContext dataBindingContext,
@NonNull IObservableValue pojoObservableValue) {
this.composite = parent;
this.dataBindingContext = dataBindingContext;
this.pojoObservableValue = pojoObservableValue;
}
public TextComplex build() {
return new TextComplex(
composite, dataBindingContext, pojoObservableValue, validators, modifyListener,
createLabel, labelValue, defaultValue, textColSpan, labelColSpan, textMessage);
}
public TextComplexBuilder addValidator(IValidator validator) {
this.validators.add(validator);
return this;
}
public TextComplexBuilder addValidators(List<IValidator> validators) {
this.validators.addAll(validators);
return this;
}
public TextComplexBuilder modifyListener(ModifyListener modifyListener) {
this.modifyListener = modifyListener;
return this;
}
public TextComplexBuilder createLabel(boolean createLabel) {
this.createLabel = createLabel;
return this;
}
public TextComplexBuilder labelValue(String labelValue) {
this.labelValue = labelValue;
return this;
}
public TextComplexBuilder defaultValue(String defaultValue) {
this.defaultValue = Optional.<String>ofNullable(defaultValue).orElse("");
return this;
}
public TextComplexBuilder textColSpan(int textColSpan) {
this.textColSpan = textColSpan;
return this;
}
public TextComplexBuilder labelColSpan(int labelColSpan) {
this.labelColSpan = labelColSpan;
return this;
}
public TextComplexBuilder textMessage(String textMessage) {
this.textMessage = textMessage;
return this;
}
}
}
| 7,656 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/widget/package-info.java | /*
* Copyright 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.
*/
/**
* Collection of reusable widgets.
*/
package com.amazonaws.eclipse.core.widget; | 7,657 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/RemoteDebugLauncher.java | /*
* Copyright 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.eclipse.core.util;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
/**
* Launch a remote debugger.
*
* @see org.eclipse.m2e.internal.launch.MavenConsoleLineTracker
*/
public class RemoteDebugLauncher extends AbstractApplicationLauncher {
private final IProject project;
private final int portNo;
public RemoteDebugLauncher(IProject project, int port, IProgressMonitor monitor) {
super(ILaunchManager.DEBUG_MODE, monitor);
this.project = project;
this.portNo = port;
}
@Override
protected ILaunchConfiguration createLaunchConfiguration() throws CoreException {
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager
.getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_REMOTE_JAVA_APPLICATION);
ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null,
"Connecting debugger to port " + portNo);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_ALLOW_TERMINATE, true);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_CONNECTOR,
IJavaLaunchConfigurationConstants.ID_SOCKET_ATTACH_VM_CONNECTOR);
Map<String, String> connectMap = new HashMap<String, String>();
connectMap.put("port", String.valueOf(portNo));
connectMap.put("hostname", "localhost");
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP, connectMap);
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getName());
return workingCopy;
}
@Override
protected void validateParameters() {
if (project == null) {
throw new IllegalArgumentException("The project must be specified!");
}
}
}
| 7,658 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/RssFeedParser.java | /*
* Copyright 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.eclipse.core.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* RSS feed parser using jackson-dataformat-xml.
*/
public class RssFeedParser {
private final URL url;
public RssFeedParser(String feedUrl) {
try {
this.url = new URL(feedUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public RssFeed parse() throws IOException {
InputStream inputStream = url.openStream();
ObjectMapper mapper = new XmlMapper();
// Ignoring unknown properties in case of potential breaking.
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper.readValue(inputStream, RssFeed.class);
}
}
| 7,659 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/RssFeed.java | /*
* Copyright 2017 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.core.util;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
/**
* Simplified RSS feed POJO with only interested elements modeled.
* See <a href="https://aws.amazon.com/blogs/developer/category/java/feed/">AWS Java Blog RSS Feed</a>
* for sample RSS feed document.
*/
public class RssFeed {
private Channel channel;
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public static class Channel {
@JacksonXmlElementWrapper(useWrapping=false)
@JacksonXmlProperty(localName = "item")
private List<Item> items = new ArrayList<>();
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
public static class Item {
String title;
String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
}
| 7,660 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/PluginUtils.java | /*
* Copyright 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.eclipse.core.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
/**
* Utilities for invoking other plugin features.
*/
public class PluginUtils {
/**
* Get or create a new MessageConsole given the console name.
*/
public static MessageConsole getOrCreateMessageConsole(String consoleName) {
IConsoleManager consoleManager = ConsolePlugin.getDefault().getConsoleManager();
// Search existing consoles
IConsole[] consoles = consoleManager.getConsoles();
if (consoles != null) {
for (IConsole console : consoles) {
if (consoleName.equals(console.getName())
&& (console instanceof MessageConsole)) {
return (MessageConsole)console;
}
}
}
// If not found, create a new console
MessageConsole newConsole = new MessageConsole(consoleName, null);
ConsolePlugin.getDefault().getConsoleManager()
.addConsoles(new IConsole[] { newConsole });
return newConsole;
}
/**
* Replace the placeholder variables in the original string with the real ones.
* E.g. ${workspace_loc:/Project/file.txt} will be replaced to the real workspace location.
*
* @throws CoreException - If unable to resolve the value of one or more variables
*/
public static String variablePluginReplace(String originalValue) throws CoreException {
if (originalValue == null || originalValue.isEmpty()) {
return originalValue;
}
return VariablesPlugin.getDefault().getStringVariableManager().performStringSubstitution(originalValue);
}
private static final String WORKSPACE_LOC = "workspace_loc";
/**
* Generate a String with workspace location variable, and the relative path argument.
*/
public static String variablePluginGenerateWorkspacePath(String argument) {
return VariablesPlugin.getDefault().getStringVariableManager().generateVariableExpression(WORKSPACE_LOC, argument);
}
public static String variablePluginGenerateWorkspacePath(IPath relativePath) {
return variablePluginGenerateWorkspacePath(relativePath.toString());
}
}
| 7,661 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/KmsClientUtils.java | /*
* Copyright 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.eclipse.core.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.model.AliasListEntry;
import com.amazonaws.services.kms.model.KeyListEntry;
import com.amazonaws.services.kms.model.ListAliasesRequest;
import com.amazonaws.services.kms.model.ListAliasesResult;
import com.amazonaws.services.kms.model.ListKeysRequest;
import com.amazonaws.services.kms.model.ListKeysResult;
/**
* Utility class for using AWS KMS client.
*/
public class KmsClientUtils {
public static List<KeyListEntry> listKeys(AWSKMS kmsClient) {
ListKeysRequest request = new ListKeysRequest();
ListKeysResult result;
List<KeyListEntry> keys = new ArrayList<>();
do {
result = kmsClient.listKeys(request);
keys.addAll(result.getKeys());
request.setMarker(result.getNextMarker());
} while (result.getNextMarker() != null);
return keys;
}
/**
* Return a map of KMS key id to its alias. Notice, those don't have an alias are not
* included in this map.
*/
public static Map<String, AliasListEntry> listAliases(AWSKMS kmsClient) {
ListAliasesRequest request = new ListAliasesRequest();
ListAliasesResult result;
Map<String, AliasListEntry> aliases = new HashMap<>();
do {
result = kmsClient.listAliases(request);
result.getAliases().stream()
.filter(alias -> alias.getTargetKeyId() != null)
.forEach(alias -> aliases.put(alias.getTargetKeyId(), alias));
request.setMarker(result.getNextMarker());
} while (result.getNextMarker() != null);
return aliases;
}
}
| 7,662 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/ValidationUtils.java | /*
* Copyright 2015 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.core.util;
/**
* Static validation utility methods
*/
public class ValidationUtils {
/**
* Validates that the given object is non-null
*
* @param object
* Object to validate
* @param fieldName
* Field name to display in exception message if object is null
* @return The object if valid
* @throws IllegalArgumentException
* If object is null
*/
public static <T> T validateNonNull(T object, String fieldName) throws IllegalArgumentException {
if (object == null) {
throw new IllegalArgumentException(fieldName + " cannot be null");
}
return object;
}
}
| 7,663 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/S3BucketUtil.java | /*
* Copyright 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.eclipse.core.util;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.Bucket;
public class S3BucketUtil {
public static List<Bucket> listBucketsInRegion(AmazonS3 s3, Region region) {
List<Bucket> bucketsInAllRegions = s3.listBuckets();
return findBucketsInRegion(s3, bucketsInAllRegions, region, 10);
}
private static List<Bucket> findBucketsInRegion(final AmazonS3 s3, List<Bucket> buckets,
final Region region, int threads) {
ExecutorService es = Executors.newFixedThreadPool(threads);
final CopyOnWriteArrayList<Bucket> result = new CopyOnWriteArrayList<>();
final CountDownLatch latch = new CountDownLatch(buckets.size());
for (final Bucket bucket : buckets) {
es.submit(new Runnable() {
@Override
public void run() {
try {
if (isBucketInRegion(s3, bucket, region)) {
result.add(bucket);
}
} catch (Exception e) {
AwsToolkitCore.getDefault().logInfo("Exception thrown when checking bucket " + bucket.getName() +
" with message: " + e.getMessage());
} finally {
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return result;
}
public static String createS3Path(String bucketName, String keyName) {
return String.format("s3://%s/%s", bucketName, keyName);
}
private static boolean isBucketInRegion(AmazonS3 s3, Bucket bucket,
Region eclipseRegion) {
String s3RegionId = s3.getBucketLocation(bucket.getName());
if (s3RegionId == null || s3RegionId.equals("US")) {
s3RegionId = "us-east-1";
}
return eclipseRegion.getId().equals(s3RegionId);
}
} | 7,664 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/MavenBuildLauncher.java | /*
* Copyright 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.eclipse.core.util;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.debug.ui.RefreshTab;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.m2e.actions.MavenLaunchConstants;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.project.IMavenProjectRegistry;
import org.eclipse.m2e.core.project.ResolverConfiguration;
/**
* Utility class for launching a customized Maven build.
*
* @see org.eclipse.m2e.actions.ExecutePomAction
*/
public class MavenBuildLauncher extends AbstractApplicationLauncher {
private static final String POM_FILE_NAME = "pom.xml";
private static final String executePomActionExecutingMessage(String goals, String projectLocation) {
return String.format("Executing %s in %s", goals, projectLocation);
}
private final IProject project;
private final String goals;
public MavenBuildLauncher(IProject project, String goals, IProgressMonitor monitor) {
super(ILaunchManager.RUN_MODE, monitor);
this.project = project;
this.goals = goals;
}
@Override
protected ILaunchConfiguration createLaunchConfiguration() throws CoreException {
ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType launchConfigurationType = launchManager
.getLaunchConfigurationType(MavenLaunchConstants.LAUNCH_CONFIGURATION_TYPE_ID);
String rawConfigName = executePomActionExecutingMessage(goals, project.getLocation().toString());
String safeConfigName = launchManager.generateLaunchConfigurationName(rawConfigName);
ILaunchConfigurationWorkingCopy workingCopy = launchConfigurationType.newInstance(null, safeConfigName);
workingCopy.setAttribute(MavenLaunchConstants.ATTR_POM_DIR, project.getLocation().toOSString());
workingCopy.setAttribute(MavenLaunchConstants.ATTR_GOALS, goals);
workingCopy.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
workingCopy.setAttribute(RefreshTab.ATTR_REFRESH_SCOPE, "${project}");
workingCopy.setAttribute(RefreshTab.ATTR_REFRESH_RECURSIVE, true);
setProjectConfiguration(workingCopy, project);
IPath path = getJREContainerPath(project);
if (path != null) {
workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_JRE_CONTAINER_PATH,
path.toPortableString());
}
return workingCopy;
}
private void setProjectConfiguration(ILaunchConfigurationWorkingCopy workingCopy, IContainer basedir) {
IMavenProjectRegistry projectManager = MavenPlugin.getMavenProjectRegistry();
IFile pomFile = basedir.getFile(new Path(POM_FILE_NAME));
IMavenProjectFacade projectFacade = projectManager.create(pomFile, false, new NullProgressMonitor());
if (projectFacade != null) {
ResolverConfiguration configuration = projectFacade.getResolverConfiguration();
String selectedProfiles = configuration.getSelectedProfiles();
if (selectedProfiles != null && selectedProfiles.length() > 0) {
workingCopy.setAttribute(MavenLaunchConstants.ATTR_PROFILES, selectedProfiles);
}
}
}
private IPath getJREContainerPath(IContainer basedir) throws CoreException {
IProject project = basedir.getProject();
if (project != null && project.hasNature(JavaCore.NATURE_ID)) {
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] entries = javaProject.getRawClasspath();
for (int i = 0; i < entries.length; i++) {
IClasspathEntry entry = entries[i];
if (JavaRuntime.JRE_CONTAINER.equals(entry.getPath().segment(0))) {
return entry.getPath();
}
}
}
return null;
}
/**
* Validate all the provided parameters to perform a launch.
*
* @throws IllegalArgumentException if any parameter is not legal.
*/
@Override
protected void validateParameters() {
if (project == null) {
throw new IllegalArgumentException("The provided project cannot be null!");
}
if (project.findMember(POM_FILE_NAME) == null) {
throw new IllegalArgumentException("The project must be a Maven project with a " + POM_FILE_NAME + " file in the root!");
}
if (goals == null || goals.isEmpty()) {
throw new IllegalArgumentException("The goals specified must not be empty!");
}
}
}
| 7,665 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/FileUtils.java | /*
* Copyright 2018 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.eclipse.core.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;
public class FileUtils {
/**
* Create a new file with permission to POSIX permission 600 or equivalent, i.e owner-only readable and writable.
*
* @param fileLocation The file location
* @return The newly created File with the permission.
* @throws IOException When fails to set POSIX permission.
* @throws FileAlreadyExistsException When the file already exists.
*/
public static File createFileWithPermission600(String fileLocation) throws IOException, FileAlreadyExistsException {
Path filePath = Paths.get(fileLocation);
if (Files.exists(filePath)) {
throw new FileAlreadyExistsException(filePath.toString());
}
Files.createFile(filePath);
if (OsPlatformUtils.isWindows()) {
File file = filePath.toFile();
file.setReadable(true, true);
file.setWritable(true, true);
} else if (OsPlatformUtils.isLinux() || OsPlatformUtils.isMac()) {
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(filePath, perms);
}
return filePath.toFile();
}
}
| 7,666 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/OsPlatformUtils.java | /*
* Copyright 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.eclipse.core.util;
import org.eclipse.core.runtime.Platform;
public class OsPlatformUtils {
public static boolean isWindows() {
return Platform.getOS().equals(Platform.OS_WIN32);
}
public static boolean isMac() {
return Platform.getOS().equals(Platform.OS_MACOSX);
}
public static boolean isLinux() {
return Platform.getOS().equals(Platform.OS_LINUX);
}
public static String currentUser() {
return System.getProperty("user.name");
}
} | 7,667 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/JavaProjectUtils.java | /*
* Copyright 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.eclipse.core.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Utility class for managing Java project.
*/
public class JavaProjectUtils {
/**
* Replace the JRE version for the specified Java project to the default one and set the
* compliance level to the default JRE version
*
* @param javaProject - The specified Java project
* @param monitor - The progress monitor
*
* @throws JavaModelException
*/
public static void setDefaultJreToProjectClasspath(IJavaProject javaProject, IProgressMonitor monitor)
throws JavaModelException {
List<IClasspathEntry> classpathEntry = new ArrayList<>();
for (IClasspathEntry entry : javaProject.getRawClasspath()) {
if (!entry.getPath().toString().startsWith(JavaRuntime.JRE_CONTAINER)) {
classpathEntry.add(entry);
}
}
classpathEntry.addAll(Arrays.asList(PreferenceConstants.getDefaultJRELibrary()));
javaProject.setRawClasspath(
classpathEntry.toArray(new IClasspathEntry[classpathEntry.size()]), monitor);
Map<String, String> options = JavaCore.getOptions();
javaProject.setOption(JavaCore.COMPILER_SOURCE, options.get(JavaCore.COMPILER_SOURCE));
javaProject.setOption(JavaCore.COMPILER_COMPLIANCE, options.get(JavaCore.COMPILER_COMPLIANCE));
javaProject.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, options.get(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM));
}
}
| 7,668 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/CliUtil.java | /*
* Copyright 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.eclipse.core.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
/**
* Utility for calling a CLI command, and managing the input/output of the process.
*/
public class CliUtil {
public static CliProcessTracker executeCommand(List<String> commandLine, Map<String, String> envp, OutputStream stdOut, OutputStream stdErr)
throws IOException {
Process process = buildProcess(commandLine, envp);
PipeThread stdInputOutput = new PipeThread("CLI stdout", process.getInputStream(), stdOut);
PipeThread stdErrThread = new PipeThread("CLI stderr", process.getErrorStream(), stdErr);
stdInputOutput.start();
stdErrThread.start();
return new CliProcessTracker(process, stdInputOutput, stdErrThread);
}
/**
* Using {@link ProcessBuilder} to build a {@link Process}. {@link ProcessBuilder} aggregates a copy of the current process environment
* so that we don't have to manually copy these.
*
* @see {@link ProcessBuilder#environment()}
*/
public static Process buildProcess(List<String> commandLine, Map<String, String> envp) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
processBuilder.environment().putAll(envp);
return processBuilder.start();
}
/**
* Tracks the process along with its two stream threads.
*/
public static class CliProcessTracker {
private final Process process;
private final PipeThread stdOutThread;
private final PipeThread stdErrThread;
public CliProcessTracker(Process process, PipeThread stdOutThread, PipeThread stdErrThread) {
this.process = process;
this.stdOutThread = stdOutThread;
this.stdErrThread = stdErrThread;
}
public Process getProcess() {
return process;
}
/**
* Destroy the process and wait for the Stream threads to finish.
*/
public void destroy() {
process.destroy();
waitForStream();
}
/**
* Wait for the Stream threads to finish. Ie. to drain the input streams, and return the exit code.
*/
public int waitForStream() {
try {
stdOutThread.join();
stdErrThread.join();
} catch (InterruptedException e) {
}
return process.exitValue();
}
}
/**
* A thread that keeps reading from a target InputStream, and writes to an OutputStream.
*/
private static class PipeThread extends Thread {
private final InputStream inputStream;
private final OutputStream outputStream;
private PipeThread(String name, InputStream inputStream, OutputStream outputStream) {
this.inputStream = inputStream;
this.outputStream = outputStream;
this.setName(name);
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String line = null;
while ((line = reader.readLine()) != null) {
outputStream.write(String.format("%s%n", line).getBytes(StandardCharsets.UTF_8));
}
} catch (IOException e) {}
}
}
}
| 7,669 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/WorkbenchUtils.java | /*
* Copyright 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.eclipse.core.util;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.dialogs.MessageDialogWithToggle;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
/**
* The IWorkbench.getActiveWorkbenchWindow must be invoked in the UI thread. Otherwise, null will be returned.
*/
public class WorkbenchUtils {
public static void selectAndReveal(final IResource resource, final IWorkbench workbench) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (resource == null || workbench == null) return;
BasicNewResourceWizard.selectAndReveal(resource, workbench.getActiveWorkbenchWindow());
}
});
}
public static void openFileInEditor(final IFile file, final IWorkbench workbench) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
if (file == null || workbench == null) return;
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
if (window != null) {
IWorkbenchPage page = window.getActivePage();
try {
IDE.openEditor(page, file, true);
} catch (PartInitException e) {
AwsToolkitCore.getDefault().logWarning(String.format(
"Failed to open file %s in the editor!", file.toString()), e);
}
}
}
});
}
public static void openInternalBrowserAsEditor(final URL url, final IWorkbench workbench) {
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
if (url == null || workbench == null) return;
IWorkbenchBrowserSupport browserSupport = workbench.getBrowserSupport();
browserSupport.createBrowser(
IWorkbenchBrowserSupport.AS_EDITOR
| IWorkbenchBrowserSupport.LOCATION_BAR
| IWorkbenchBrowserSupport.NAVIGATION_BAR, null, null, null)
.openURL(url);
} catch (PartInitException e) {
AwsToolkitCore.getDefault().logWarning(String.format("Failed to open the url %s in the editor!", url.toString()), e);
}
}
});
}
/**
* Return true if no dirty files or all the dirty files are saved through the pop-up dialog, false otherwise.
*/
public static boolean openSaveFilesDialog(IWorkbench workbench) {
IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
List<IEditorPart> dirtyEditors = new ArrayList<>();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorPart[] editors = page.getDirtyEditors();
dirtyEditors.addAll(Arrays.asList(editors));
}
}
if (!dirtyEditors.isEmpty()) {
boolean saveFilesAndProceed = MessageDialogWithToggle.ALWAYS.equals(
AwsToolkitCore.getDefault().getPreferenceStore().getString(PreferenceConstants.P_SAVE_FILES_AND_PROCEED));
if (!saveFilesAndProceed) {
MessageDialogWithToggle dialog = MessageDialogWithToggle.openOkCancelConfirm(
Display.getCurrent().getActiveShell(),
"Save files?",
"Save all unsaved files and proceed?",
"Always save files and proceed",
false,
AwsToolkitCore.getDefault().getPreferenceStore(),
PreferenceConstants.P_SAVE_FILES_AND_PROCEED);
saveFilesAndProceed = Window.OK == dialog.getReturnCode();
}
if (saveFilesAndProceed) {
for (IEditorPart part : dirtyEditors) {
part.doSave(null);
}
}
return saveFilesAndProceed;
}
return true;
}
}
| 7,670 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/BundleUtils.java | /*
* Copyright 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.eclipse.core.util;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.osgi.framework.Bundle;
/**
* Utilities for Bundle management.
*/
public class BundleUtils {
/**
* Return the actual file location in the bundle. The bundle could be a regular folder, or a jar file.
*/
public static File getFileFromBundle(Bundle bundle, String... path) throws IOException, URISyntaxException {
URL rootUrl = FileLocator.toFileURL(bundle.getEntry("/"));
URI resolvedUrl = new URI(rootUrl.getProtocol(), rootUrl.getPath(), null);
File file = new File(resolvedUrl);
for (String segment : path) {
file = new File(file, segment);
}
return file;
}
}
| 7,671 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/util/AbstractApplicationLauncher.java | /*
* Copyright 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.eclipse.core.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.ui.DebugUITools;
/**
* Super class for launching an application.
*
* @see MavenBuildLauncher
* @see RemoteDebugLauncher
*/
public abstract class AbstractApplicationLauncher {
protected long timeIntervalMilli = 5000L;
protected final String mode;
protected final IProgressMonitor monitor;
protected AbstractApplicationLauncher(String mode, IProgressMonitor monitor) {
this.mode = mode;
this.monitor = monitor;
}
/**
* Validate the required parameters for launching this application.
* @throws IllegalArgumentException - If the required parameters are not provided or invalid.
*/
protected abstract void validateParameters() throws IllegalArgumentException;
/**
* Create a new {@link ILaunchConfiguration} for this application.
*/
protected abstract ILaunchConfiguration createLaunchConfiguration() throws CoreException;
public final ILaunch launchAsync() throws CoreException {
validateParameters();
ILaunchConfiguration launchConfiguration = createLaunchConfiguration();
return DebugUITools.buildAndLaunch(launchConfiguration, mode, monitor);
}
/**
* Blocking call for launching the application. This call blocks until the application terminates.
*/
public final ILaunch launch() throws CoreException {
ILaunch launch = launchAsync();
while (!launch.isTerminated()) {
try {
Thread.sleep(timeIntervalMilli);
} catch (InterruptedException e) {
}
}
return launch;
}
} | 7,672 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/maven/MavenArtifactVersionComparator.java | /*
* Copyright 2016 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.eclipse.core.maven;
import java.util.Comparator;
public class MavenArtifactVersionComparator implements Comparator<String> {
@Override
public int compare(String left, String right) {
int[] leftVersion = parseVersion(left);
int[] rightVersion = parseVersion(right);
int min = Math.min(leftVersion.length, rightVersion.length);
for (int i = 0; i < min; i++) {
if (leftVersion[i] < rightVersion[i]) return 1;
if (leftVersion[i] > rightVersion[i]) return -1;
}
return 0;
}
private int[] parseVersion(String version) {
if (version == null) return new int[0];
String[] components = version.split("\\.");
int[] ints = new int[components.length];
int counter = 0;
for (String component : components) {
int versionNumber = Integer.MIN_VALUE;
try {
versionNumber = Integer.parseInt(component);
} catch (NumberFormatException e) {
// In case the version is not a number, we use the minimum integer to lower the priority.
}
ints[counter++] = versionNumber;
}
return ints;
}
}
| 7,673 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/maven/MavenUtils.java | /*
* Copyright 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.eclipse.core.maven;
import org.eclipse.core.resources.IFile;
import org.eclipse.m2e.core.internal.IMavenConstants;
@SuppressWarnings("restriction")
public class MavenUtils {
// Returns whether the specified file is a Maven POM file.
public static boolean isFilePom(IFile file) {
return file != null && file.getFullPath().toFile().getAbsolutePath().endsWith(IMavenConstants.POM_FILE_NAME);
}
}
| 7,674 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/maven/MavenFactory.java | /*
* Copyright 2016 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.eclipse.core.maven;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import org.apache.maven.archetype.catalog.Archetype;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.project.ProjectImportConfiguration;
import com.amazonaws.util.StringUtils;
/**
* A helper class used to perform common Maven related operations.
*/
public class MavenFactory {
private static final String MAVEN_SOURCE_FOLDER = "src/main/java";
private static final String MAVEN_TEST_FOLDER = "src/test/java";
private static final String MAVEN_SOURCE_RESOURCES_FOLDER = "src/main/resources";
private static final String MAVEN_TEST_RESOURCES_FOLDER = "src/test/resources";
private static String MAVEN_MODEL_VERSION = "4.0.0";
private static String AWS_JAVA_SDK_GROUP_NAME = "com.amazonaws";
private static String AWS_JAVA_SDK_ARTIFACT_NAME = "aws-java-sdk";
private static String AWS_JAVA_SDK_ARTIFACT_TYPE = "jar";
private static String DEFAULT_AWS_JAVA_SDK_VERSION = "1.11.256";
private static String AWS_JAVA_SDK_BOM_GROUP_NAME = "com.amazonaws";
private static String AWS_JAVA_SDK_BOM_ARTIFACT_NAME = "aws-java-sdk-bom";
private static String AWS_JAVA_SDK_BOM_ARTIFACT_TYPE = "pom";
private static String DEFAULT_AWS_JAVA_SDK_BOM_VERSION = "1.11.256";
private static String AMAZON_KINESIS_CLIENT_GROUP_NAME = "com.amazonaws";
private static String AMAZON_KINESIS_CLIENT_ARTIFACT_NAME = "amazon-kinesis-client";
private static String AMAZON_KINESIS_CLIENT_ARTIFACT_TYPE = "jar";
private static String JUNIT_GROUP_NAME = "junit";
private static String JUNIT_ARTIFACT_NAME = "junit";
private static String JUNIT_ARTIFACT_TYPE = "jar";
private static String DEFAULT_JUNIT_VERSION = "4.11";
private static String AWS_LAMBDA_JAVA_CORE_GROUP_NAME = "com.amazonaws";
private static String AWS_LAMBDA_JAVA_CORE_ARTIFACT_NAME = "aws-lambda-java-core";
private static String AWS_LAMBDA_JAVA_CORE_ARTIFACT_TYPE = "jar";
private static String DEFAULT_AWS_LAMBDA_JAVA_CORE_VERSION = "1.1.0";
private static String AWS_LAMBDA_JAVA_EVENTS_GROUP_NAME = "com.amazonaws";
private static String AWS_LAMBDA_JAVA_EVENTS_ARTIFACT_NAME = "aws-lambda-java-events";
private static String AWS_LAMBDA_JAVA_EVENTS_ARTIFACT_TYPE = "jar";
private static String DEFAULT_AWS_LAMBDA_JAVA_EVENTS_VERSION = "1.3.0";
private static final String[] MAVEN_FOLDERS = {MAVEN_SOURCE_FOLDER, MAVEN_TEST_FOLDER, MAVEN_SOURCE_RESOURCES_FOLDER, MAVEN_TEST_RESOURCES_FOLDER};
public static void createMavenProject(final IProject project, final Model model, IProgressMonitor monitor) throws CoreException {
MavenPlugin.getProjectConfigurationManager().createSimpleProject(
project, null, model, MavenFactory.MAVEN_FOLDERS,
new ProjectImportConfiguration(), monitor);
}
public static List<IProject> createArchetypeProject(String archetypeGroupId, String archetypeArtifactId, String archetypeVersion,
String groupId, String artifactId, String version, String packageName, IProgressMonitor monitor) throws CoreException {
Archetype archetype = new Archetype();
archetype.setGroupId(archetypeGroupId);
archetype.setArtifactId(archetypeArtifactId);
archetype.setVersion(archetypeVersion);
return MavenPlugin.getProjectConfigurationManager().createArchetypeProjects(null, archetype,
groupId, artifactId, version, packageName,
new Properties(), new ProjectImportConfiguration(), monitor);
}
public static String getMavenSourceFolder() {
return MAVEN_SOURCE_FOLDER;
}
public static String getMavenTestFolder() {
return MAVEN_TEST_FOLDER;
}
public static String getMavenResourceFolder() {
return MAVEN_SOURCE_RESOURCES_FOLDER;
}
public static String getMavenTestResourceFolder() {
return MAVEN_TEST_RESOURCES_FOLDER;
}
public static String getMavenModelVersion() {
return MAVEN_MODEL_VERSION;
}
public static Dependency getLatestAwsBomDependency() {
return getLatestArtifactDependency(AWS_JAVA_SDK_BOM_GROUP_NAME, AWS_JAVA_SDK_BOM_ARTIFACT_NAME, "import", AWS_JAVA_SDK_BOM_ARTIFACT_TYPE, DEFAULT_AWS_JAVA_SDK_BOM_VERSION);
}
public static Dependency getLatestAwsSdkDependency(String scope) {
return getLatestArtifactDependency(AWS_JAVA_SDK_GROUP_NAME, AWS_JAVA_SDK_ARTIFACT_NAME, scope, AWS_JAVA_SDK_ARTIFACT_TYPE, DEFAULT_AWS_JAVA_SDK_VERSION);
}
public static Dependency getAwsJavaSdkDependency(String version, String scope) {
return createArtifactDependency(AWS_JAVA_SDK_GROUP_NAME, AWS_JAVA_SDK_ARTIFACT_NAME, version, scope, AWS_JAVA_SDK_ARTIFACT_TYPE);
}
public static Dependency getAmazonKinesisClientDependency(String version, String scope) {
return createArtifactDependency(AMAZON_KINESIS_CLIENT_GROUP_NAME, AMAZON_KINESIS_CLIENT_ARTIFACT_NAME,
version, scope, AMAZON_KINESIS_CLIENT_ARTIFACT_TYPE);
}
public static Dependency getAwsLambdaJavaEventsDependency(String version, String scope) {
return createArtifactDependency(AWS_LAMBDA_JAVA_EVENTS_GROUP_NAME, AWS_LAMBDA_JAVA_EVENTS_ARTIFACT_NAME,
version, scope, AWS_LAMBDA_JAVA_EVENTS_ARTIFACT_TYPE);
}
public static Dependency getAwsLambdaJavaEventsDependency() {
return getAwsLambdaJavaEventsDependency(DEFAULT_AWS_LAMBDA_JAVA_EVENTS_VERSION, "compile");
}
public static Dependency getAwsLambdaJavaCoreDependency(String version, String scope) {
return createArtifactDependency(AWS_LAMBDA_JAVA_CORE_GROUP_NAME, AWS_LAMBDA_JAVA_CORE_ARTIFACT_NAME,
version, scope, AWS_LAMBDA_JAVA_CORE_ARTIFACT_TYPE);
}
public static Dependency getAwsLambdaJavaCoreDependency() {
return getAwsLambdaJavaCoreDependency(DEFAULT_AWS_LAMBDA_JAVA_CORE_VERSION, "compile");
}
public static Dependency getJunitDependency(String version, String scope) {
return createArtifactDependency(JUNIT_GROUP_NAME, JUNIT_ARTIFACT_NAME, version, scope, JUNIT_ARTIFACT_TYPE);
}
public static Dependency getJunitDependency() {
return getJunitDependency(DEFAULT_JUNIT_VERSION, "test");
}
@NonNull
public static String getLatestJavaSdkVersion() {
return Optional.ofNullable(getLatestArtifactVersion(AWS_JAVA_SDK_GROUP_NAME, AWS_JAVA_SDK_ARTIFACT_NAME)).orElse(DEFAULT_AWS_JAVA_SDK_VERSION);
}
private static Dependency getLatestArtifactDependency(String groupId, String artifactId, String scope, String type, String defaultVersion) {
String version = getLatestArtifactVersion(groupId, artifactId);
if (version == null) {
if (defaultVersion == null) {
throw new RuntimeException(
String.format("The latest version of %s cannot be fetched either from remote Maven repository or the local", artifactId));
}
version = defaultVersion;
}
return createArtifactDependency(groupId, artifactId, version, scope, type);
}
private static Dependency createArtifactDependency(
String groupId, String artifactId, String version, String scope, String type) {
Dependency dependency = new Dependency();
dependency.setGroupId(groupId);
dependency.setArtifactId(artifactId);
dependency.setVersion(version);
dependency.setScope(scope);
dependency.setType(type);
return dependency;
}
/**
* Access the default remote Maven repository to fetch the latest version for the specified artifact.
* If the repository is not available or no such an artifact, access the local repository instead.
*/
public static String getLatestArtifactVersion(String groupId, String artifactId) {
String remoteLatestVersion = MavenRepositories.getRemoteMavenRepository().getLatestVersion(groupId, artifactId);
return remoteLatestVersion == null ? MavenRepositories.getDefaultLocalMavenRepository().getLatestVersion(groupId, artifactId)
: remoteLatestVersion;
}
/**
* Assume package name from the group id and artifact id: concatenating them with a dot '.'.
* Return empty string if the parameter is not valid.
*/
public static String assumePackageName(String groupId, String artifactId) {
return StringUtils.isNullOrEmpty(groupId) || StringUtils.isNullOrEmpty(artifactId)
? "" : groupId + "." + artifactId;
}
}
| 7,675 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/maven/MavenRepository.java | /*
* Copyright 2016 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.eclipse.core.maven;
/**
* Interface for artifact managements within a Maven repository.
*/
public interface MavenRepository {
/*
* Returns the latest version of the specified artifact. Return null if the artifact doesn't
* exist or any sort of exception occurs.
*/
String getLatestVersion(String groupId, String artifactId);
}
| 7,676 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/maven/MavenRepositories.java | /*
* Copyright 2016 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.eclipse.core.maven;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.internal.repository.RepositoryRegistry;
import org.eclipse.m2e.core.repository.IRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* Class to manage Maven repositories used in the Maven plugin.
*/
@SuppressWarnings("restriction")
public class MavenRepositories {
private static final String DEFAULT_REMOTE_MAVEN_REPOSITORY_URL = "https://repo.maven.apache.org/maven2/";
public static MavenRepository getRemoteMavenRepository() {
String remoteRepositoryUrl = DEFAULT_REMOTE_MAVEN_REPOSITORY_URL;
// We respect the repositories configured in the Maven plugin.
List<IRepository> repositories = MavenPlugin.getRepositoryRegistry()
.getRepositories(RepositoryRegistry.SCOPE_SETTINGS);
for (IRepository repository : repositories) {
if (repository.getUrl() != null) {
remoteRepositoryUrl = repository.getUrl();
break;
}
}
return getRemoteMavenRepository(remoteRepositoryUrl);
}
private static MavenRepository getRemoteMavenRepository(String remoteUrl) {
return new RemoteMavenRepository(remoteUrl);
}
public static MavenRepository getDefaultLocalMavenRepository() {
return getLocalMavenRepository(MavenPlugin.getRepositoryRegistry().getLocalRepository().getBasedir());
}
private static MavenRepository getLocalMavenRepository(File root) {
return new LocalMavenRepository(root);
}
private static class RemoteMavenRepository implements MavenRepository {
private static final String MAVEN_METADATA_XML_FILE_NAME = "maven-metadata.xml";
private final String remoteUrl;
// Modeled artifact metadata xml file. See http://repo1.maven.org/maven2/junit/junit/maven-metadata.xml for example.
private static class ArtifactMetadata {
public String groupId;
public String artifactId;
public Versioning versioning;
public String getLatest() {
return versioning.latest;
}
}
private static class Versioning {
public String latest;
public String release;
public Long lastUpdated;
public List<String> versions;
}
public RemoteMavenRepository(String remoteUrl) {
if (!remoteUrl.endsWith("/")) {
remoteUrl += "/"; // appending "/" to remote url.
}
// Use "HTTPS" explicitly to avoid 403 error code.
URL url = null;
try {
url = new URL(remoteUrl);
if ("http".equalsIgnoreCase(url.getProtocol())) {
url = new URL("https", url.getHost(), url.getPort(), url.getFile());
}
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
this.remoteUrl = url.toString();
}
@Override
public String getLatestVersion(String groupId, String artifactId) {
String metadataUrl = buildMavenMetadataXmlUrl(groupId, artifactId);
try {
InputStream inputStream = new URL(metadataUrl).openStream();
ObjectMapper mapper = new XmlMapper();
return mapper.readValue(inputStream, ArtifactMetadata.class)
.getLatest();
} catch (Exception e) {
return null;
}
}
// See the following link for example. The URL is fixed given group id and artifact id
// https://repo.maven.apache.org/maven2/com/amazonaws/aws-java-sdk/maven-metadata.xml
private String buildMavenMetadataXmlUrl(String groupId, String artifactId) {
return String.format("%s%s/%s/%s",
this.remoteUrl, groupId.replace('.', '/'), artifactId, MAVEN_METADATA_XML_FILE_NAME);
}
}
private static class LocalMavenRepository implements MavenRepository {
private final String rootPath;
public LocalMavenRepository(File root) {
this.rootPath = root.getAbsolutePath();
}
@Override
public String getLatestVersion(String groupId, String artifactId) {
File targetFile = getTargetFolder(groupId, artifactId);
if (!targetFile.exists() || !targetFile.isDirectory()) {
return null;
}
List<String> versions = Arrays.asList(targetFile.list());
if (versions.isEmpty()) {
return null;
}
Collections.sort(versions, new MavenArtifactVersionComparator());
return versions.get(0);
}
private File getTargetFolder(String groupId, String artifactId) {
return new File(String.format("%s/%s/%s", rootPath, groupId.replace('.', '/'), artifactId));
}
}
}
| 7,677 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic/ui/AwsToolkitErrorSupportProvider.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.core.diagnostic.ui;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
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.jface.dialogs.ErrorSupportProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
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.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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.statushandlers.AbstractStatusAreaProvider;
import org.eclipse.ui.statushandlers.StatusAdapter;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.diagnostic.utils.AwsErrorReportUtils;
import com.amazonaws.eclipse.core.diagnostic.utils.EmailMessageLauncher;
import com.amazonaws.eclipse.core.diagnostic.utils.PlatformEnvironmentDataCollector;
import com.amazonaws.eclipse.core.exceptions.AwsActionException;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.eclipse.core.ui.EmailLinkListener;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.core.ui.overview.Toolkit;
import com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory;
import com.amazonaws.services.errorreport.model.ErrorDataModel;
import com.amazonaws.services.errorreport.model.ErrorReportDataModel;
/**
* A custom AbstractStatusAreaProvider implementation that provides additional
* UI components for users to directly report errors that are associated with
* "com.amazonaws.*" plugins.
*
* NOTE: this class won't work if it directly extends ErrorSupportProvider,
* since the default workbench error dialog will only check the
* {@link #validFor(StatusAdapter)} method if it finds an instance of
* AbstractStatusAreaProvider.
*
* @see http://wiki.eclipse.org/Status_Handling_Best_Practices#
* Developing_an_ErrorSupportProvider
*
* @see "org.eclipse.ui.internal.statushandlers.InternalDialog"
* @see "org.eclipse.ui.internal.statushandlers.SupportTray"
*/
public class AwsToolkitErrorSupportProvider extends AbstractStatusAreaProvider {
/** http://www.regular-expressions.info/email.html */
private static final String VALID_EMAIL_REGEX = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$";
private static final String COM_DOT_AMAZONAWS_DOT = "com.amazonaws.";
/**
* The ErrorSupportProvider that was previously configured in the JFace
* Policy. Status events that don't match the criteria of
* AwsToolkitErrorSupportProvider will be handled by this provider instead
* (it it's not null).
*/
private final ErrorSupportProvider overriddenProvider;
public AwsToolkitErrorSupportProvider(ErrorSupportProvider overriddenProvider) {
this.overriddenProvider = overriddenProvider;
}
/**
* Returns true if the given status should be processed by either the
* AWS-specific error reporting support or the ErrorSupportProvider that was
* overridden by this class.
* <p>
* The workbench's internal error dialog won't create the support area if
* this method returns false.
*
* @see AbstractStatusAreaProvider#validFor(StatusAdapter)
*/
@Override
public boolean validFor(StatusAdapter statusAdapter) {
IStatus status = statusAdapter.getStatus();
if (status == null) return false;
return isAwsErrorStatus(status) || validForOverriddenProvider(status);
}
/**
* Returns true if the status has ERROR-level severity and that it's
* associated with "com.amazonaws.*" plugins.
*/
private static boolean isAwsErrorStatus(IStatus status) {
return status != null
&&
status.getSeverity() == Status.ERROR
&&
status.getPlugin() != null
&&
status.getPlugin().startsWith(COM_DOT_AMAZONAWS_DOT);
}
/**
* Returns true if the status is valid for the error provider that was
* overridden by this provider.
*/
private boolean validForOverriddenProvider(IStatus status) {
if (overriddenProvider == null)
return false;
// ErrorSupportProvider#validFor(IStatus) is not added to Eclipse
// platform until 3.7 version.
try {
Method validFor = overriddenProvider.getClass().getMethod("validFor", IStatus.class);
return (Boolean) validFor.invoke(overriddenProvider, status);
} catch (Exception e) {
return false;
}
}
/**
* Create the custom support area that will be injected in the workbench
* default error dialog.
*/
@Override
public Control createSupportArea(Composite parent, final StatusAdapter statusAdapter) {
final IStatus status = statusAdapter.getStatus();
// If the status is not associated with "com.amazonaws.*", we check
// whether it should be handled by the overridden provider.
if ( !isAwsErrorStatus(status) ) {
return validForOverriddenProvider(status)?
overriddenProvider.createSupportArea(parent, status)
:
parent;
}
GridData parentData = new GridData(SWT.FILL, SWT.FILL, true, true);
parentData.widthHint = 300;
parentData.minimumWidth = 300;
parentData.heightHint = 250;
parentData.minimumHeight = 250;
parent.setLayoutData(parentData);
GridLayout layout = new GridLayout(1, false);
layout.marginBottom = 15;
parent.setLayout(layout);
Group userInputGroup = new Group(parent, SWT.NONE);
GridData groupData = new GridData(SWT.FILL, SWT.FILL, true, true);
userInputGroup.setLayoutData(groupData);
userInputGroup.setLayout(new GridLayout(1, false));
/* User email input */
final Label label_email = new Label(userInputGroup, SWT.WRAP);
label_email.setText("(Optional) Please provide a valid email:");
label_email.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
final Text email = new Text(userInputGroup, SWT.BORDER | SWT.SINGLE);
email.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
// Pre-populate the default user email if it's found in the preference store
email.setText(AwsToolkitCore.getDefault().getPreferenceStore()
.getString(PreferenceConstants.P_ERROR_REPORT_DEFAULT_USER_EMAIL));
/* User description input */
Label label_description = new Label(userInputGroup, SWT.WRAP);
label_description.setText("(Optional) Please provide more details to help us investigate:");
label_description.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
final Text description = new Text(userInputGroup, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL);
description.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
WizardWidgetFactory.newLink(userInputGroup, new WebLinkListener(), String.format(
"You can also cut a <a href=\"%s\">Github Issue</a> for tracking the problem. Since it will be public, please exclude sensitive data from the report.",
"https://github.com/aws/aws-toolkit-eclipse/issues/new"), 1);
/* OK button */
final Button reportBtn = new Button(parent, SWT.PUSH);
reportBtn.setText("Report this bug to AWS");
reportBtn.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
reportBtn.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
final String userEmail = email.getText();
final String userDescription = description.getText();
Job job = new Job("Sending error report to AWS...") {
@Override
protected IStatus run(IProgressMonitor arg0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
final ErrorReportDataModel errorReportDataModel = new ErrorReportDataModel()
.error(new ErrorDataModel()
.stackTrace(AwsErrorReportUtils.getStackTraceFromThrowable(status.getException()))
.errorMessage(status.getMessage()))
.platformData(PlatformEnvironmentDataCollector.getData())
.userEmail(userEmail)
.userDescription(userDescription)
.timeOfError(sdf.format(new Date()));
if (status.getException() instanceof AwsActionException) {
errorReportDataModel.setCommandRun(((AwsActionException) status.getException()).getActionName());
}
try {
AwsErrorReportUtils.reportBugToAws(errorReportDataModel);
} catch (Exception error) {
// Show a message box with mailto: link as fallback
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
showFailureDialog(Display.getDefault().getActiveShell(), errorReportDataModel);
}
});
AwsToolkitCore.getDefault().logInfo(
"Unable to send error report. " + error.getMessage());
return Status.CANCEL_STATUS;
}
// If success, save the email as default
AwsToolkitCore.getDefault().getPreferenceStore().setValue(
PreferenceConstants.P_ERROR_REPORT_DEFAULT_USER_EMAIL,
userEmail);
// Show a confirmation message
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
showSuccessDialog(Display.getDefault().getActiveShell());
}
});
AwsToolkitCore.getDefault().logInfo("Successfully sent the error report.");
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
reportBtn.setEnabled(false);
}
});
// Add simple validation to the email field
email.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
String userInput = email.getText();
// It's either empty, or a valid email address
if (userInput.isEmpty()
|| userInput.matches(VALID_EMAIL_REGEX)) {
label_email.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLACK));
reportBtn.setEnabled(true);
} else {
label_email.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_RED));
reportBtn.setEnabled(false);
}
}
});
return parent;
}
private static void showSuccessDialog(Shell parentShell) {
MessageDialog.openInformation(parentShell,
"Successfully sent error report",
"Thanks for reporting the error. " +
"Our team will investigate this as soon as possible.");
}
private static void showFailureDialog(Shell parentShell, ErrorReportDataModel errorData) {
MessageDialog dialog = new ErrorReportFailureMessageDialog(parentShell,
errorData);
dialog.open();
}
private static class ErrorReportFailureMessageDialog extends MessageDialog {
private static final String COPY_TO_CLIPBOARD_LABEL = "Copy error report data to clipboard";
private final ErrorReportDataModel errorData;
public ErrorReportFailureMessageDialog(Shell parentShell, ErrorReportDataModel errorData) {
super(parentShell,
"Failed to send error report",
AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_ICON),
"Failed to send error report data to AWS.",
MessageDialog.NONE, new String[] { "Ok", COPY_TO_CLIPBOARD_LABEL }, 0);
this.errorData = errorData;
}
@Override
protected Control createCustomArea(Composite parent) {
// Add the mailto: link
Link link = new Link(parent, SWT.WRAP);
link.setText("Please contact us via email "
+ Toolkit.createAnchor(
EmailMessageLauncher.AWS_ECLIPSE_ERRORS_AT_AMZN,
EmailMessageLauncher.AWS_ECLIPSE_ERRORS_AT_AMZN));
WizardWidgetFactory.newLink(parent, new WebLinkListener(), String.format(
"You can also cut a <a href=\"%s\">Github Issue</a> for tracking the problem. Since it will be public, please exclude sensitive data from the report.",
"https://github.com/aws/aws-toolkit-eclipse/issues/new"), 1);
EmailLinkListener emailLinkListener
= new EmailLinkListener(EmailMessageLauncher.createEmptyErrorReportEmail());
link.addListener(SWT.Selection, emailLinkListener);
return parent;
}
/**
* We need to override this method in order to suppress closing the
* dialog after the user clicks the
* "Copy error report data to clipboard" button.
*/
@Override
protected void buttonPressed(int buttonId) {
if (buttonId == 1) {
Clipboard clipboard = null;
try {
clipboard = new Clipboard(Display.getDefault());
clipboard.setContents(new Object[] { errorData.toString() },
new Transfer[] { TextTransfer.getInstance() });
} finally {
if (clipboard != null) {
clipboard.dispose();
}
}
return;
}
super.buttonPressed(buttonId);
}
}
}
| 7,678 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic/utils/EmailMessageLauncher.java | /*
* Copyright 2008-2014 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.core.diagnostic.utils;
import java.util.logging.Logger;
import org.eclipse.swt.program.Program;
import com.amazonaws.util.SdkHttpUtils;
/**
* A utility class responsible for opening an email message.
*/
public class EmailMessageLauncher {
public static final String AWS_ECLIPSE_FEEDBACK_AT_AMZN = "aws-eclipse-feedback@amazon.com";
public static final String ECLIPSE_FEEDBACK_SUBJECT = "AWS Eclipse Toolkit General Feedback";
public static final String AWS_ECLIPSE_ERRORS_AT_AMZN = "aws-eclipse-errors@amazon.com";
public static final String ECLIPSE_ERROR_REPORT_SUBJECT = "AWS Eclipse Toolkit Error Report";
private final String recipient;
private final String subject;
private final String body;
private EmailMessageLauncher(String recipient, String subject, String body) {
this.recipient = recipient;
this.subject = subject;
this.body = body;
}
/**
* Use "mailto:" link to open an email message via the system preferred
* email client.
*/
public void open() {
try {
StringBuilder mailto = new StringBuilder()
.append("mailto:").append(SdkHttpUtils.urlEncode(recipient, false))
.append("?subject=").append(SdkHttpUtils.urlEncode(subject, false))
.append("&body=").append(SdkHttpUtils.urlEncode(body, false));
Program.launch(mailto.toString());
} catch (Exception e) {
Logger logger = Logger.getLogger(EmailMessageLauncher.class.getName());
logger.warning("Unable to open email message to '" + recipient + "': " + e.getMessage());
}
}
/**
* Create an email launcher that builds a message sent to
* "aws-eclipse-feedback@amazon.com"
*/
public static EmailMessageLauncher createEmptyFeedbackEmail() {
return new EmailMessageLauncher(
AWS_ECLIPSE_FEEDBACK_AT_AMZN, ECLIPSE_FEEDBACK_SUBJECT, "");
}
/**
* Create an email launcher that builds a message sent to
* "aws-eclipse-errors@amazon.com"
*/
public static EmailMessageLauncher createEmptyErrorReportEmail() {
return new EmailMessageLauncher(
AWS_ECLIPSE_ERRORS_AT_AMZN, ECLIPSE_ERROR_REPORT_SUBJECT, "");
}
}
| 7,679 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic/utils/AwsErrorReportUtils.java | /*
* Copyright 2008-2014 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.core.diagnostic.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.cognito.AWSCognitoCredentialsProvider;
import com.amazonaws.eclipse.core.telemetry.cognito.identity.ToolkitCachedCognitoIdentityIdProvider;
import com.amazonaws.eclipse.core.telemetry.internal.Constants;
import com.amazonaws.services.errorreport.ErrorReporter;
import com.amazonaws.services.errorreport.ErrorReporterClient;
import com.amazonaws.services.errorreport.model.ErrorReportDataModel;
import com.amazonaws.services.errorreport.model.PostReportRequest;
import com.amazonaws.services.errorreport.model.PostReportResult;
/**
* A util class responsible for sending error report data to the AWS ErrorReport platform.
*/
public class AwsErrorReportUtils {
private static final ErrorReporter ERROR_REPORTER_CLIENT = buildErrorReporterClient();
/**
* Send the error report data to the AWS ErrorReport platform.
*
* @throws AmazonClientException
* Thrown if the toolkit failed to retrieve a fresh
* authenticity_token, or if any client-side error occurred when
* sending the POST request and reading the POST response.
* @throws AmazonServiceException
* Thrown if the POST request was rejected with non-2xx status
* code.
*/
public static void reportBugToAws(final ErrorReportDataModel reportData)
throws AmazonClientException, AmazonServiceException {
PostReportResult result = ERROR_REPORTER_CLIENT.postReport(new PostReportRequest()
.errorReportDataModel(reportData));
if (!result.getErrorReportResult().isSuccess()) {
throw new RuntimeException(result.getErrorReportResult().getMessage());
}
}
public static String getStackTraceFromThrowable(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.println();
if (t.getCause() != null) {
t.getCause().printStackTrace(pw);
}
return sw.toString();
}
private static ErrorReporter buildErrorReporterClient() {
ToolkitCachedCognitoIdentityIdProvider identityIdProvider = new ToolkitCachedCognitoIdentityIdProvider(
Constants.COGNITO_IDENTITY_POOL_ID_PROD, AwsToolkitCore.getDefault().getPreferenceStore());
AWSCredentialsProvider credentialsProvider = new AWSCognitoCredentialsProvider(identityIdProvider);
return ErrorReporterClient.builder()
.iamCredentials(credentialsProvider)
.iamRegion(Constants.COGNITO_IDENTITY_SERVICE_REGION.getName())
.endpoint(Constants.ERROR_REPORT_SERVICE_ENDPOINT)
.build();
}
} | 7,680 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic/utils/ServiceExceptionParser.java | /*
* Copyright 2010-2014 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.eclipse.core.diagnostic.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.amazonaws.AmazonServiceException;
public class ServiceExceptionParser {
private static final String ACCESS_DENIED = "AccessDenied";
private static final String OPERATION_NOT_ALLOWED_MSG_REGEX = "(.+) is not authorized to perform: (.+) on resource: (.+)";
public static final String PRINCIPAL = "PRINCIPAL";
public static final String ACTION = "ACTION";
public static final String RESOURCE = "RESOURCE";
/**
* Returns true if the given service exception indicates that the current
* IAM user doesn't have sufficient permission to perform the operation.
*/
public static boolean isOperationNotAllowedException(Exception e) {
return e instanceof AmazonServiceException
&& parseOperationNotAllowedException((AmazonServiceException) e) != null;
}
/**
* Returns a map of properties parsed from the given exception, or null if
* the exception doesn't indicate a operation-not-allowed error.
* <p>
* The following properties are available in the returned map:
* <ul>
* <li>PRINCIPAL</li>
* <li>ACTION</li>
* <li>RESOURCE</li>
* </ul>
*/
public static Map<String, String> parseOperationNotAllowedException(AmazonServiceException ase) {
if (ase != null
&& ACCESS_DENIED.equalsIgnoreCase(ase.getErrorCode())
&& ase.getErrorMessage() != null) {
Pattern p = Pattern.compile(OPERATION_NOT_ALLOWED_MSG_REGEX);
Matcher m = p.matcher(ase.getErrorMessage());
if (m.matches()) {
Map<String, String> properties = new HashMap<>();
properties.put(PRINCIPAL, m.group(1));
properties.put(ACTION, m.group(2));
properties.put(RESOURCE, m.group(3));
return properties;
}
}
return null;
}
}
| 7,681 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/diagnostic/utils/PlatformEnvironmentDataCollector.java | /*
* Copyright 2008-2014 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.core.diagnostic.utils;
import org.eclipse.core.runtime.Platform;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.internal.Constants;
import com.amazonaws.services.errorreport.model.PlatformDataModel;
/**
* This class collects all the platform runtime environment data upon its
* initialization.
*/
final public class PlatformEnvironmentDataCollector {
private static final PlatformDataModel DATA = getPlatformDataModel(Constants.AWS_TOOLKIT_FOR_ECLIPSE_PRODUCT_NAME);
private static final PlatformDataModel DATA_TEST = getPlatformDataModel(Constants.AWS_TOOLKIT_FOR_ECLIPSE_PRODUCT_NAME_TEST);
public static PlatformDataModel getData() {
return AwsToolkitCore.getDefault().isDebugMode() ? DATA_TEST : DATA;
}
private static PlatformDataModel getPlatformDataModel(final String productName) {
return new PlatformDataModel()
.awsProduct(productName)
.awsProductVersion(AwsToolkitCore.getDefault().getBundle().getVersion().toString())
.language("Java")
.languageVersion(System.getProperty("java.version"))
.languageVmName(System.getProperty("java.vm.name"))
.osArch(System.getProperty("os.arch"))
.osName(System.getProperty("os.name"))
.osVersion(System.getProperty("os.version"))
.platform("Eclipse")
.platformVersion(Platform.getBundle("org.eclipse.platform").getVersion().toString());
}
}
| 7,682 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiConsoleColorPalette.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
import org.eclipse.swt.graphics.RGB;
import com.amazonaws.eclipse.core.util.OsPlatformUtils;
public class AnsiConsoleColorPalette {
private static final int PALETTE_SIZE = 256;
// From Wikipedia, http://en.wikipedia.org/wiki/ANSI_escape_code
private final static RGB[] paletteXP = {
new RGB( 0, 0, 0), // black
new RGB(128, 0, 0), // red
new RGB( 0, 128, 0), // green
new RGB(128, 128, 0), // brown/yellow
new RGB( 0, 0, 128), // blue
new RGB(128, 0, 128), // magenta
new RGB( 0, 128, 128), // cyan
new RGB(192, 192, 192), // gray
new RGB(128, 128, 128), // dark gray
new RGB(255, 0, 0), // bright red
new RGB( 0, 255, 0), // bright green
new RGB(255, 255, 0), // yellow
new RGB( 0, 0, 255), // bright blue
new RGB(255, 0, 255), // bright magenta
new RGB( 0, 255, 255), // bright cyan
new RGB(255, 255, 255) // white
};
private final static RGB[] paletteMac = {
new RGB( 0, 0, 0), // black
new RGB(194, 54, 33), // red
new RGB( 37, 188, 36), // green
new RGB(173, 173, 39), // brown/yellow
new RGB( 73, 46, 225), // blue
new RGB(211, 56, 211), // magenta
new RGB( 51, 187, 200), // cyan
new RGB(203, 204, 205), // gray
new RGB(129, 131, 131), // dark gray
new RGB(252, 57, 31), // bright red
new RGB( 49, 231, 34), // bright green
new RGB(234, 236, 35), // yellow
new RGB( 88, 51, 255), // bright blue
new RGB(249, 53, 248), // bright magenta
new RGB( 20, 240, 240), // bright cyan
new RGB(233, 235, 235) // white
};
private final static RGB[] paletteXTerm = {
new RGB( 0, 0, 0), // black
new RGB(205, 0, 0), // red
new RGB( 0, 205, 0), // green
new RGB(205, 205, 0), // brown/yellow
new RGB( 0, 0, 238), // blue
new RGB(205, 0, 205), // magenta
new RGB( 0, 205, 205), // cyan
new RGB(229, 229, 229), // gray
new RGB(127, 127, 127), // dark gray
new RGB(255, 0, 0), // bright red
new RGB( 0, 255, 0), // bright green
new RGB(255, 255, 0), // yellow
new RGB( 92, 92, 255), // bright blue
new RGB(255, 0, 255), // bright magenta
new RGB( 0, 255, 255), // bright cyan
new RGB(255, 255, 255) // white
};
private static RGB[] palette = getDefaultPalette();
public static boolean isValidIndex(int value) {
return value >= 0 && value < PALETTE_SIZE;
}
static int TRUE_RGB_FLAG = 0x10000000; // Representing true RGB colors as 0x10RRGGBB
public static int hackRgb(int r, int g, int b) {
if (!isValidIndex(r)) return -1;
if (!isValidIndex(g)) return -1;
if (!isValidIndex(b)) return -1;
return TRUE_RGB_FLAG | r << 16 | g << 8 | b;
}
static int safe256(int value, int modulo) {
int result = value * PALETTE_SIZE / modulo;
return result < PALETTE_SIZE ? result : PALETTE_SIZE - 1;
}
public static RGB getColor(Integer index) {
if (null == index)
return null;
if (index >= TRUE_RGB_FLAG) {
int red = index >> 16 & 0xff;
int green = index >> 8 & 0xff;
int blue = index & 0xff;
return new RGB(red, green, blue);
}
if (index >= 0 && index < palette.length) // basic, 16 color palette
return palette[index];
if (index >= 16 && index < 232) { // 6x6x6 color matrix
int color = index - 16;
int blue = color % 6;
color = color / 6;
int green = color % 6;
int red = color / 6;
return new RGB(safe256(red, 6), safe256(green, 6), safe256(blue, 6));
}
if (index >= 232 && index < PALETTE_SIZE) { // grayscale
int gray = safe256(index - 232, 24);
return new RGB(gray, gray, gray);
}
return null;
}
private static RGB[] getDefaultPalette() {
if (OsPlatformUtils.isWindows()) {
return paletteXP;
} else if (OsPlatformUtils.isMac()) {
return paletteMac;
} else {
return paletteXTerm;
}
}
} | 7,683 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiConsoleStyleListener.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_CONCEAL_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_CONCEAL_ON;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_CROSSOUT_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_CROSSOUT_ON;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_FRAMED_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_FRAMED_ON;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_INTENSITY_BRIGHT;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_INTENSITY_FAINT;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_INTENSITY_NORMAL;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_ITALIC;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_ITALIC_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_NEGATIVE_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_NEGATIVE_ON;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_RESET;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_UNDERLINE;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_UNDERLINE_DOUBLE;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_ATTR_UNDERLINE_OFF;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_BACKGROUND_FIRST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_BACKGROUND_LAST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_BACKGROUND_RESET;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_FOREGROUND_FIRST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_FOREGROUND_LAST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_FOREGROUND_RESET;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_COLOR_INTENSITY_DELTA;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_BACKGROUND;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_BACKGROUND_FIRST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_BACKGROUND_LAST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_FOREGROUND;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_FOREGROUND_FIRST;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.COMMAND_HICOLOR_FOREGROUND_LAST;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.LineStyleEvent;
import org.eclipse.swt.custom.LineStyleListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GlyphMetrics;
public class AnsiConsoleStyleListener implements LineStyleListener {
private AnsiConsoleAttributes lastAttributes = new AnsiConsoleAttributes();
private AnsiConsoleAttributes currentAttributes = new AnsiConsoleAttributes();
private final static Pattern pattern = Pattern.compile("\u001b\\[[\\d;]*[A-HJKSTfimnsu]");
private final static char ESCAPE_SGR = 'm';
int lastRangeEnd = 0;
private boolean interpretCommand(List<Integer> nCommands) {
boolean result = false;
Iterator<Integer> iter = nCommands.iterator();
while (iter.hasNext()) {
int nCmd = iter.next();
switch (nCmd) {
case COMMAND_ATTR_RESET: currentAttributes.reset(); break;
case COMMAND_ATTR_INTENSITY_BRIGHT: currentAttributes.bold = true; break;
case COMMAND_ATTR_INTENSITY_FAINT: currentAttributes.bold = false; break;
case COMMAND_ATTR_INTENSITY_NORMAL: currentAttributes.bold = false; break;
case COMMAND_ATTR_ITALIC: currentAttributes.italic = true; break;
case COMMAND_ATTR_ITALIC_OFF: currentAttributes.italic = false; break;
case COMMAND_ATTR_UNDERLINE: currentAttributes.underline = SWT.UNDERLINE_SINGLE; break;
case COMMAND_ATTR_UNDERLINE_DOUBLE: currentAttributes.underline = SWT.UNDERLINE_DOUBLE; break;
case COMMAND_ATTR_UNDERLINE_OFF: currentAttributes.underline = AnsiConsoleAttributes.UNDERLINE_NONE; break;
case COMMAND_ATTR_CROSSOUT_ON: currentAttributes.strike = true; break;
case COMMAND_ATTR_CROSSOUT_OFF: currentAttributes.strike = false; break;
case COMMAND_ATTR_NEGATIVE_ON: currentAttributes.invert = true; break;
case COMMAND_ATTR_NEGATIVE_OFF: currentAttributes.invert = false; break;
case COMMAND_ATTR_CONCEAL_ON: currentAttributes.conceal = true; break;
case COMMAND_ATTR_CONCEAL_OFF: currentAttributes.conceal = false; break;
case COMMAND_ATTR_FRAMED_ON: currentAttributes.framed = true; break;
case COMMAND_ATTR_FRAMED_OFF: currentAttributes.framed = false; break;
case COMMAND_COLOR_FOREGROUND_RESET: currentAttributes.currentFgColor = null; break;
case COMMAND_COLOR_BACKGROUND_RESET: currentAttributes.currentBgColor = null; break;
case COMMAND_HICOLOR_FOREGROUND:
case COMMAND_HICOLOR_BACKGROUND: // {esc}[48;5;{color}m
int color = -1;
int nMustBe2or5 = iter.hasNext() ? iter.next() : -1;
if (nMustBe2or5 == 5) { // 256 colors
color = iter.hasNext() ? iter.next() : -1;
if (!AnsiConsoleColorPalette.isValidIndex(color))
color = -1;
} else if (nMustBe2or5 == 2) { // rgb colors
int r = iter.hasNext() ? iter.next() : -1;
int g = iter.hasNext() ? iter.next() : -1;
int b = iter.hasNext() ? iter.next() : -1;
color = AnsiConsoleColorPalette.hackRgb(r, g, b);
}
if (color != -1) {
if (nCmd == COMMAND_HICOLOR_FOREGROUND)
currentAttributes.currentFgColor = color;
else
currentAttributes.currentBgColor = color;
}
break;
case -1: break; // do nothing
default:
if (nCmd >= COMMAND_COLOR_FOREGROUND_FIRST && nCmd <= COMMAND_COLOR_FOREGROUND_LAST) // text color
currentAttributes.currentFgColor = nCmd - COMMAND_COLOR_FOREGROUND_FIRST;
else if (nCmd >= COMMAND_COLOR_BACKGROUND_FIRST && nCmd <= COMMAND_COLOR_BACKGROUND_LAST) // background color
currentAttributes.currentBgColor = nCmd - COMMAND_COLOR_BACKGROUND_FIRST;
else if (nCmd >= COMMAND_HICOLOR_FOREGROUND_FIRST && nCmd <= COMMAND_HICOLOR_FOREGROUND_LAST) // text color
currentAttributes.currentFgColor = nCmd - COMMAND_HICOLOR_FOREGROUND_FIRST + COMMAND_COLOR_INTENSITY_DELTA;
else if (nCmd >= COMMAND_HICOLOR_BACKGROUND_FIRST && nCmd <= COMMAND_HICOLOR_BACKGROUND_LAST) // background color
currentAttributes.currentBgColor = nCmd - COMMAND_HICOLOR_BACKGROUND_FIRST + COMMAND_COLOR_INTENSITY_DELTA;
}
}
return result;
}
private void addRange(List<StyleRange> ranges, int start, int length, Color foreground, boolean isCode) {
StyleRange range = new StyleRange(start, length, foreground, null);
AnsiConsoleAttributes.updateRangeStyle(range, lastAttributes);
if (isCode) {
range.metrics = new GlyphMetrics(0, 0, 0);
}
ranges.add(range);
lastRangeEnd = lastRangeEnd + range.length;
}
@Override
public void lineGetStyle(LineStyleEvent event) {
if (event == null || event.lineText == null || event.lineText.length() == 0)
return;
String currentText = event.lineText;
Matcher matcher = pattern.matcher(currentText);
// Return directly if the pattern is not found.
if (!matcher.find()) {
return;
}
StyleRange defStyle;
if (event.styles != null && event.styles.length > 0) {
defStyle = (StyleRange) event.styles[0].clone();
if (defStyle.background == null)
defStyle.background = AnsiConsolePreferenceUtils.getDebugConsoleBgColor();
} else {
defStyle = new StyleRange(1, lastRangeEnd,
new Color(null, AnsiConsoleColorPalette.getColor(0)),
new Color(null, AnsiConsoleColorPalette.getColor(15)),
SWT.NORMAL);
}
lastRangeEnd = 0;
List<StyleRange> ranges = new ArrayList<StyleRange>();
do {
int start = matcher.start();
int end = matcher.end();
String theEscape = currentText.substring(start + 2, end - 1);
char code = currentText.charAt(end - 1);
if (code == ESCAPE_SGR) {
// Select Graphic Rendition (SGR) escape sequence
List<Integer> nCommands = new ArrayList<Integer>();
for (String cmd : theEscape.split(";")) {
int nCmd = AnsiConsolePreferenceUtils.tryParseInteger(cmd);
if (nCmd != -1)
nCommands.add(nCmd);
}
if (nCommands.isEmpty())
nCommands.add(0);
interpretCommand(nCommands);
}
if (lastRangeEnd != start)
addRange(ranges, event.lineOffset + lastRangeEnd, start - lastRangeEnd, defStyle.foreground, false);
lastAttributes = currentAttributes.clone();
addRange(ranges, event.lineOffset + start, end - start, defStyle.foreground, true);
} while (matcher.find());
if (lastRangeEnd != currentText.length())
addRange(ranges, event.lineOffset + lastRangeEnd, currentText.length() - lastRangeEnd, defStyle.foreground, false);
lastAttributes = currentAttributes.clone();
if (!ranges.isEmpty())
event.styles = ranges.toArray(new StyleRange[ranges.size()]);
}
}
| 7,684 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiConsolePreferenceUtils.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IPreferencesService;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
public class AnsiConsolePreferenceUtils {
private final static String DEBUG_CONSOLE_PLUGIN_ID = "org.eclipse.debug.ui";
private final static String DEBUG_CONSOLE_FALLBACK_BKCOLOR = "0,0,0";
private final static String DEBUG_CONSOLE_FALLBACK_FGCOLOR = "192,192,192";
static Color colorFromStringRgb(String strRgb) {
Color result = null;
String[] splitted = strRgb.split(",");
if (splitted != null && splitted.length == 3) {
int red = tryParseInteger(splitted[0]);
int green = tryParseInteger(splitted[1]);
int blue = tryParseInteger(splitted[2]);
result = new Color(null, new RGB(red, green, blue));
}
return result;
}
public static Color getDebugConsoleBgColor() {
IPreferencesService ps = Platform.getPreferencesService();
String value = ps.getString(DEBUG_CONSOLE_PLUGIN_ID, "org.eclipse.debug.ui.consoleBackground",
DEBUG_CONSOLE_FALLBACK_BKCOLOR, null);
return colorFromStringRgb(value);
}
public static Color getDebugConsoleFgColor() {
IPreferencesService ps = Platform.getPreferencesService();
String value = ps.getString(DEBUG_CONSOLE_PLUGIN_ID, "org.eclipse.debug.ui.outColor",
DEBUG_CONSOLE_FALLBACK_FGCOLOR, null);
return colorFromStringRgb(value);
}
public static int tryParseInteger(String text) {
if ("".equals(text))
return -1;
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return -1;
}
}
}
| 7,685 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiConsoleAttributes.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import com.amazonaws.eclipse.core.util.OsPlatformUtils;
import static com.amazonaws.eclipse.core.ansi.AnsiCommands.*;
public class AnsiConsoleAttributes implements Cloneable {
public final static int UNDERLINE_NONE = -1; // nothing in SWT, a bit of an abuse
public Integer currentBgColor;
public Integer currentFgColor;
public int underline;
public boolean bold;
public boolean italic;
public boolean invert;
public boolean conceal;
public boolean strike;
public boolean framed;
public AnsiConsoleAttributes() {
reset();
}
public void reset() {
currentBgColor = null;
currentFgColor = null;
underline = UNDERLINE_NONE;
bold = false;
italic = false;
invert = false;
conceal = false;
strike = false;
framed = false;
}
@Override
public AnsiConsoleAttributes clone() {
AnsiConsoleAttributes result = new AnsiConsoleAttributes();
result.currentBgColor = currentBgColor;
result.currentFgColor = currentFgColor;
result.underline = underline;
result.bold = bold;
result.italic = italic;
result.invert = invert;
result.conceal = conceal;
result.strike = strike;
result.framed = framed;
return result;
}
public static Color hiliteRgbColor(Color c) {
if (c == null)
return new Color(null, new RGB(0xff, 0xff, 0xff));
int red = c.getRed() * 2;
int green = c.getGreen() * 2;
int blue = c.getBlue() * 2;
if (red > 0xff) red = 0xff;
if (green > 0xff) green = 0xff;
if (blue > 0xff) blue = 0xff;
return new Color(null, new RGB(red, green, blue)); // here
}
// This function maps from the current attributes as "described" by escape sequences to real,
// Eclipse console specific attributes (resolving color palette, default colors, etc.)
public static void updateRangeStyle(StyleRange range, AnsiConsoleAttributes attribute) {
boolean useWindowsMapping = OsPlatformUtils.isWindows();
AnsiConsoleAttributes tempAttrib = attribute.clone();
boolean hilite = false;
if (useWindowsMapping) {
if (tempAttrib.bold) {
tempAttrib.bold = false; // not supported, rendered as intense, already done that
hilite = true;
}
if (tempAttrib.italic) {
tempAttrib.italic = false;
tempAttrib.invert = true;
}
tempAttrib.underline = UNDERLINE_NONE; // not supported on Windows
tempAttrib.strike = false; // not supported on Windows
tempAttrib.framed = false; // not supported on Windows
}
// Prepare the foreground color
if (hilite) {
if (tempAttrib.currentFgColor == null) {
range.foreground = AnsiConsolePreferenceUtils.getDebugConsoleFgColor();
range.foreground = hiliteRgbColor(range.foreground);
} else {
if (tempAttrib.currentFgColor < COMMAND_COLOR_INTENSITY_DELTA)
range.foreground = new Color(null, AnsiConsoleColorPalette.getColor(tempAttrib.currentFgColor + COMMAND_COLOR_INTENSITY_DELTA));
else
range.foreground = new Color(null, AnsiConsoleColorPalette.getColor(tempAttrib.currentFgColor));
}
} else {
if (tempAttrib.currentFgColor != null)
range.foreground = new Color(null, AnsiConsoleColorPalette.getColor(tempAttrib.currentFgColor));
}
// Prepare the background color
if (tempAttrib.currentBgColor != null)
range.background = new Color(null, AnsiConsoleColorPalette.getColor(tempAttrib.currentBgColor));
// These two still mess with the foreground/background colors
// We need to solve them before we use them for strike/underline/frame colors
if (tempAttrib.invert) {
if (range.foreground == null)
range.foreground = AnsiConsolePreferenceUtils.getDebugConsoleFgColor();
if (range.background == null)
range.background = AnsiConsolePreferenceUtils.getDebugConsoleBgColor();
Color tmp = range.background;
range.background = range.foreground;
range.foreground = tmp;
}
if (tempAttrib.conceal) {
if (range.background == null)
range.background = AnsiConsolePreferenceUtils.getDebugConsoleBgColor();
range.foreground = range.background;
}
range.font = null;
range.fontStyle = SWT.NORMAL;
// Prepare the rest of the attributes
if (tempAttrib.bold)
range.fontStyle |= SWT.BOLD;
if (tempAttrib.italic)
range.fontStyle |= SWT.ITALIC;
if (tempAttrib.underline != UNDERLINE_NONE) {
range.underline = true;
range.underlineColor = range.foreground;
range.underlineStyle = tempAttrib.underline;
}
else
range.underline = false;
range.strikeout = tempAttrib.strike;
range.strikeoutColor = range.foreground;
if (tempAttrib.framed) {
range.borderStyle = SWT.BORDER_SOLID;
range.borderColor = range.foreground;
}
else
range.borderStyle = SWT.NONE;
}
} | 7,686 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiConsolePageParticipant.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsolePageParticipant;
import org.eclipse.ui.part.IPageBookViewPage;
public class AnsiConsolePageParticipant implements IConsolePageParticipant {
@Override
public Object getAdapter(Class adapter) {
return null;
}
@Override
public void activated() {}
@Override
public void deactivated() {}
@Override
public void dispose() {}
@Override
public void init(IPageBookViewPage page, IConsole console) {
if (page.getControl() instanceof StyledText) {
StyledText viewer = (StyledText) page.getControl();
viewer.addLineStyleListener(new AnsiConsoleStyleListener());
}
}
}
| 7,687 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/ansi/AnsiCommands.java | /**
* 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://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License 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.core.ansi;
//From Wikipedia, http://en.wikipedia.org/wiki/ANSI_escape_code
public class AnsiCommands {
public static final int COMMAND_ATTR_RESET = 0; // Reset / Normal (all attributes off)
public static final int COMMAND_ATTR_INTENSITY_BRIGHT = 1; // Bright (increased intensity) or Bold
public static final int COMMAND_ATTR_INTENSITY_FAINT = 2; // Faint (decreased intensity) (not widely supported)
public static final int COMMAND_ATTR_ITALIC = 3; // Italic: on not widely supported. Sometimes treated as inverse.
public static final int COMMAND_ATTR_UNDERLINE = 4; // Underline: Single
public static final int COMMAND_ATTR_BLINK_SLOW = 5; // Blink: Slow (less than 150 per minute)
public static final int COMMAND_ATTR_BLINK_FAST = 6; // Blink: Rapid (MS-DOS ANSI.SYS; 150 per minute or more; not widely supported)
public static final int COMMAND_ATTR_NEGATIVE_ON = 7; // Image: Negative (inverse or reverse; swap foreground and background)
public static final int COMMAND_ATTR_CONCEAL_ON = 8; // Conceal (not widely supported)
public static final int COMMAND_ATTR_CROSSOUT_ON = 9; // Crossed-out (Characters legible, but marked for deletion. Not widely supported.)
public static final int COMMAND_ATTR_UNDERLINE_DOUBLE = 21; // Bright/Bold: off or Underline: Double (bold off not widely supported, double underline hardly ever)
public static final int COMMAND_ATTR_INTENSITY_NORMAL = 22; // Normal color or intensity (neither bright, bold nor faint)
public static final int COMMAND_ATTR_ITALIC_OFF = 23; // Not italic, not Fraktur
public static final int COMMAND_ATTR_UNDERLINE_OFF = 24; // Underline: None (not singly or doubly underlined)
public static final int COMMAND_ATTR_BLINK_OFF = 25; // Blink: off
public static final int COMMAND_ATTR_NEGATIVE_OFF = 27; // Image: Positive
public static final int COMMAND_ATTR_CONCEAL_OFF = 28; // Reveal (conceal off)
public static final int COMMAND_ATTR_CROSSOUT_OFF = 29; // Not crossed out
// Extended colors. Next arguments are 5;<index_0_255> or 2;<red_0_255>;<green_0_255>;<blue_0_255>
public static final int COMMAND_HICOLOR_FOREGROUND = 38; // Set text color
public static final int COMMAND_HICOLOR_BACKGROUND = 48; // Set background color
public static final int COMMAND_COLOR_FOREGROUND_RESET = 39; // Default text color
public static final int COMMAND_COLOR_BACKGROUND_RESET = 49; // Default background color
public static final int COMMAND_COLOR_FOREGROUND_FIRST = 30; // First text color
public static final int COMMAND_COLOR_FOREGROUND_LAST = 37; // Last text color
public static final int COMMAND_COLOR_BACKGROUND_FIRST = 40; // First background text color
public static final int COMMAND_COLOR_BACKGROUND_LAST = 47; // Last background text color
public static final int COMMAND_ATTR_FRAMED_ON = 51; // Framed
public static final int COMMAND_ATTR_FRAMED_OFF = 54; // Not framed or encircled
public static final int COMMAND_HICOLOR_FOREGROUND_FIRST = 90; // First text color
public static final int COMMAND_HICOLOR_FOREGROUND_LAST = 97; // Last text color
public static final int COMMAND_HICOLOR_BACKGROUND_FIRST = 100; // First background text color
public static final int COMMAND_HICOLOR_BACKGROUND_LAST = 107; // Last background text color
public static final int COMMAND_COLOR_INTENSITY_DELTA = 8; // Last background text color
} | 7,688 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/plugin/AbstractAwsWizard.java | /*
* Copyright 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.eclipse.core.plugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.wizard.Wizard;
import com.amazonaws.eclipse.core.AwsToolkitCore;
/**
* Base class for all AWS Wizards. Subclasses should follow the pattern below to implement this class.
* <li> it must have a DataModel member and initialize the DataModel by implementing {@link #initDataModel()} method.
* <li> it must provide the Wizard Window Title
* <li> it must provide the Job Title.
*/
abstract class AbstractAwsWizard extends Wizard {
protected AbstractAwsWizard(String windowTitle) {
super();
setWindowTitle(windowTitle);
setDefaultPageImageDescriptor(
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
setNeedsProgressMonitor(true);
}
// The actual implementation for finishing the wizard.
protected abstract IStatus doFinish(IProgressMonitor monitor);
// Initialize data model either with default values or load data from PreferenceStore/Project Metadata.
// Subclasses should implement this method and call in an appropriate location, mostly at the end of Constructor.
protected abstract void initDataModel();
// The underlying Job Dialog title in the finish wizard.
protected abstract String getJobTitle();
protected void beforeExecution() {
// Subclass should implement this method if actions are needed before performing finish.
// Analytics goes here for recording the type of this action.
}
protected void afterExecution(IStatus status) {
// Subclass should implement this method if actions are needed after performing finish.
// Analytics goes here for recording whether the Wizard completion is problematic or not.
}
}
| 7,689 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/plugin/AbstractAwsPlugin.java | /*
* Copyright 2016 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.eclipse.core.plugin;
import java.util.Collections;
import java.util.Map;
import java.util.Map.Entry;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.statushandlers.StatusManager;
/**
* Abstract plugin that to be extended by AWS plugins. It defines common logics shared
* by all the AWS plugins such as logging and exception reporting.
*/
public abstract class AbstractAwsPlugin extends AbstractUIPlugin {
/**
* Returns the default plugin id defined in the manifest file.
*/
public String getPluginId() {
return getBundle().getSymbolicName();
}
/**
* Convenience method for logging a debug message at INFO level.
*/
public IStatus logInfo(String infoMessage) {
IStatus status = new Status(IStatus.INFO, getPluginId(), infoMessage, null);
getLog().log(status);
return status;
}
/**
* Convenience method for logging a warning message.
*/
public IStatus logWarning(String warningMessage, Throwable e) {
IStatus status = new Status(IStatus.WARNING, getPluginId(), warningMessage, e);
getLog().log(status);
return status;
}
/**
* Convenience method for logging an error message.
*/
public IStatus logError(String errorMessage, Throwable e) {
IStatus status = new Status(IStatus.ERROR, getPluginId(), errorMessage, e);
getLog().log(status);
return status;
}
/**
* Convenience method for reporting error to StatusManager.
*/
public IStatus reportException(String errorMessage, Throwable e) {
IStatus status = new Status(IStatus.ERROR, getPluginId(), errorMessage, e);
StatusManager.getManager().handle(
status, StatusManager.SHOW | StatusManager.LOG);
return status;
}
@Override
protected ImageRegistry createImageRegistry() {
ImageRegistry imageRegistry = super.createImageRegistry();
for (Entry<String, String> entry : getImageRegistryMap().entrySet()) {
imageRegistry.put(entry.getKey(), ImageDescriptor.createFromFile(getClass(), entry.getValue()));
}
return imageRegistry;
}
// Subclass plugin should override this method if their image registry is not empty.
protected Map<String, String> getImageRegistryMap() {
return Collections.emptyMap();
}
protected String getBundleVersion() {
return getBundle().getVersion().toString();
}
}
| 7,690 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/plugin/package-info.java | /*
* Copyright 2016 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.
*/
/**
* Collection of base classes that all the AWS plugins should extend for creating different
* components in one plugin.
*
*/
package com.amazonaws.eclipse.core.plugin; | 7,691 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/plugin/AbstractAwsProjectWizard.java | /*
* Copyright 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.eclipse.core.plugin;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
/**
* Base class for creating new project wizard.
*/
public abstract class AbstractAwsProjectWizard extends AbstractAwsWizard implements INewWizard {
protected IStructuredSelection selection;
protected IWorkbench workbench;
private long actionStartTimeMilli;
private long actionEndTimeMilli;
protected AbstractAwsProjectWizard(String windowTitle) {
super(windowTitle);
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
this.selection = selection;
this.workbench = workbench;
}
@Override
public final boolean performFinish() {
beforeExecution();
actionStartTimeMilli = System.currentTimeMillis();
IRunnableWithProgress runnable = new IRunnableWithProgress() {
@Override
public void run(IProgressMonitor monitor)
throws InvocationTargetException, InterruptedException {
new WorkspaceModifyOperation() {
@Override
protected void execute(IProgressMonitor monitor) throws CoreException,
InvocationTargetException, InterruptedException {
IStatus status = doFinish(monitor);
actionEndTimeMilli = System.currentTimeMillis();
afterExecution(status);
if (status.getSeverity() == IStatus.ERROR) {
throw new InvocationTargetException(status.getException(), status.getMessage());
}
}
}.run(monitor);
}
};
IStatus status = Status.OK_STATUS;
try {
boolean fork = true;
boolean cancelable = true;
getContainer().run(fork, cancelable, runnable);
} catch (InterruptedException ex) {
status = Status.CANCEL_STATUS;
} catch (InvocationTargetException ex) {
Throwable exception = ex.getCause();
if (exception instanceof OperationCanceledException) {
status = Status.CANCEL_STATUS;
} else {
status = getPlugin().reportException(exception.getMessage(), exception);
}
}
return status.isOK();
}
protected long getActionExecutionTimeMillis() {
return actionEndTimeMilli - actionStartTimeMilli;
}
protected abstract AbstractAwsPlugin getPlugin();
}
| 7,692 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/plugin/AbstractAwsJobWizard.java | /*
* Copyright 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.eclipse.core.plugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.Job;
public abstract class AbstractAwsJobWizard extends AbstractAwsWizard {
protected AbstractAwsJobWizard(String windowTitle) {
super(windowTitle);
}
@Override
public final boolean performFinish() {
beforeExecution();
Job awsJob = new Job(getJobTitle()) {
@Override
protected IStatus run(IProgressMonitor monitor) {
IStatus status = doFinish(monitor);
afterExecution(status);
return status;
}
};
awsJob.setUser(true);
awsJob.schedule();
return true;
}
}
| 7,693 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/exceptions/AwsActionException.java | /*
* Copyright 2018 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.eclipse.core.exceptions;
/**
* Base exception for all AWS actions.
*/
public class AwsActionException extends RuntimeException {
private final String actionName;
public AwsActionException(String actionName, String errorMessage, Throwable e) {
super(errorMessage, e);
this.actionName = actionName;
}
public String getActionName() {
return actionName;
}
}
| 7,694 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AccountOptionalConfiguration.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.core.accounts;
import java.io.File;
/**
* Abstract class describing the interface for accessing configured AWS account
* preferences and provides hooks for notification of change events.
*/
public abstract class AccountOptionalConfiguration {
/**
* Returns the currently configured AWS user account ID.
*
* @return The currently configured AWS user account ID.
*/
public abstract String getUserId();
/**
* Sets the currently configured AWS user account ID.
*/
public abstract void setUserId(String userId);
/**
* Returns the currently configured EC2 private key file.
*
* @return The currently configured EC2 private key file.
*/
public abstract String getEc2PrivateKeyFile();
/**
* Sets the currently configured EC2 private key file.
*/
public abstract void setEc2PrivateKeyFile(String ec2PrivateKeyFile);
/**
* Returns the currently configured EC2 certificate file.
*
* @return The currently configured EC2 certificate file.
*/
public abstract String getEc2CertificateFile();
/**
* Sets the currently configured EC2 certificate file.
*/
public abstract void setEc2CertificateFile(String ec2CertificateFile);
/**
* Persist the optional configurations in the source where it was loaded,
* e.g. save the related preference store properties, or save output the
* information to an external file.
*/
public abstract void save();
/**
* Delete the optional configurations in the source where it was loaded.
*/
public abstract void delete();
/**
* Returns true if this class contains in-memory changes that are not saved
* yet.
*/
public abstract boolean isDirty();
/**
* Returns true if and only if the configured certificate and corresponding
* private key are valid. Currently that distinction is made by verifying
* that the referenced files exist.
*
* @return True if and only if the configured certificate and corresponding
* private key are valid.
*/
public boolean isCertificateValid() {
String certificateFile = getEc2CertificateFile();
String privateKeyFile = getEc2PrivateKeyFile();
if (certificateFile == null || certificateFile.length() == 0) return false;
if (privateKeyFile == null || privateKeyFile.length() == 0) return false;
return (new File(certificateFile).isFile() &&
new File(privateKeyFile).isFile());
}
}
| 7,695 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AwsPluginAccountManager.java | /*
* Copyright 2008-2014 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.core.accounts;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.apache.http.annotation.Contract;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.accounts.preferences.PluginPreferenceStoreAccountOptionalConfiguration;
import com.amazonaws.eclipse.core.accounts.profiles.SdkCredentialsFileMonitor;
import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesCredentialsConfiguration;
import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesFactory;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.eclipse.core.preferences.PreferencePropertyChangeListener;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage;
/**
* This class acts as a facade for all the account-related configurations for
* the plugin. Different feature components should use this class to query/set
* the current default account. It is also responsible to notify the registered
* listeners about the change of default account.
* <p>
* When requested to retrieve a specific account info, this class delegates to a
* list of AccountInfoProvider implementations to aggregate all the accounts
* configured via different ways (e.g. by the Eclipse preference store system,
* or loaded from the local credentials file).
*/
@Contract (threading = org.apache.http.annotation.ThreadingBehavior.UNSAFE)
public final class AwsPluginAccountManager {
/**
* The preference store where the configuration for the global/regional
* default account is persisted..
*/
private final IPreferenceStore preferenceStore;
/** Monitors for changes of global/regional default account preference */
private DefaultAccountMonitor defaultAccountMonitor;
/** Monitors the configured location of the credentials file as specified in the preference store */
private final SdkCredentialsFileMonitor sdkCredentialsFileMonitor;
/**
* The AccountInfoProvider from which the manager retrieves the AccountInfo
* objects.
*/
private final AccountInfoProvider accountInfoProvider;
/**
* The AccountInfo object to return when no account is configured and the
* toolkit is unable to bootstrap the credentials file.
*/
private final AccountInfo tempAccount;
private boolean noAccountConfigured = false;
public AwsPluginAccountManager(IPreferenceStore preferenceStore,
AccountInfoProvider accountInfoProvider) {
this.preferenceStore = preferenceStore;
this.accountInfoProvider = accountInfoProvider;
this.sdkCredentialsFileMonitor = new SdkCredentialsFileMonitor();
String accountId = UUID.randomUUID().toString();
tempAccount = new AccountInfoImpl(accountId,
new SdkProfilesCredentialsConfiguration(preferenceStore, accountId,
SdkProfilesFactory.newEmptyBasicProfile("temp")),
new PluginPreferenceStoreAccountOptionalConfiguration(preferenceStore, accountId));
}
/**
* Start all the monitors on account-related preference properties.
*/
public void startAccountMonitors() {
if (defaultAccountMonitor == null) {
defaultAccountMonitor = new DefaultAccountMonitor();
getPreferenceStore().addPropertyChangeListener(
defaultAccountMonitor);
}
}
/**
* Stop all the monitors on account-related preference properties.
*/
public void stopAccountMonitors() {
if (defaultAccountMonitor != null) {
getPreferenceStore().removePropertyChangeListener(defaultAccountMonitor);
}
}
/**
* Start monitoring the location and content of the credentials file
*/
public void startCredentialsFileMonitor() {
sdkCredentialsFileMonitor.start(preferenceStore);
}
/**
* Returns the AccountInfoProvider that is used by this class.
*/
public AccountInfoProvider getAccountInfoProvider() {
return accountInfoProvider;
}
/**
* Returns the currently selected account info. If the current account id is
* not found in the loaded accounts (e.g. when the previously configured
* account is removed externally in the credentials file), this method falls
* back to returning the "default" profile account (or the first profile
* account if the "default" profile doesn't exist). If no account is
* configured in the toolkit (most probably because the toolkit failed to
* load the credentials file), this method returns a temporary empty
* AccountInfo object. In short, this method never returns null.
*
* @return The user's AWS account info.
*/
public AccountInfo getAccountInfo() {
if (noAccountConfigured) {
return tempAccount;
}
AccountInfo currentAccount = getAccountInfo(getCurrentAccountId());
if (currentAccount != null) {
return currentAccount;
}
// Find an existing account to fall back to
Collection<AccountInfo> allAccounts = getAllAccountInfo().values();
if ( !allAccounts.isEmpty() ) {
AwsToolkitCore.getDefault().logInfo("The current accountId is not found in the system. " +
"Switching to the default account.");
AccountInfo fallbackAccount = allAccounts.iterator().next();
// Find the "default" account
for (AccountInfo account : allAccounts) {
if (account.getAccountName().equals(PreferenceConstants.DEFAULT_ACCOUNT_NAME)) {
fallbackAccount = account;
}
}
setCurrentAccountId(fallbackAccount.getInternalAccountId());
return fallbackAccount;
}
AwsToolkitCore.getDefault().logInfo("No account could be found. " +
"Switching to a temporary account.");
// Directly return the temp AccountInfo object if no account could be found
noAccountConfigured = true;
return tempAccount;
}
/**
* Gets account info for the given account name. The query is performed by
* the AccountInfoProvider instance included in this manager. This method
* still checks for the legacy pref-store-based accounts if the account id
* cannot be found in the profile-based accounts.
*
* @param accountId
* The id of the account for which to get info.
*/
public AccountInfo getAccountInfo(String accountId) {
if (accountInfoProvider.getProfileAccountInfo(accountId) != null) {
return accountInfoProvider.getProfileAccountInfo(accountId);
}
if (accountInfoProvider.getLegacyPreferenceStoreAccountInfo(accountId) != null) {
return accountInfoProvider.getLegacyPreferenceStoreAccountInfo(accountId);
}
return null;
}
/**
* Refresh all the account info providers.
*/
public void reloadAccountInfo() {
noAccountConfigured = false;
final boolean noLegacyAccounts = accountInfoProvider.getAllLegacyPreferenceStoreAccontInfo().isEmpty();
// Only bootstrap the credentials file if no legacy account exists
final boolean boostrapCredentialsFile = noLegacyAccounts;
// Only show warning for the credentials file loading failure if no legacy account exists
final boolean showWarningOnFailure = noLegacyAccounts;
accountInfoProvider.refreshProfileAccountInfo(boostrapCredentialsFile, showWarningOnFailure);
}
/**
* Returns the current account Id
*/
public String getCurrentAccountId() {
return getPreferenceStore().getString(
PreferenceConstants.P_CURRENT_ACCOUNT);
}
/**
* Sets the current account id. No error checking is performed, so ensure
* the given account Id is valid.
*/
public void setCurrentAccountId(String accountId) {
getPreferenceStore().setValue(PreferenceConstants.P_CURRENT_ACCOUNT,
accountId);
}
/**
* Update the default account to use according to the current default
* region.
*/
public void updateCurrentAccount() {
updateCurrentAccount(RegionUtils.getCurrentRegion());
}
/**
* Set the given account identifier as the default account for a region. If
* this region does not have any default account setting (or setting is
* disabled), then this method will set it as the global default account.
*/
public void setDefaultAccountId(Region region, String accountId) {
if (AwsAccountPreferencePage.isRegionDefaultAccountEnabled(
getPreferenceStore(), region)) {
getPreferenceStore()
.setValue(
PreferenceConstants
.P_REGION_CURRENT_DEFAULT_ACCOUNT(region),
accountId);
} else {
getPreferenceStore().setValue(
PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT,
accountId);
}
}
/**
* Update the current accountId according to the given region.
*/
public void updateCurrentAccount(Region newRegion) {
if (AwsAccountPreferencePage.isRegionDefaultAccountEnabled(
getPreferenceStore(), newRegion)) {
AwsToolkitCore.getDefault().logInfo(
"Switching to region-specific default account for region "
+ newRegion.getId());
// Use the region-specific default account
setCurrentAccountId(getPreferenceStore().getString(
PreferenceConstants
.P_REGION_CURRENT_DEFAULT_ACCOUNT(newRegion)));
} else {
AwsToolkitCore.getDefault().logInfo(
"Switching to global default account");
// Use the global default account
setCurrentAccountId(getPreferenceStore().getString(
PreferenceConstants.P_GLOBAL_CURRENT_DEFAULT_ACCOUNT));
}
}
/**
* Returns a map of the names of all the accounts configured in the toolkit.
*/
public Map<String, String> getAllAccountNames() {
Map<String, AccountInfo> allAccountInfo = getAllAccountInfo();
if (allAccountInfo == null) {
return Collections.<String, String>emptyMap();
}
Map<String, String> allAccountNames = new LinkedHashMap<>();
for (Entry<String, AccountInfo> entry : allAccountInfo.entrySet()) {
allAccountNames.put(
entry.getKey(),
entry.getValue().getAccountName());
}
return allAccountNames;
}
/**
* Returns a map from profile names to account names in the toolkit.
*/
public Map<String, String> getAllAccountIds() {
Map<String, AccountInfo> allAccountInfo = getAllAccountInfo();
if (allAccountInfo == null) {
return Collections.<String, String>emptyMap();
}
Map<String, String> allAccountIds = new LinkedHashMap<>();
for (Entry<String, AccountInfo> entry : allAccountInfo.entrySet()) {
allAccountIds.put(
entry.getValue().getAccountName(),
entry.getKey()
);
}
return allAccountIds;
}
/**
* Returns a map of all the accounts configured in the toolkit. This method
* returns all the legacy pref-store-based accounts if none of the profile
* accounts could be found. This method returns an empty map when it failed
* to load accounts from the credentials file and no legacy account is
* configured.
*/
public Map<String, AccountInfo> getAllAccountInfo() {
Map<String, AccountInfo> accounts = accountInfoProvider.getAllProfileAccountInfo();
// If no profile account is found, fall back to the legacy accounts
if (accounts.isEmpty()) {
accounts = accountInfoProvider.getAllLegacyPreferenceStoreAccontInfo();
}
// If even legacy accounts cannot be found, bootstrap the credentials file
if (accounts.isEmpty()) {
AwsToolkitCore.getDefault().logInfo(
String.format("No account is configued in the toolkit. " +
"Bootstrapping the credentials file at (%s).",
preferenceStore.getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION)));
// boostrapCredentialsFile=true, showWarningOnFailure=false
accountInfoProvider.refreshProfileAccountInfo(true, false);
accounts = accountInfoProvider.getAllProfileAccountInfo();
}
return accounts;
}
/**
* Registers a listener to receive notifications when account info is
* changed.
*
* @param listener
* The listener to add.
*/
public void addAccountInfoChangeListener(
AccountInfoChangeListener listener) {
accountInfoProvider.addAccountInfoChangeListener(listener);
}
/**
* Stops a listener from receiving notifications when account info is
* changed.
*
* @param listener
* The listener to remove.
*/
public void removeAccountInfoChangeListener(
AccountInfoChangeListener listener) {
accountInfoProvider.removeAccountInfoChangeListener(listener);
}
/**
* Registers a listener to receive notifications when global/regional
* default accounts are changed.
*
* @param listener
* The listener to add.
*/
public void addDefaultAccountChangeListener(
PreferencePropertyChangeListener listener) {
defaultAccountMonitor.addChangeListener(listener);
}
/**
* Stops a listener from receiving notifications when global/regional
* default accounts are changed.
*
* @param listener
* The listener to remove.
*/
public void removeDefaultAccountChangeListener(
PreferencePropertyChangeListener listener) {
defaultAccountMonitor.removeChangeListener(listener);
}
private IPreferenceStore getPreferenceStore() {
return preferenceStore;
}
/**
* Returns whether there are valid aws accounts configured
*/
public boolean validAccountsConfigured() {
return getAccountInfo().isValid() || getAllAccountNames().size() > 1;
}
}
| 7,696 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AccountCredentialsConfiguration.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.core.accounts;
/**
* Abstract class describing the credentials information of a configured AWS
* account. The information includes the account name (or the profile name in
* case of profile-based accounts), the AWS access and secret keys and an
* optional session token.
*/
public abstract class AccountCredentialsConfiguration {
/**
* @return The UI-friendly name for this account.
*/
public abstract String getAccountName();
/**
* Sets the UI-friendly name for this account.
*
* @param accountName
* The UI-friendly name for this account.
*/
public abstract void setAccountName(String accountName);
/**
* @return The currently configured AWS user access key.
*/
public abstract String getAccessKey();
/**
* Sets the AWS Access Key ID for this account info object.
*
* @param accessKey The AWS Access Key ID.
*/
public abstract void setAccessKey(String accessKey);
/**
* @return The currently configured AWS secret key.
*/
public abstract String getSecretKey();
/**
* Sets the AWS Secret Access Key for this account info object.
*
* @param secretKey The AWS Secret Access Key.
*/
public abstract void setSecretKey(String secretKey);
/**
* @return true if the current account includes a session token
*/
public abstract boolean isUseSessionToken();
/**
* Sets whether the current account includes a session token
*
* @param useSessionToken
* true if the current account includes a session token
*/
public abstract void setUseSessionToken(boolean useSessionToken);
/**
* @return The currently configured AWS session token.
*/
public abstract String getSessionToken();
/**
* Sets the AWS session token for this account info object.
*
* @param sessionToken The AWS session token.
*/
public abstract void setSessionToken(String sessionToken);
/**
* Persist this account credentials information in the source where it was
* loaded, e.g. save the related preference store properties, or save output
* the information to an external file.
*/
public abstract void save();
/**
* Delete this account credentials information in the source where it was
* loaded.
*/
public abstract void delete();
/**
* Returns true if this class contains in-memory changes that are not saved
* yet.
*/
public abstract boolean isDirty();
/**
* Returns true if the configured account credentials appears to be valid,
* i.e. both the access key and the secret key are non-empty.
*/
public boolean isCredentialsValid() {
if (isEmpty(getAccessKey())) return false;
if (isEmpty(getSecretKey())) return false;
if (isUseSessionToken() && isEmpty(getSessionToken())) return false;
return true;
}
private boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
}
| 7,697 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AccountInfoProvider.java | /*
* Copyright 2010-2014 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.core.accounts;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfilesConfigFile;
import com.amazonaws.auth.profile.ProfilesConfigFileWriter;
import com.amazonaws.auth.profile.internal.BasicProfile;
import com.amazonaws.auth.profile.internal.Profile;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.accounts.preferences.PluginPreferenceStoreAccountCredentialsConfiguration;
import com.amazonaws.eclipse.core.accounts.preferences.PluginPreferenceStoreAccountOptionalConfiguration;
import com.amazonaws.eclipse.core.accounts.profiles.SdkProfilesCredentialsConfiguration;
import com.amazonaws.eclipse.core.preferences.PreferenceConstants;
import com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage;
import com.amazonaws.eclipse.core.util.FileUtils;
import com.amazonaws.util.StringUtils;
/**
* A class that loads and returns all the configured AccountInfo. It's
* also responsible for hooking the AccountInfoChangeListener.
*/
public class AccountInfoProvider {
private final IPreferenceStore prefStore;
/**
* Loading from the credentials file is an expensive operation, so we want
* to cache all the loaded AccountInfo objects.
*/
Map<String, AccountInfo> profileAccountInfoCache = new LinkedHashMap<>();
/** All the registered AccountInfoChangeListener */
List<AccountInfoChangeListener> listeners = new LinkedList<>();
/**
* Initialize the provider with the given preference store instance.
*/
public AccountInfoProvider(IPreferenceStore prefStore) {
this.prefStore = prefStore;
}
/**
* Returns all the account info that are loaded from the credential profiles
* file. For performance reason, this method won't attempt to reload the
* accounts upon each method call, therefore the returned result might be
* out of sync with the external source. Call the {@link #refresh()} method
* to forcefully reload all the account info.
*
* @return Map from the accountId to each of the profile-based AccountInfo
* object.
*/
public Map<String, AccountInfo> getAllProfileAccountInfo() {
return Collections.unmodifiableMap(profileAccountInfoCache);
}
/**
* Returns the profile account info by the account identifier.
*
* @see #getAllProfileAccountInfo()
*/
public AccountInfo getProfileAccountInfo(String accountId) {
return profileAccountInfoCache.get(accountId);
}
/**
* Loads and returns all the legacy account configuration from the
* preference store system. The identifiers of legacy accounts could be
* found in the following preference keys:
* (1) accountIds (ids of all the global accounts)
* (2) accountIds-region (e.g. "accountIds-cn-north-1", ids of all the regional accounts)
*
* @return Map from the accountId to each of the legacy AccountInfo
* object.
*/
public Map<String, AccountInfo> getAllLegacyPreferenceStoreAccontInfo() {
Map<String, AccountInfo> preferenceStoreAccounts = new LinkedHashMap<>();
// Global accounts
preferenceStoreAccounts.putAll(loadPreferenceStoreAccountsByRegion(null));
// Regional accounts
List<String> regionsWithDefaultAccount = AwsAccountPreferencePage
.getRegionsWithDefaultAccounts(prefStore);
for (String regionId : regionsWithDefaultAccount) {
preferenceStoreAccounts.putAll(loadPreferenceStoreAccountsByRegion(regionId));
}
return preferenceStoreAccounts;
}
/**
* Returns the legacy preference store account info by the account
* identifier.
*
* @see #getAllLegacyPreferenceStoreAccontInfo()
*/
public AccountInfo getLegacyPreferenceStoreAccountInfo(String accountId) {
return getAllLegacyPreferenceStoreAccontInfo().get(accountId);
}
/**
* Forces the provider to refresh all the profile AccountInfo it vends.
*
* @param boostrapCredentialsFile
* If set true, this method will create a credentials file with a
* default profile if no account is currently configured in the
* toolkit.
* @param showWarningOnFailure
* If true, this method will show a warning message box if it
* fails to load accounts.
*/
public synchronized void refreshProfileAccountInfo(final boolean boostrapCredentialsFile, final boolean showWarningOnFailure) {
reloadProfileAccountInfo(boostrapCredentialsFile, showWarningOnFailure);
// Notify the change listeners
for (AccountInfoChangeListener listener : listeners) {
listener.onAccountInfoChange();
}
}
/**
* Update the following preference value:
* (1) P_CREDENTIAL_PROFILE_ACCOUNT_IDS - ids of all the accounts that were loaded from credential profiles file.
* (2) accountId:P_CREDENTIAL_PROFILE_NAME - name of the credential profile
*
* This method needs to be called whenever we reload profile credentials.
*/
public void updateProfileAccountMetadataInPreferenceStore(Collection<AccountInfo> accounts) {
List<String> accountIds = new LinkedList<>();
for (AccountInfo accountInfo : accounts) {
accountIds.add(accountInfo.getInternalAccountId());
}
String accountIdsString = StringUtils.join(PreferenceConstants.ACCOUNT_ID_SEPARATOR,
accountIds.toArray(new String[accountIds.size()]));
prefStore.setValue(
PreferenceConstants.P_CREDENTIAL_PROFILE_ACCOUNT_IDS, accountIdsString);
for(AccountInfo profileAccount : accounts) {
String profileNamePrefKey = profileAccount.getInternalAccountId()
+ ":" + PreferenceConstants.P_CREDENTIAL_PROFILE_NAME;
prefStore.setValue(
profileNamePrefKey, profileAccount.getAccountName());
}
}
/**
* Register an AccountInfoChangeListener to this provider. All the
* registered listeners will be notified whenever this provider is
* refreshed.
*
* @param listener
* The new AccountInfoChangeListener to be registered.
*/
public void addAccountInfoChangeListener(AccountInfoChangeListener listener) {
synchronized(listeners) {
listeners.add(listener);
}
}
/**
* Remove an AccountInfoChangeListener from this provider.
*/
public void removeAccountInfoChangeListener(AccountInfoChangeListener listener) {
synchronized(listeners) {
listeners.remove(listener);
}
}
/* Profile-based account info */
private void reloadProfileAccountInfo(final boolean boostrapCredentialsFile, final boolean showWarningOnFailure) {
profileAccountInfoCache.clear();
/* Load the credential profiles file */
String credFileLocation = prefStore
.getString(PreferenceConstants.P_CREDENTIAL_PROFILE_FILE_LOCATION);
ProfilesConfigFile profileConfigFile = null;
try {
Path credFilePath = Paths.get(credFileLocation);
if (!Files.exists(credFilePath) && boostrapCredentialsFile) {
File credFile = FileUtils.createFileWithPermission600(credFileLocation);
// TODO We need to reconsider whether to dump an empty credentials profile when we cannot find one.
ProfilesConfigFileWriter.dumpToFile(
credFile,
true, // overwrite=true
new Profile(PreferenceConstants.DEFAULT_ACCOUNT_NAME, new BasicAWSCredentials("", "")));
}
profileConfigFile = new ProfilesConfigFile(credFilePath.toFile());
} catch (Exception e) {
String errorMsg = String.format("Failed to load credential profiles from (%s).",
credFileLocation);
AwsToolkitCore.getDefault().logInfo(errorMsg + e.getMessage());
if ( showWarningOnFailure ) {
MessageDialog.openError(null,
"Unable to load profile accounts",
errorMsg + " Please check that your credentials file is at the correct location "
+ "and that it is in the correct format.");
}
}
if (profileConfigFile == null) return;
/* Set up the AccountInfo objects */
// Map from profile name to its pre-configured account id
Map<String, String> exisitingProfileAccountIds = getExistingProfileAccountIds();
// Iterate through the newly loaded profiles. Re-use the existing
// account id if the profile name is already configured in the toolkit.
// Otherwise assign a new UUID for it.
for (Entry<String, BasicProfile> entry : profileConfigFile.getAllBasicProfiles().entrySet()) {
String profileName = entry.getKey();
BasicProfile basicProfile = entry.getValue();
String accountId = exisitingProfileAccountIds.get(profileName);
if (accountId == null) {
AwsToolkitCore.getDefault().logInfo("No profile found: " + profileName);
accountId = UUID.randomUUID().toString();
}
AccountInfo profileAccountInfo = new AccountInfoImpl(accountId,
new SdkProfilesCredentialsConfiguration(prefStore, accountId, basicProfile),
// Profile accounts use profileName as the preference name prefix
// @see PluginPreferenceStoreAccountOptionalConfiguration
new PluginPreferenceStoreAccountOptionalConfiguration(prefStore, profileName));
profileAccountInfoCache.put(accountId, profileAccountInfo);
}
/* Update the preference store metadata for the newly loaded profile accounts */
updateProfileAccountMetadataInPreferenceStore(profileAccountInfoCache.values());
}
/**
* The toolkit uses the "credentialProfileAccountIds" preference property to
* store the identifiers of all the profile-based accounts. This method
* checks this preference value and returns a map of all the existing
* profile accounts that are already configured in the toolkit.
*
* @return Key - profile name; Value - account id
*/
private Map<String, String> getExistingProfileAccountIds() {
Map<String, String> exisitingProfileAccounts = new HashMap<>();
// Ids of all the profile accounts currently configured in the toolkit
String[] profileAccountIds = prefStore.getString(
PreferenceConstants.P_CREDENTIAL_PROFILE_ACCOUNT_IDS).split(
PreferenceConstants.ACCOUNT_ID_SEPARATOR_REGEX);
for (String accountId : profileAccountIds) {
String configuredProfileName = prefStore.getString(
accountId + ":" + PreferenceConstants.P_CREDENTIAL_PROFILE_NAME);
if (configuredProfileName != null && !configuredProfileName.isEmpty()) {
exisitingProfileAccounts.put(configuredProfileName, accountId);
}
}
return exisitingProfileAccounts;
}
/* Pref-store-based account info */
/**
* Returns a map of all the preference-store-based account info.
*
* @param region
* Null value indicates the global region
*/
@SuppressWarnings("deprecation")
private Map<String, AccountInfo> loadPreferenceStoreAccountsByRegion(String regionId) {
String p_regionalAccountIds = regionId == null ?
PreferenceConstants.P_ACCOUNT_IDS
:
PreferenceConstants.P_ACCOUNT_IDS + "-" + regionId;
String[] accountIds = prefStore.getString(p_regionalAccountIds)
.split(PreferenceConstants.ACCOUNT_ID_SEPARATOR_REGEX);
Map<String, AccountInfo> accounts = new LinkedHashMap<>();
for ( String accountId : accountIds ) {
if (accountId.length() > 0) {
// Both credential and optional configurations are preference-store-based
AccountInfo prefStoreAccountInfo = new AccountInfoImpl(accountId,
new PluginPreferenceStoreAccountCredentialsConfiguration(prefStore, accountId),
new PluginPreferenceStoreAccountOptionalConfiguration(prefStore, accountId));
accounts.put(accountId, prefStoreAccountInfo);
}
}
return accounts;
}
}
| 7,698 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.core/src/com/amazonaws/eclipse/core/accounts/AccountInfoImpl.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.core.accounts;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import com.amazonaws.eclipse.core.AccountInfo;
/**
* A Java-bean compliant implementation of the AccountInfo interface. This class
* consists of two main components - AccountCredentialsConfiguration and
* AccountOptionalConfiguration. These two components are independent and might
* use different source to read and persist the configurations.
*/
public class AccountInfoImpl implements AccountInfo {
private transient PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
this);
/**
* The internal account identifier associated with this account.
*/
private final String accountId;
/**
* Config information related to the security credentials for this account.
*/
private final AccountCredentialsConfiguration credentialsConfig;
/**
* All the optional configuration for this account.
*/
private final AccountOptionalConfiguration optionalConfig;
public AccountInfoImpl(
final String accountId,
final AccountCredentialsConfiguration credentialsConfig,
final AccountOptionalConfiguration optionalConfig) {
if (accountId == null)
throw new IllegalArgumentException("accountId must not be null.");
if (credentialsConfig == null)
throw new IllegalArgumentException("credentialsConfig must not be null.");
if (optionalConfig == null)
throw new IllegalArgumentException("optionalConfig must not be null.");
this.accountId = accountId;
this.credentialsConfig = credentialsConfig;
this.optionalConfig = optionalConfig;
}
/**
* {@inheritDoc}
*/
@Override
public String getInternalAccountId() {
return accountId;
}
/**
* {@inheritDoc}
*/
@Override
public String getAccountName() {
return credentialsConfig.getAccountName();
}
/**
* {@inheritDoc}
*/
@Override
public void setAccountName(String accountName) {
String oldValue = getAccountName();
if ( !isEqual(oldValue, accountName) ) {
credentialsConfig.setAccountName(accountName);
firePropertyChange("accountName", oldValue, accountName);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getAccessKey() {
return credentialsConfig.getAccessKey();
}
/**
* {@inheritDoc}
*/
@Override
public void setAccessKey(String accessKey) {
String oldValue = getAccessKey();
if ( !isEqual(oldValue, accessKey) ) {
credentialsConfig.setAccessKey(accessKey);
firePropertyChange("accessKey", oldValue, accessKey);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getSecretKey() {
return credentialsConfig.getSecretKey();
}
/**
* {@inheritDoc}
*/
@Override
public void setSecretKey(String secretKey) {
String oldValue = getSecretKey();
if ( !isEqual(oldValue, secretKey) ) {
credentialsConfig.setSecretKey(secretKey);
firePropertyChange("secretKey", oldValue, secretKey);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isUseSessionToken() {
return credentialsConfig.isUseSessionToken();
}
/**
* {@inheritDoc}
*/
@Override
public void setUseSessionToken(boolean useSessionToken) {
boolean oldValue = isUseSessionToken();
if ( oldValue != useSessionToken ) {
credentialsConfig.setUseSessionToken(useSessionToken);
firePropertyChange("useSessionToken", oldValue, useSessionToken);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getSessionToken() {
return credentialsConfig.getSessionToken();
}
/**
* {@inheritDoc}
*/
@Override
public void setSessionToken(String sessionToken) {
String oldValue = getSessionToken();
if ( !isEqual(oldValue, sessionToken) ) {
credentialsConfig.setSessionToken(sessionToken);
firePropertyChange("sessionToken", oldValue, sessionToken);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getUserId() {
return optionalConfig.getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public void setUserId(String userId) {
String oldValue = getUserId();
if ( !isEqual(oldValue, userId) ) {
optionalConfig.setUserId(userId);
firePropertyChange("userId", oldValue, userId);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getEc2PrivateKeyFile() {
return optionalConfig.getEc2PrivateKeyFile();
}
/**
* {@inheritDoc}
*/
@Override
public void setEc2PrivateKeyFile(String ec2PrivateKeyFile) {
String oldValue = getEc2PrivateKeyFile();
if ( !isEqual(oldValue, ec2PrivateKeyFile) ) {
optionalConfig.setEc2PrivateKeyFile(ec2PrivateKeyFile);
firePropertyChange("ec2PrivateKeyFile", oldValue, ec2PrivateKeyFile);
}
}
/**
* {@inheritDoc}
*/
@Override
public String getEc2CertificateFile() {
return optionalConfig.getEc2CertificateFile();
}
/**
* {@inheritDoc}
*/
@Override
public void setEc2CertificateFile(String ec2CertificateFile) {
String oldValue = getEc2CertificateFile();
if ( !isEqual(oldValue, ec2CertificateFile) ) {
optionalConfig.setEc2CertificateFile(ec2CertificateFile);
firePropertyChange("ec2CertificateFile", oldValue, ec2CertificateFile);
}
}
/**
* {@inheritDoc}
*/
@Override
public void save() {
credentialsConfig.save();
optionalConfig.save();
}
/**
* {@inheritDoc}
*/
@Override
public void delete() {
credentialsConfig.delete();
optionalConfig.delete();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDirty() {
return credentialsConfig.isDirty()
|| optionalConfig.isDirty();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isValid() {
return credentialsConfig.isCredentialsValid();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isCertificateValid() {
return optionalConfig.isCertificateValid();
}
/* Java Bean related interfaces */
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(propertyName,
listener);
}
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(propertyName,
listener);
}
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
propertyChangeSupport.firePropertyChange(propertyName, oldValue,
newValue);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(getAccountName());
sb.append("]: ");
sb.append("accessKey=");
sb.append(getAccessKey());
sb.append(", secretKey=");
sb.append(getSecretKey());
sb.append(", userId=");
sb.append(getUserId());
sb.append(", certFile=");
sb.append(getEc2CertificateFile());
sb.append(", privateKey=");
sb.append(getEc2PrivateKeyFile());
return sb.toString();
}
private static boolean isEqual(Object a, Object b) {
if (a == null || b == null) {
return a == null && b == null;
}
return a.equals(b);
}
}
| 7,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.