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.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EnvironmentConfigDataModel.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.elasticbeanstalk.server.ui.configEditor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.core.databinding.observable.Observables;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.observable.map.WritableMap;
import org.eclipse.core.databinding.observable.set.WritableSet;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.CancelableThread;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationOptionsRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeConfigurationOptionsResult;
/**
* Simple data model factory for environments.
*/
public class EnvironmentConfigDataModel {
private static final Map<Environment, EnvironmentConfigDataModel> models = new HashMap<>();
private final Environment environment;
private final IObservableMap dataModel;
private final Map<OptionKey, IObservableValue> sharedObservables;
private final List<RefreshListener> listeners;
private final List<ConfigurationOptionDescription> options;
private final IgnoredOptions ignoredOptions;
private CancelableThread refreshThread;
private EnvironmentConfigDataModel(Environment environment) {
this.environment = environment;
this.dataModel = new WritableMap();
this.sharedObservables = new HashMap<>();
this.listeners = new LinkedList<>();
this.options = new LinkedList<>();
this.ignoredOptions = IgnoredOptions.getDefault();
}
/**
* Returns a data model for the environment given.
*/
public static synchronized EnvironmentConfigDataModel getInstance(Environment environment) {
if ( !models.containsKey(environment) ) {
models.put(environment, new EnvironmentConfigDataModel(environment));
}
return models.get(environment);
}
/**
* Returns the raw model, which is a typeless map. It's not generally safe
* to observe this map further.
*
* @see EnvironmentConfigDataModel#observeEntry(ConfigurationOptionDescription)
*/
public IObservableMap getDataModel() {
return dataModel;
}
/**
* Observes the entry described by the key given. This must be used, rather
* than observing the map entries directly, to ensure proper sharing of
* observables.
*/
public synchronized IObservableValue observeEntry(ConfigurationOptionDescription key) {
OptionKey optionKey = getKey(key);
if ( !sharedObservables.containsKey(optionKey) ) {
IObservableValue observable = Observables.observeMapEntry(dataModel, optionKey);
sharedObservables.put(optionKey, observable);
}
return sharedObservables.get(optionKey);
}
/**
* Returns the data model entry corresponding to the given key.
*/
public synchronized Object getEntry(ConfigurationOptionDescription key) {
return dataModel.get(getKey(key));
}
/**
* Initializes the model given with the values provided, overwriting any
* previous values.
*/
public synchronized void init(final Map<String, List<ConfigurationOptionSetting>> settings,
final List<ConfigurationOptionDescription> options) {
this.options.clear();
this.options.addAll(options);
/*
*TODO : There is a potential bug here. We should clear the all the contents in the dataModel first.
* But it will make the editor dirty immediately. Hope in the future we can find a better way
* to mark the edittor dirty.
*
*/
for ( ConfigurationOptionDescription opt : options ) {
if (!ignoredOptions.isNamespaceIgnored(opt.getNamespace())) {
List<ConfigurationOptionSetting> settingsInNamespace = settings.get(opt.getNamespace());
if ( settingsInNamespace != null ) {
for ( ConfigurationOptionSetting setting : settingsInNamespace ) {
if ( opt.getName().equals(setting.getOptionName()) ) {
String valueType = opt.getValueType();
OptionKey key = getKey(opt);
if ( valueType.equals("Scalar") ) {
dataModel.put(key, setting.getValue());
} else if ( valueType.equals("Boolean") ) {
if (setting.getValue() != null) {
dataModel.put(key, Boolean.valueOf(setting.getValue()));
}
} else if ( valueType.equals("List") ) {
if ( !dataModel.containsKey(key) ) {
dataModel.put(key, new WritableSet());
}
synchronizeSets(setting, key);
} else if ( valueType.equals("CommaSeparatedList") ) {
dataModel.put(key, setting.getValue());
} else if ( valueType.equals("KeyValueList") ) {
dataModel.put(key, setting.getValue());
}
}
}
}
}
}
}
/**
* Register a listener for refresh events.
*/
public synchronized void addRefreshListener(RefreshListener listener) {
listeners.add(listener);
}
/**
* Removes the given listener.
*/
public synchronized void removeRefreshListener(RefreshListener listener) {
listeners.remove(listener);
}
/**
* Asynchronously refreshes the model with services calls. To be notified of
* refresh lifecycle events, register a listener.
*
* @param templateName
* If non-null, will initialize using the values in the template
* named, rather than the environment's running settings.
*/
public synchronized void refresh(String templateName) {
cancelThread(refreshThread);
refreshThread = new RefreshThread(templateName);
refreshThread.start();
}
public List<ConfigurationOptionDescription> getOptions() {
return options;
}
/**
* Synchronizes the two sets given in such as a way as to not provoke a set
* changed event if their contents are equal.
*/
void synchronizeSets(ConfigurationOptionSetting setting, OptionKey key) {
Set<String> settingValues = new HashSet<>();
@SuppressWarnings("unchecked")
Collection<String> modelValues = ((Collection<String>) dataModel.get(key));
/*
* Sets a and b are equivalent iff for each element e in set a,
* b.contains(e) and vice versa
*/
boolean setsEquivalent = true;
String value = setting.getValue();
if ( value != null ) {
for ( String v : value.split(",") ) {
settingValues.add(v);
if ( !modelValues.contains(v) ) {
setsEquivalent = false;
}
}
}
for ( String v : modelValues ) {
if ( !settingValues.contains(v) )
setsEquivalent = false;
}
if ( !setsEquivalent ) {
modelValues.clear();
modelValues.addAll(settingValues);
}
}
/**
* Returns the current settings for this environment.
*
* @param templateName
* If not null, get the settings for the template named, rather
* than the running environment.
*/
public Map<String, List<ConfigurationOptionSetting>> getCurrentSettings(String templateName) {
Map<String, List<ConfigurationOptionSetting>> settings;
if ( templateName == null )
settings = getEnvironmentConfiguration(environment.getEnvironmentName());
else
settings = getTemplateConfiguration(templateName);
return settings;
}
/**
* Returns a list of configuration options sorted first by namespace, then
* by option name.
*/
public List<ConfigurationOptionDescription> getSortedConfigurationOptions() {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
DescribeConfigurationOptionsResult optionsDesc = null;
try {
optionsDesc = client.describeConfigurationOptions(new DescribeConfigurationOptionsRequest()
.withEnvironmentName(environment.getEnvironmentName()));
} catch (AmazonServiceException e) {
if ( "InvalidParameterValue".equals(e.getErrorCode()) ) {
// If the environment doesn't exist yet...
return new ArrayList<>();
} else {
throw e;
}
}
List<ConfigurationOptionDescription> options = new ArrayList<>();
for ( ConfigurationOptionDescription desc : optionsDesc.getOptions() ) {
if (!ignoredOptions.isOptionIgnored(desc.getNamespace(), desc.getName())) {
options.add(desc);
}
}
Collections.sort(options, new Comparator<ConfigurationOptionDescription>() {
@Override
public int compare(ConfigurationOptionDescription o1, ConfigurationOptionDescription o2) {
if ( o1.getNamespace().equals(o2.getNamespace()) ) {
return o1.getName().compareTo(o2.getName());
} else {
return o1.getNamespace().compareTo(o2.getNamespace());
}
}
});
return options;
}
/**
* Returns map of configuration option settings for an environment keyed by
* their namespace.
*/
public Map<String, List<ConfigurationOptionSetting>> getEnvironmentConfiguration(String environmentName) {
try {
List<ConfigurationSettingsDescription> settings = environment.getCurrentSettings();
if ( settings.isEmpty() ) return null;
return createSettingsMap(settings);
} catch (AmazonServiceException ase) {
if (ase.getErrorCode().equals("InvalidParameterValue")) return null;
else throw ase;
}
}
/**
* Returns map of configuration option settings for a template keyed by
* their namespace.
*/
public Map<String, List<ConfigurationOptionSetting>> getTemplateConfiguration(String templateName) {
List<ConfigurationSettingsDescription> settings = environment.getCurrentSettings();
if ( settings.isEmpty() )
return null;
return createSettingsMap(settings);
}
/**
* Sorts the list of settings given into a map keyed by namespace.
*/
public Map<String, List<ConfigurationOptionSetting>> createSettingsMap(List<ConfigurationSettingsDescription> settings) {
Map<String, List<ConfigurationOptionSetting>> options = new HashMap<>();
for ( ConfigurationOptionSetting opt : settings.get(0).getOptionSettings() ) {
if ( !options.containsKey(opt.getNamespace()) ) {
options.put(opt.getNamespace(), new ArrayList<ConfigurationOptionSetting>());
}
options.get(opt.getNamespace()).add(opt);
}
return options;
}
/**
* Transforms the model into a list of configuration option settings.
*/
public Collection<ConfigurationOptionSetting> createConfigurationOptions() {
Collection<ConfigurationOptionSetting> settings = new ArrayList<>();
for ( Object key : dataModel.keySet() ) {
OptionKey option = (OptionKey) key;
Object value = dataModel.get(key);
if ( value != null ) {
if ( value instanceof Collection ) {
@SuppressWarnings("rawtypes")
Collection collection = (Collection) value;
if ( !collection.isEmpty() ) {
ConfigurationOptionSetting setting = new ConfigurationOptionSetting()
.withNamespace(option.namespace).withOptionName(option.name)
.withValue(join(collection));
settings.add(setting);
}
} else {
ConfigurationOptionSetting setting = new ConfigurationOptionSetting()
.withNamespace(option.namespace).withOptionName(option.name).withValue(value.toString());
settings.add(setting);
}
}
}
return settings;
}
/**
* Joins the collection given with commas.
*/
@SuppressWarnings("rawtypes")
private String join(Collection list) {
StringBuilder b = new StringBuilder();
boolean seenOne = false;
for ( Object o : list ) {
if ( seenOne )
b.append(",");
else
seenOne = true;
b.append(o);
}
return b.toString();
}
private OptionKey getKey(ConfigurationOptionDescription key) {
return new OptionKey(key);
}
/**
* Cancels the thread given if it's running.
*/
protected void cancelThread(CancelableThread thread) {
if ( thread != null ) {
synchronized (thread) {
if ( thread.isRunning() ) {
thread.cancel();
}
}
}
}
private final class RefreshThread extends CancelableThread {
private String template;
public RefreshThread(String template) {
this.template = template;
}
@Override
public void run() {
try {
for ( RefreshListener listener : listeners ) {
listener.refreshStarted();
}
final List<ConfigurationOptionDescription> options = getSortedConfigurationOptions();
final Map<String, List<ConfigurationOptionSetting>> settings = getCurrentSettings(template);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
synchronized (RefreshThread.this) {
if ( !isCanceled() )
init(settings, options);
}
}
});
} catch ( Exception e ) {
for ( RefreshListener listener : listeners ) {
listener.refreshError(e);
}
return;
}
for ( RefreshListener listener : listeners ) {
listener.refreshFinished();
}
}
}
/**
* We can't use the SDK's data types as map keys because they don't .equals
* one another. This is a lightweight adapter to allow them to be used as
* such, as well as being reversible to an option name.
*/
public static final class OptionKey {
private final String name;
private final String namespace;
public OptionKey(ConfigurationOptionDescription opt) {
this.name = opt.getName();
this.namespace = opt.getNamespace();
}
@Override
public boolean equals(Object o2) {
if ( o2 instanceof OptionKey == false )
return false;
return ((OptionKey) o2).name.equals(this.name) && ((OptionKey) o2).namespace.equals(this.namespace);
}
@Override
public int hashCode() {
return name.hashCode() + namespace.hashCode();
}
@Override
public String toString() {
return namespace + ":" + name;
}
}
/**
* Container for ignored namespaces and options
*/
public static class IgnoredOptions {
static final String IGNORE_ALL_OPTIONS = "aws:eclipse:toolkit:IGNORE_ALL_OPTIONS_IN_NAMESPACE";
private final Map<String, List<String>> ignoredOptions;
public static IgnoredOptions getDefault() {
IgnoredOptions options = new IgnoredOptions(new HashMap<String, List<String>>());
options.ignoreNamespace("aws:cloudformation:template:parameter");
options.ignoreNamespace("aws:ec2:vpc");
options.ignoreOption(ConfigurationOptionConstants.HEALTH_REPORTING_SYSTEM, "ConfigDocument");
return options;
}
public IgnoredOptions(Map<String, List<String>> ignoredOptions) {
this.ignoredOptions = ignoredOptions;
}
public boolean isOptionIgnored(String namespace, String optionName) {
return isNamespaceIgnored(namespace) || containsOption(namespace, optionName);
}
public boolean isNamespaceIgnored(String namespace) {
return containsOption(namespace, IGNORE_ALL_OPTIONS);
}
private boolean containsOption(String namespace, String option) {
if (!ignoredOptions.containsKey(namespace)) {
return false;
}
return ignoredOptions.get(namespace).contains(option);
}
void ignoreOption(String namespace, String optionName) {
if (ignoredOptions.get(namespace) == null) {
ignoredOptions.put(namespace, new LinkedList<String>());
}
ignoredOptions.get(namespace).add(optionName);
}
void ignoreNamespace(String namespace) {
ignoreOption(namespace, IGNORE_ALL_OPTIONS);
}
}
}
| 7,400 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/NullOperation.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.server.ui.configEditor;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.operations.AbstractOperation;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/**
* Simply calling firePropertyChange(IEditorPart.PROP_DIRTY) won't mark the
* editor as dirty. This is because ServerEditor (which is our EditorSite)
* doesn't defer to its pages to determine dirty status, but just asks the
* global command manager. We have to execute() this stub to achieve the
* desired effect. It doesn't do anything.
*/
final class NullOperation extends AbstractOperation {
public NullOperation() {
super("");
}
@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
return Status.OK_STATUS;
}
@Override
public IStatus redo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
return Status.OK_STATUS;
}
@Override
public IStatus undo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
return Status.OK_STATUS;
}
@Override
public boolean canRedo() {
return false;
}
@Override
public boolean canUndo() {
return false;
}
@Override
public boolean canExecute() {
return false;
}
}
| 7,401 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/LogTailEditorSection.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.elasticbeanstalk.server.ui.configEditor;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.wst.server.ui.editor.ServerEditorSection;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.AwsToolkitHttpClient;
import com.amazonaws.eclipse.core.HttpClientFactory;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentInfoDescription;
import com.amazonaws.services.elasticbeanstalk.model.RequestEnvironmentInfoRequest;
import com.amazonaws.services.elasticbeanstalk.model.RetrieveEnvironmentInfoRequest;
import com.amazonaws.services.elasticbeanstalk.model.RetrieveEnvironmentInfoResult;
public class LogTailEditorSection extends ServerEditorSection {
/** The section widget we're managing */
private Section section;
private FormToolkit toolkit;
private Text log;
private static final Object JOB_FAMILY = new Object();
@Override
public void createSection(Composite parent) {
super.createSection(parent);
toolkit = getFormToolkit(parent.getDisplay());
section = toolkit.createSection(parent,
Section.TITLE_BAR | Section.DESCRIPTION );
section.setText("Environment Log");
section.setDescription("Aggregate logs of your Elastic Beanstalk environment");
Composite composite = toolkit.createComposite(section);
FillLayout layout = new FillLayout();
layout.marginHeight = 10;
layout.marginWidth = 10;
layout.type = SWT.VERTICAL;
composite.setLayout(layout);
toolkit.paintBordersFor(composite);
section.setClient(composite);
section.setLayout(layout);
createLogViewer(composite);
refresh();
}
/**
* @param composite
*/
private void createLogViewer(Composite composite) {
log = new Text(composite, SWT.READ_ONLY | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
}
private class LoadEnvironmentLogJob extends Job {
private final Environment environment;
public LoadEnvironmentLogJob(Environment environment) {
super("Loading log for environment " + environment.getEnvironmentName());
this.environment = environment;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
AWSElasticBeanstalk elasticBeanstalk = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
try {
elasticBeanstalk.requestEnvironmentInfo(new RequestEnvironmentInfoRequest().withEnvironmentName(
environment.getEnvironmentName()).withInfoType("tail"));
} catch (AmazonServiceException ase) {
if (ase.getErrorCode().equals("InvalidParameterValue")) {
return Status.OK_STATUS;
} else {
throw ase;
}
}
RetrieveEnvironmentInfoResult infoResult;
long pollingStartTime = System.currentTimeMillis();
while (true) {
infoResult = elasticBeanstalk.retrieveEnvironmentInfo(
new RetrieveEnvironmentInfoRequest()
.withInfoType("tail")
.withEnvironmentName(environment.getEnvironmentName()));
// Break once we find environment info
if (infoResult.getEnvironmentInfo().size() > 0) {
break;
}
// Or if we don't see any env info after waiting a while
if (System.currentTimeMillis() - pollingStartTime > 1000*60*5) {
break;
}
// Otherwise, keep polling
try {Thread.sleep(1000 * 5);}
catch (InterruptedException e) { return Status.CANCEL_STATUS; }
}
final List<EnvironmentInfoDescription> envInfos = infoResult.getEnvironmentInfo();
AwsToolkitHttpClient client = HttpClientFactory.create(ElasticBeanstalkPlugin.getDefault(), "https://s3.amazonaws.com");
// For each instance, there are potentially multiple tail samples.
// We just display the last one for each instance.
Map<String, EnvironmentInfoDescription> tails = new HashMap<>();
for (EnvironmentInfoDescription envInfo : envInfos) {
if ( !tails.containsKey(envInfo.getEc2InstanceId())
|| tails.get(envInfo.getEc2InstanceId()).getSampleTimestamp()
.before(envInfo.getSampleTimestamp()) ) {
tails.put(envInfo.getEc2InstanceId(), envInfo);
}
}
List<String> instanceIds = new ArrayList<>();
instanceIds.addAll(tails.keySet());
Collections.sort(instanceIds);
// Print the id and the log for each instance
final StringBuilder builder = new StringBuilder();
for ( String instanceId : instanceIds ) {
builder.append("Log for ").append(instanceId).append(":").append("\n\n");
EnvironmentInfoDescription envInfo = tails.get(instanceId);
try {
// The message is a url to fetch for logs
InputStream content = client.getEntityContent(envInfo.getMessage());
if (content != null) {
builder.append(IOUtils.toString(content));
}
} catch ( Exception e ) {
builder.append("Exception fetching " + envInfo.getMessage());
}
}
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
log.setText(builder.toString());
}
});
return Status.OK_STATUS;
}
@Override
public boolean belongsTo(Object family) {
return family == JOB_FAMILY;
}
}
/**
* Refreshes the log.
*/
void refresh() {
/*
* There's a race condition here, but the consequences are trivial.
*/
if ( Job.getJobManager().find(JOB_FAMILY).length == 0 ) {
Environment environment = (Environment) server.loadAdapter(Environment.class, null);
new LoadEnvironmentLogJob(environment).schedule();
}
}
}
| 7,402 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/ImportTemplateDialog.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.elasticbeanstalk.server.ui.configEditor;
import java.util.Collection;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* Dialog to prompt the user to select a template to import into their editor.
*/
public class ImportTemplateDialog extends MessageDialog {
private String templateName;
private Collection<String> existingTemplateNames;
public String getTemplateName() {
return templateName;
}
public ImportTemplateDialog(Shell parentShell, Collection<String> existingTemplateNames) {
super(parentShell, "Import configuration template", null,
"Choose the configuration template to import into the editor. "
+ "This will overwrite any unsaved values in the editor.", MessageDialog.NONE, new String[] {
IDialogConstants.OK_LABEL, IDialogConstants.CANCEL_LABEL }, 0);
this.existingTemplateNames = existingTemplateNames;
}
@Override
protected Control createCustomArea(Composite parent) {
parent.setLayout(new FillLayout());
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout(2, false));
new Label(composite, SWT.None).setText("Template to import: ");
final Combo existingTemplateNamesCombo = new Combo(composite, SWT.READ_ONLY);
existingTemplateNamesCombo.setItems(existingTemplateNames.toArray(new String[existingTemplateNames.size()]));
existingTemplateNamesCombo.select(0);
existingTemplateNamesCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
templateName = existingTemplateNamesCombo.getItem(existingTemplateNamesCombo.getSelectionIndex());
}
});
return composite;
}
}
| 7,403 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EnvironmentConfigEditorPart.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.elasticbeanstalk.server.ui.configEditor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.wst.server.ui.internal.ImageResource;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.jobs.ExportConfigurationJob;
import com.amazonaws.eclipse.elasticbeanstalk.jobs.UpdateEnvironmentConfigurationJob;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.basic.AdvancedEnvironmentTypeConfigEditorSection;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.ApplicationDescription;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationsRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeApplicationsResult;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentsRequest;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus;
import com.amazonaws.services.elasticbeanstalk.model.UpdateEnvironmentRequest;
import com.amazonaws.services.elasticbeanstalk.model.ValidateConfigurationSettingsRequest;
import com.amazonaws.services.elasticbeanstalk.model.ValidateConfigurationSettingsResult;
import com.amazonaws.services.elasticbeanstalk.model.ValidationMessage;
/**
* Advanced environment configuration editor part.
*/
@SuppressWarnings("restriction")
public class EnvironmentConfigEditorPart extends AbstractEnvironmentConfigEditorPart implements RefreshListener {
private AwsAction exportTemplateAction;
private AwsAction importTemplateAction;
private Composite leftColumnComp;
private Composite rightColumnComp;
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
model.addRefreshListener(this);
}
@Override
public void createPartControl(Composite parent) {
managedForm = new ManagedForm(parent);
setManagedForm(managedForm);
ScrolledForm form = managedForm.getForm();
FormToolkit toolkit = managedForm.getToolkit();
toolkit.decorateFormHeading(form.getForm());
form.setText("Environment Configuration");
form.setImage(ImageResource.getImage(ImageResource.IMG_SERVER));
form.getBody().setLayout(new GridLayout());
Composite columnComp = toolkit.createComposite(form.getBody());
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.horizontalSpacing = 10;
columnComp.setLayout(layout);
columnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Label restartNotice = toolkit.createLabel(columnComp, RESTART_NOTICE, SWT.WRAP);
GridData layoutData = new GridData(SWT.FILL, SWT.TOP, false, false);
layoutData.horizontalSpan = 2;
layoutData.widthHint = 600; // required for wrapping
restartNotice.setLayoutData(layoutData);
// left column
leftColumnComp = toolkit.createComposite(columnComp);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 0;
leftColumnComp.setLayout(layout);
leftColumnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
// right column
rightColumnComp = toolkit.createComposite(columnComp);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 0;
rightColumnComp.setLayout(layout);
rightColumnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
refreshAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR,
"Refresh", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh");
}
@Override
protected void doRun() {
refresh(null);
actionFinished();
}
};
managedForm.getForm().getToolBarManager().add(refreshAction);
exportTemplateAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_EXPORT_TEMPLATE,
"Export current values as template", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return ImageDescriptor.createFromFile(ElasticBeanstalkPlugin.class, "/icons/export.gif");
}
@Override
protected void doRun() {
exportAsTemplate();
actionFinished();
}
};
importTemplateAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_IMPORT_TEMPLATE,
"Import template values into editor", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return ImageDescriptor.createFromFile(ElasticBeanstalkPlugin.class, "/icons/import.gif");
}
@Override
protected void doRun() {
importTemplate();
actionFinished();
}
};
managedForm.getForm().getToolBarManager().add(importTemplateAction);
managedForm.getForm().getToolBarManager().add(exportTemplateAction);
managedForm.getForm().getToolBarManager().update(true);
managedForm.reflow(true);
refresh(null);
}
/**
* Imports a template's config settings into the editor.
*/
protected void importTemplate() {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
DescribeApplicationsResult result = client.describeApplications(new DescribeApplicationsRequest()
.withApplicationNames(environment.getApplicationName()));
final Collection<String> existingTemplateNames = new HashSet<>();
for ( ApplicationDescription app : result.getApplications() ) {
for ( String templateName : app.getConfigurationTemplates() ) {
existingTemplateNames.add(templateName);
}
}
final ImportTemplateDialog dialog = new ImportTemplateDialog(getSite().getShell(), existingTemplateNames);
dialog.open();
if ( dialog.getReturnCode() == MessageDialog.OK ) {
refresh(dialog.getTemplateName());
}
}
/**
* Refreshes the editor with the latest values
*/
@Override
public void refresh(String templateName) {
model.refresh(templateName);
}
/**
* Exports the current model as a template, prompting the user for a name.
*/
private void exportAsTemplate() {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
DescribeApplicationsResult result = client.describeApplications(new DescribeApplicationsRequest()
.withApplicationNames(environment.getApplicationName()));
final Collection<String> existingTemplateNames = new HashSet<>();
for ( ApplicationDescription app : result.getApplications() ) {
for ( String templateName : app.getConfigurationTemplates() ) {
existingTemplateNames.add(templateName);
}
}
final ExportTemplateDialog dialog = new ExportTemplateDialog(getSite().getShell(), existingTemplateNames,
"newTemplate" + System.currentTimeMillis());
dialog.open();
if ( dialog.getReturnCode() == MessageDialog.OK ) {
new ExportConfigurationJob(environment, dialog.getTemplateName(), dialog.getTemplateDescription(), model.createConfigurationOptions(),
dialog.isCreatingNew()).schedule();
}
}
/**
* Creates and returns the appropriate sections for the configuration
* options given, one per namespace.
*/
private List<EnvironmentConfigEditorSection> createEditorSections(List<ConfigurationOptionDescription> options) {
List<EnvironmentConfigEditorSection> editorSections = new ArrayList<>();
Map<String, List<ConfigurationOptionDescription>> optionsByNamespace = new HashMap<>();
for ( ConfigurationOptionDescription o : options ) {
if ( !optionsByNamespace.containsKey(o.getNamespace()) ) {
ArrayList<ConfigurationOptionDescription> optionsInNamespace = new ArrayList<>();
optionsByNamespace.put(o.getNamespace(), optionsInNamespace);
// We use our customized environment type section
if (o.getNamespace().equals(ConfigurationOptionConstants.ENVIRONMENT_TYPE) && o.getName().equals("EnvironmentType")) {
editorSections.add(new AdvancedEnvironmentTypeConfigEditorSection(this, model, environment, bindingContext, o.getNamespace(),
optionsInNamespace));
} else {
editorSections.add(new EnvironmentConfigEditorSection(this, model, environment, bindingContext, o.getNamespace(), optionsInNamespace));
}
}
optionsByNamespace.get(o.getNamespace()).add(o);
}
return editorSections;
}
@Override
public void refreshStarted() {
/*
* Although we are likely already in the UI thread, not executing this
* in the context of the parent shell's UI thread leads to race
* conditions with the RefreshThread's own composite manipulation.
*/
getEditorSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
exportTemplateAction.setEnabled(false);
importTemplateAction.setEnabled(false);
managedForm.getForm().setText(getTitle() + " (loading...)");
}
});
}
@Override
public void refreshFinished() {
getEditorSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
// Every time we redraw the layouts.
destroyOldLayouts();
final List<EnvironmentConfigEditorSection> editorSections = createEditorSections(model.getOptions());
int numLeft = 0;
int numRight = 0;
for (EnvironmentConfigEditorSection section : editorSections) {
section.setServerEditorPart(EnvironmentConfigEditorPart.this);
section.init(getEditorSite(), getEditorInput());
if (numLeft <= numRight) {
section.createSection(leftColumnComp);
numLeft += section.getNumControls();
} else {
section.createSection(rightColumnComp);
numRight += section.getNumControls();
}
managedForm.reflow(true);
}
managedForm.getForm().setText(getTitle());
exportTemplateAction.setEnabled(true);
importTemplateAction.setEnabled(true);
}
});
}
@Override
public void refreshError(Throwable e) {
ElasticBeanstalkPlugin.getDefault().getLog().log(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Error creating editor", e));
}
/**
* Called on every editor part by the parent multi-page editor when the user
* saves. An OK status means a save can take place; an error results in a
* pop-up error dialog.
*/
@Override
public IStatus[] getSaveStatus() {
if ( !isDirty() )
return new IStatus[] { Status.OK_STATUS };
// Don't allow a save unless the form has no errors
Object aggregateFormStatus = aggregateValidationStatus.getValue();
if ( aggregateFormStatus instanceof IStatus == false )
return new IStatus[] { Status.OK_STATUS };
else if ( ((IStatus) aggregateFormStatus).getSeverity() == IStatus.ERROR ) {
return new IStatus[] { (IStatus) aggregateFormStatus };
}
try {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
ValidateConfigurationSettingsResult validation = client
.validateConfigurationSettings(new ValidateConfigurationSettingsRequest()
.withApplicationName(environment.getApplicationName())
.withEnvironmentName(environment.getEnvironmentName())
.withOptionSettings(model.createConfigurationOptions()));
for ( ValidationMessage status : validation.getMessages() ) {
if ( status.getSeverity().toLowerCase().equals("error") ) {
return new IStatus[] { new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, status.getMessage()) };
}
}
// We can't save these values unless the environment is available
List<EnvironmentDescription> envs = client.describeEnvironments(
new DescribeEnvironmentsRequest().withEnvironmentNames(environment.getEnvironmentName()))
.getEnvironments();
if ( envs.size() > 1 ) {
return new IStatus[] { new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Environment busy") };
}
if ( !envs.get(0).getStatus().equals(EnvironmentStatus.Ready.toString()) ) {
return new IStatus[] { new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
"Environment must be available before saving") };
}
} catch ( Exception e ) {
return new IStatus[] { new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage(), e) };
}
return new IStatus[] { Status.OK_STATUS };
}
/**
* Performs the save operation, implemented as a job.
*/
@Override
public void doSave(IProgressMonitor monitor) {
if (dirty) {
UpdateEnvironmentRequest rq = new UpdateEnvironmentRequest();
rq.setEnvironmentName(environment.getEnvironmentName());
Collection<ConfigurationOptionSetting> settings = model.createConfigurationOptions();
rq.setOptionSettings(settings);
UpdateEnvironmentConfigurationJob job = new UpdateEnvironmentConfigurationJob(environment, rq);
job.schedule();
dirty = false;
}
}
@Override
public void destroyOldLayouts() {
// Not allow refresh action during the destroying of controls
refreshAction.setEnabled(false);
if (leftColumnComp != null) {
for (Control control : leftColumnComp.getChildren()) {
control.dispose();
}
}
if (rightColumnComp != null) {
for (Control control : rightColumnComp.getChildren()) {
control.dispose();
}
}
refreshAction.setEnabled(true);
}
}
| 7,404 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EnvironmentOverviewEditorSection.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.server.ui.configEditor;
import java.util.List;
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.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.resource.LocalResourceManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
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.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.wst.server.ui.editor.ServerEditorSection;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.core.ui.overview.HyperlinkHandler;
import com.amazonaws.eclipse.core.ui.preferences.AwsAccountPreferencePage;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentHealthRequest;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentHealthResult;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.services.elasticbeanstalk.model.InvalidRequestException;
import com.amazonaws.util.CollectionUtils;
import com.amazonaws.util.StringUtils;
/**
* Environment overview editor section
*/
public class EnvironmentOverviewEditorSection extends ServerEditorSection {
/** The section widget we're managing */
private Section section;
private Environment environment;
private FormToolkit toolkit;
private StyledText environmentNameLabel;
private StyledText environmentDescriptionLabel;
private StyledText regionNameLabel;
private StyledText applicationNameLabel;
private StyledText applicationVersionLabel;
private StyledText applicationTierLabel;
private StyledText statusLabel;
private StyledText healthLabel;
private StyledText healthCausesLabel;
private StyledText solutionStackLabel;
private StyledText createdOnLabel;
private StyledText dateUpdatedLabel;
private Hyperlink environmentUrlHyperlink;
private Hyperlink owningAccountHyperlink;
/*
* (non-Javadoc)
* @see org.eclipse.wst.server.ui.editor.ServerEditorSection#init(org.eclipse.ui.IEditorSite,
* org.eclipse.ui.IEditorInput)
*/
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
environment = (Environment) server.loadAdapter(Environment.class, null);
}
@Override
public void createSection(Composite parent) {
super.createSection(parent);
getManagedForm().getForm().getToolBarManager().add(new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR,
"Refresh", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh");
}
@Override
protected void doRun() {
refreshEnvironmentDetails();
actionFinished();
}
});
getManagedForm().getForm().getToolBarManager().update(true);
toolkit = getFormToolkit(parent.getDisplay());
section = toolkit.createSection(parent, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED
| ExpandableComposite.TITLE_BAR | Section.DESCRIPTION | ExpandableComposite.FOCUS_TITLE);
section.setText("AWS Elastic Beanstalk Environment");
section.setDescription("Basic information about your environment.");
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
GridData horizontalAndVerticalFillGridData = new GridData(GridData.FILL_HORIZONTAL
| GridData.VERTICAL_ALIGN_FILL);
Composite composite = toolkit.createComposite(section);
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.marginHeight = 5;
layout.marginWidth = 10;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 15;
composite.setLayout(layout);
composite.setLayoutData(horizontalAndVerticalFillGridData);
toolkit.paintBordersFor(composite);
section.setClient(composite);
section.setLayout(layout);
section.setLayoutData(horizontalAndVerticalFillGridData);
environmentNameLabel = createRow(composite, "Environment Name: ", environment.getEnvironmentName());
environmentDescriptionLabel = createRow(composite, "Environment Description: ",
environment.getEnvironmentDescription());
if (ConfigurationOptionConstants.WEB_SERVER.equals(environment.getEnvironmentTier())) {
createLabel(toolkit, composite, "Environment URL:");
environmentUrlHyperlink = toolkit.createHyperlink(composite, "", SWT.NONE);
environmentUrlHyperlink.addHyperlinkListener(new HyperlinkHandler());
}
regionNameLabel = createRow(composite, "AWS Region: ", "");
applicationNameLabel = createRow(composite, "Application Name: ", environment.getApplicationName());
applicationVersionLabel = createRow(composite, "Application Version: ", environment.getEnvironmentDescription());
applicationTierLabel = createRow(composite, "Application Tier: ", environment.getEnvironmentTier());
statusLabel = createRow(composite, "Status:", "");
healthLabel = createRow(composite, "Health: ", "");
healthCausesLabel = createRow(composite, "Causes:", "");
solutionStackLabel = createRow(composite, "Solution Stack: ", "");
createdOnLabel = createRow(composite, "Created On: ", "");
dateUpdatedLabel = createRow(composite, "Last Updated: ", "");
String accountId = environment.getAccountId();
String accountName = AwsToolkitCore.getDefault().getAccountManager().getAllAccountNames().get(accountId);
if (accountName != null) {
createLabel(toolkit, composite, "AWS Account: ");
String href = "preference:" + AwsAccountPreferencePage.ID;
String text = accountName;
owningAccountHyperlink = toolkit.createHyperlink(composite, text, SWT.None);
owningAccountHyperlink.setHref(href);
owningAccountHyperlink.addHyperlinkListener(new HyperlinkHandler());
}
refreshEnvironmentDetails();
}
private void refreshEnvironmentDetails() {
new LoadHealthStatusJob().schedule();
String regionEndpoint = environment.getRegionEndpoint();
try {
Region region = RegionUtils.getRegionByEndpoint(regionEndpoint);
regionNameLabel.setText(region.getName());
} catch (Exception e) {
regionNameLabel.setText(regionEndpoint);
}
EnvironmentDescription environmentDescription = environment.getCachedEnvironmentDescription();
if (environmentDescription != null) {
environmentNameLabel.setText(environmentDescription.getEnvironmentName());
if (environmentDescription.getDescription() != null) {
environmentDescriptionLabel.setText(environmentDescription.getDescription());
}
if (environmentUrlHyperlink != null) {
String environmentUrl = "http://" + environmentDescription.getCNAME();
environmentUrlHyperlink.setText(environmentUrl);
environmentUrlHyperlink.setHref(environmentUrl);
}
applicationNameLabel.setText(environmentDescription.getApplicationName());
applicationVersionLabel.setText(environmentDescription.getVersionLabel());
applicationTierLabel.setText(environmentDescription.getTier().getName());
statusLabel.setText(environmentDescription.getStatus());
solutionStackLabel.setText(environmentDescription.getSolutionStackName());
createdOnLabel.setText(environmentDescription.getDateCreated().toString());
dateUpdatedLabel.setText(environmentDescription.getDateUpdated().toString());
} else {
environmentNameLabel.setText(environment.getEnvironmentName());
if (environment.getEnvironmentDescription() != null) {
environmentDescriptionLabel.setText(environment.getEnvironmentDescription());
}
environmentUrlHyperlink.setText("");
environmentUrlHyperlink.setHref("");
applicationNameLabel.setText(environment.getApplicationName());
applicationVersionLabel.setText("");
statusLabel.setText("");
healthLabel.setText("");
solutionStackLabel.setText("");
createdOnLabel.setText("");
dateUpdatedLabel.setText("");
}
section.layout(true);
}
protected EnvironmentDescription describeEnvironment(String environmentName) {
return new ElasticBeanstalkClientExtensions(environment).getEnvironmentDescription(environmentName);
}
protected StyledText createRow(Composite composite, String labelText, String value) {
createLabel(toolkit, composite, labelText);
StyledText text = createReadOnlyText(toolkit, composite, value);
text.setLayoutData(new GridData(GridData.FILL_BOTH));
return text;
}
protected Label createLabel(FormToolkit toolkit, Composite parent, String text) {
Label label = toolkit.createLabel(parent, text);
label.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
return label;
}
protected StyledText createReadOnlyText(FormToolkit toolkit, Composite parent, String text) {
StyledText t = new StyledText(parent, SWT.READ_ONLY | SWT.NO_FOCUS | SWT.WRAP);
t.setText(text);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.widthHint = 400;
t.setLayoutData(gridData);
return t;
}
/**
* Italize all text in the StyledText. Should be called after text is set.
*
* @param styledText
*/
private static void italizeStyledText(StyledText styledText) {
StyleRange italicStyle = new StyleRange();
italicStyle.fontStyle = SWT.ITALIC;
italicStyle.length = styledText.getText().length();
styledText.setStyleRange(italicStyle);
}
/**
* Background job to load the environment health data and dump it into the UI
*/
private final class LoadHealthStatusJob extends Job {
private final BeanstalkHealthColorConverter colorConverter = new BeanstalkHealthColorConverter(
new LocalResourceManager(JFaceResources.getResources(), section));
private final AWSElasticBeanstalk beanstalk = environment.getClient();
public LoadHealthStatusJob() {
super("Loading Health Status");
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
updateEnhancedHealthControls(getEnvironmentHealth());
} catch (InvalidRequestException e) {
// Enhanced health isn't supported for this environment so just show the basic data
// from the EnvironmentDescription
updateBasicHealthControls();
}
return Status.OK_STATUS;
}
private DescribeEnvironmentHealthResult getEnvironmentHealth() {
return beanstalk.describeEnvironmentHealth(new DescribeEnvironmentHealthRequest().withEnvironmentName(
environment.getEnvironmentName()).withAttributeNames("All"));
}
/**
* Update the Health using data from the {@link EnvironmentDescription} since Enhanced
* health reporting is not enabled for this environment
*/
private void updateBasicHealthControls() {
final EnvironmentDescription envDesc = environment.getCachedEnvironmentDescription();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
healthLabel.setForeground(colorConverter.toColor(envDesc.getHealth()));
healthLabel.setText(envDesc.getHealth());
healthCausesLabel
.setText("Causes information is only available for environments with Enhanced Health Reporting enabled");
italizeStyledText(healthCausesLabel);
}
});
}
/**
* Update the Health and Causes using data from the {@link DescribeEnvironmentHealthResult}
* for the Enhanced Health capable environment
*/
private void updateEnhancedHealthControls(final DescribeEnvironmentHealthResult result) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
healthLabel.setText(result.getHealthStatus());
healthLabel.setForeground(colorConverter.toColor(result.getColor()));
healthCausesLabel.setText(getCausesDisplayText(result.getCauses()));
}
});
}
/**
* Convert the list of causes to something that can be displayed in the Text control
*
* @param causes
* List of causes for non-OK health statuses
* @return Display string
*/
private String getCausesDisplayText(List<String> causes) {
if (!CollectionUtils.isNullOrEmpty(causes)) {
return StringUtils.join(",", causes.toArray(new String[0]));
} else {
return "";
}
}
}
}
| 7,405 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EventLogEditorPart.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.server.ui.configEditor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.wst.server.ui.editor.ServerEditorPart;
import org.eclipse.wst.server.ui.internal.ImageResource;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.explorer.AwsAction;
@SuppressWarnings("restriction")
public class EventLogEditorPart extends ServerEditorPart {
private ManagedForm managedForm;
private EventLogEditorSection eventLog;
@Override
public void createPartControl(Composite parent) {
managedForm = new ManagedForm(parent);
setManagedForm(managedForm);
ScrolledForm form = managedForm.getForm();
FormToolkit toolkit = managedForm.getToolkit();
toolkit.decorateFormHeading(form.getForm());
form.setText("Event Log");
form.setImage(ImageResource.getImage(ImageResource.IMG_SERVER));
Composite columnComp = toolkit.createComposite(form.getBody());
FillLayout layout = new FillLayout();
layout.marginHeight = 0;
columnComp.setLayout(new FillLayout());
form.getBody().setLayout(layout);
eventLog = new EventLogEditorSection();
eventLog.setServerEditorPart(this);
eventLog.init(this.getEditorSite(), this.getEditorInput());
eventLog.createSection(columnComp);
managedForm.getForm().getToolBarManager().add(new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR,
"Refresh", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh");
}
@Override
protected void doRun() {
eventLog.refresh();
actionFinished();
}
});
managedForm.getForm().getToolBarManager().update(true);
form.reflow(true);
}
@Override
public void setFocus() {
managedForm.setFocus();
eventLog.refresh();
}
}
| 7,406 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/AbstractEnvironmentConfigEditorPart.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.elasticbeanstalk.server.ui.configEditor;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.ChangeEvent;
import org.eclipse.core.databinding.observable.IChangeListener;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.wst.server.ui.editor.ServerEditorPart;
import com.amazonaws.eclipse.core.ui.CancelableThread;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.explorer.AwsAction;
/**
* Abstract base class for editor editor parts that edit an environment
* configuration.
*/
public abstract class AbstractEnvironmentConfigEditorPart extends ServerEditorPart {
protected static final String RESTART_NOTICE = "Save the editor to apply your changes to your AWS Elastic Beanstalk environment. "
+ "Changing a configuration value marked with * will cause your application server to restart. "
+ "Changing a value marked with ** will cause your environment to restart. "
+ "Your environment will become unavailable for several minutes.";
// SWT editor glue
protected ManagedForm managedForm;
protected Environment environment;
protected boolean dirty = false;
protected AwsAction refreshAction;
// Data model and binding context
protected EnvironmentConfigDataModel model;
protected DataBindingContext bindingContext = new DataBindingContext();
AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
environment = (Environment) server.loadAdapter(Environment.class, null);
model = EnvironmentConfigDataModel.getInstance(environment);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.getSeverity() == IStatus.OK ) {
setErrorMessage(null);
} else {
if ( status.getSeverity() == IStatus.ERROR ) {
setErrorMessage(status.getMessage());
}
}
}
});
}
@Override
public void setFocus() {
managedForm.getForm().setFocus();
}
public void markDirty() {
if (!dirty) {
dirty = true;
execute(new NullOperation());
}
}
@Override
public boolean isDirty() {
return dirty;
}
/**
* Cancels the thread given if it's running.
*/
protected void cancelThread(CancelableThread thread) {
if ( thread != null ) {
synchronized (thread) {
if ( thread.isRunning() ) {
thread.cancel();
}
}
}
}
public DataBindingContext getDataBindingContext() {
return bindingContext;
}
/**
* Refreshes the editor with the latest values
*/
public abstract void refresh(String templateName);
/**
* Destroy the controls to let refresh method to redraw them.
* Sometimes we do not need to destroy these controls before refresh
*/
public abstract void destroyOldLayouts();
}
| 7,407 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/EnvironmentResourcesEditorPart.java | /*
* Copyright 2011-2012 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.elasticbeanstalk.server.ui.configEditor;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.wst.server.ui.editor.ServerEditorPart;
import org.eclipse.wst.server.ui.editor.ServerEditorSection;
import org.eclipse.wst.server.ui.internal.ImageResource;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.ui.views.instances.InstanceSelectionTable;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.eclipse.explorer.sqs.AddMessageAction;
import com.amazonaws.services.autoscaling.AmazonAutoScaling;
import com.amazonaws.services.autoscaling.model.AutoScalingGroup;
import com.amazonaws.services.autoscaling.model.DescribeAutoScalingGroupsRequest;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.DescribeEnvironmentResourcesRequest;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentResourceDescription;
import com.amazonaws.services.elasticbeanstalk.model.Instance;
import com.amazonaws.services.elasticloadbalancing.AmazonElasticLoadBalancing;
import com.amazonaws.services.elasticloadbalancing.model.DescribeLoadBalancersRequest;
import com.amazonaws.services.elasticloadbalancing.model.LoadBalancerDescription;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.GetQueueAttributesRequest;
import com.amazonaws.services.sqs.model.QueueAttributeName;
public class EnvironmentResourcesEditorPart extends ServerEditorPart {
protected ManagedForm managedForm;
private EnvironmentInstancesEditorSection instancesEditorSection;
private EnvironmentAutoScalingEditorSection autoScalingEditorSection;
private EnvironmentElasticLoadBalancingEditorSection elasticLoadBalancingEditorSection;
private EnvironmentQueueEditorSection queueEditorSection;
@Override
public void createPartControl(Composite parent) {
managedForm = new ManagedForm(parent);
setManagedForm(managedForm);
ScrolledForm form = managedForm.getForm();
FormToolkit toolkit = managedForm.getToolkit();
toolkit.decorateFormHeading(form.getForm());
form.setText("Environment Resources");
form.setImage(ImageResource.getImage(ImageResource.IMG_SERVER));
FillLayout fillLayout = new FillLayout();
form.getBody().setLayout(fillLayout);
fillLayout.marginHeight = 10;
fillLayout.marginWidth = 10;
Composite composite = toolkit.createComposite(form.getBody());
composite.setLayout(new GridLayout(2, true));
if (!getEnvironment().getEnvironmentType().equals(ConfigurationOptionConstants.SINGLE_INSTANCE_ENV)) {
autoScalingEditorSection = new EnvironmentAutoScalingEditorSection();
autoScalingEditorSection.setServerEditorPart(this);
autoScalingEditorSection.init(this.getEditorSite(), this.getEditorInput());
autoScalingEditorSection.createSection(composite);
if (ConfigurationOptionConstants.WEB_SERVER.equals(getEnvironment().getEnvironmentTier())) {
elasticLoadBalancingEditorSection = new EnvironmentElasticLoadBalancingEditorSection();
elasticLoadBalancingEditorSection.setServerEditorPart(this);
elasticLoadBalancingEditorSection.init(this.getEditorSite(), this.getEditorInput());
elasticLoadBalancingEditorSection.createSection(composite);
} else {
queueEditorSection = new EnvironmentQueueEditorSection();
queueEditorSection.setServerEditorPart(this);
queueEditorSection.init(this.getEditorSite(), this.getEditorInput());
queueEditorSection.createSection(composite);
}
}
instancesEditorSection = new EnvironmentInstancesEditorSection();
instancesEditorSection.setServerEditorPart(this);
instancesEditorSection.init(this.getEditorSite(), this.getEditorInput());
instancesEditorSection.createSection(composite);
form.getToolBarManager().add(new RefreshAction(AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR));
form.getToolBarManager().update(true);
new RefreshThread().start();
}
private class RefreshAction extends AwsAction {
public RefreshAction(AwsToolkitMetricType metricType) {
super(metricType);
setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
setText("Refresh");
setToolTipText("Refresh");
}
@Override
protected void doRun() {
new RefreshThread().start();
actionFinished();
}
}
private class RefreshThread extends Thread {
@Override
public void run() {
if (getEnvironment().doesEnvironmentExistInBeanstalk() == false) {
return;
}
DescribeEnvironmentResourcesRequest request = new DescribeEnvironmentResourcesRequest()
.withEnvironmentName(getEnvironment().getEnvironmentName());
EnvironmentResourceDescription resources = getClient().describeEnvironmentResources(request).getEnvironmentResources();
instancesEditorSection.update(resources);
if (autoScalingEditorSection != null) {
autoScalingEditorSection.update(resources);
}
if (elasticLoadBalancingEditorSection != null) {
elasticLoadBalancingEditorSection.update(resources);
}
if (queueEditorSection != null) {
queueEditorSection.update(resources);
}
}
}
private static abstract class AbstractEnvironmentResourcesEditorSection extends ServerEditorSection {
protected Section section;
protected FormToolkit toolkit;
protected Composite createSection(Composite parent, String label, String description) {
toolkit = getFormToolkit(Display.getDefault());
section = toolkit.createSection(parent,
Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR |
Section.DESCRIPTION | Section.FOCUS_TITLE);
section.setText(label);
section.setDescription(description);
Composite composite = toolkit.createComposite(section);
FillLayout layout = new FillLayout();
layout.marginHeight = 10;
layout.marginWidth = 10;
layout.type = SWT.VERTICAL;
composite.setLayout(layout);
toolkit.paintBordersFor(composite);
section.setClient(composite);
section.setLayout(layout);
return composite;
}
public abstract void update(EnvironmentResourceDescription resources);
}
private class EnvironmentQueueEditorSection extends AbstractEnvironmentResourcesEditorSection {
private Label nameLabel;
private Link urlLink;
private Label createdLabel;
private Label numberOfMessagesLabel;
private Label numberOfMessagesInFlightLabel;
@Override
public void createSection(Composite parent) {
super.createSection(parent);
Composite composite = createSection(
parent,
"Amazon SQS Queue",
"Your Amazon SQS Queue queues work items for delivery to your "
+ "worker tier environment."
);
section.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(2, false));
GridDataFactory gdf = GridDataFactory
.swtDefaults()
.align(SWT.FILL, SWT.TOP)
.grab(true, false);
new Label(composite, SWT.NONE).setText("Name:");
nameLabel = new Label(composite, SWT.NONE);
gdf.applyTo(nameLabel);
new Label(composite, SWT.NONE).setText("URL:");
urlLink = new Link(composite, SWT.NONE);
urlLink.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
String queueUrl = event.text;
AmazonSQS sqs = AwsToolkitCore
.getClientFactory(getEnvironment().getAccountId())
.getSQSClientByEndpoint(getEndpointFromUrl(queueUrl));
new AddMessageAction(sqs, event.text, null).run();
}
});
gdf.applyTo(urlLink);
new Label(composite, SWT.NONE).setText("Created:");
createdLabel = new Label(composite, SWT.NONE);
gdf.applyTo(createdLabel);
new Label(composite, SWT.NONE).setText("Messages Available:");
numberOfMessagesLabel = new Label(composite, SWT.NONE);
gdf.applyTo(numberOfMessagesLabel);
new Label(composite, SWT.NONE).setText("Messages in Flight:");
numberOfMessagesInFlightLabel = new Label(composite, SWT.NONE);
gdf.applyTo(numberOfMessagesInFlightLabel);
}
@Override
public void update(final EnvironmentResourceDescription resources) {
if (resources.getQueues().isEmpty()) {
return;
}
final String queueName = resources.getQueues().get(0).getName();
final String queueUrl = resources.getQueues().get(0).getURL();
AmazonSQS sqs = AwsToolkitCore
.getClientFactory(getEnvironment().getAccountId())
.getSQSClientByEndpoint(getEndpointFromUrl(queueUrl));
final Map<String, String> attributes =
sqs.getQueueAttributes(new GetQueueAttributesRequest()
.withQueueUrl(queueUrl)
.withAttributeNames(
QueueAttributeName.ApproximateNumberOfMessages,
QueueAttributeName.ApproximateNumberOfMessagesNotVisible,
QueueAttributeName.CreatedTimestamp,
QueueAttributeName.DelaySeconds))
.getAttributes();
if (attributes.isEmpty()) {
return;
}
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
nameLabel.setText(queueName);
urlLink.setText("<a>" + queueUrl + "</a>");
String createdTimestamp = attributes.get("CreatedTimestamp");
if (createdTimestamp != null) {
String text;
try {
long timestamp = Long.parseLong(createdTimestamp);
text = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy")
.format(new Date(timestamp * 1000L));
} catch (NumberFormatException exception) {
text = "";
}
createdLabel.setText(text);
}
String numberOfMessages = attributes.get("ApproximateNumberOfMessages");
numberOfMessagesLabel.setText(numberOfMessages == null ? "" : numberOfMessages);
String numberOfMessagesInFlight = attributes.get("ApproximateNumberOfMessagesNotVisible");
numberOfMessagesInFlightLabel.setText(numberOfMessagesInFlight == null ? "" : numberOfMessagesInFlight);
}
});
}
private String getEndpointFromUrl(final String url) {
try {
URI parsed = new URI(url);
return parsed.getScheme() + "://" + parsed.getAuthority();
} catch (URISyntaxException exception) {
throw new RuntimeException("Could not parse URL: " + url,
exception);
}
}
}
private class EnvironmentAutoScalingEditorSection extends AbstractEnvironmentResourcesEditorSection {
private Label maxSizeLabel;
private Label minSizeLabel;
private Label launchConfigurationLabel;
private Label desiredCapacityLabel;
private Label healthCheckTypeLabel;
private Label createdLabel;
private Label availabilityZonesLabel;
private Label nameLabel;
@Override
public void createSection(Composite parent) {
super.createSection(parent);
Composite composite = createSection(parent, "Amazon Auto Scaling Group",
"Your Amazon Auto Scaling group controls how your fleet dynamically resizes.");
section.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
composite.setLayout(new GridLayout(2, false));
GridDataFactory gdf = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false);
new Label(composite, SWT.NONE).setText("Name:");
nameLabel = new Label(composite, SWT.NONE);
gdf.applyTo(nameLabel);
new Label(composite, SWT.NONE).setText("Availability Zones:");
availabilityZonesLabel = new Label(composite, SWT.NONE);
gdf.applyTo(availabilityZonesLabel);
new Label(composite, SWT.NONE).setText("Created:");
createdLabel = new Label(composite, SWT.NONE);
gdf.applyTo(createdLabel);
new Label(composite, SWT.NONE).setText("Health Check Type:");
healthCheckTypeLabel = new Label(composite, SWT.NONE);
gdf.applyTo(healthCheckTypeLabel);
new Label(composite, SWT.NONE).setText("Launch Configuration:");
launchConfigurationLabel = new Label(composite, SWT.NONE);
gdf.applyTo(launchConfigurationLabel);
new Label(composite, SWT.NONE).setText("Desired Capacity:");
desiredCapacityLabel = new Label(composite, SWT.NONE);
gdf.applyTo(desiredCapacityLabel);
new Label(composite, SWT.NONE).setText("Min Size:");
minSizeLabel = new Label(composite, SWT.NONE);
gdf.applyTo(minSizeLabel);
new Label(composite, SWT.NONE).setText("Max Size:");
maxSizeLabel = new Label(composite, SWT.NONE);
gdf.applyTo(maxSizeLabel);
}
@Override
public void update(EnvironmentResourceDescription resources) {
Region region = RegionUtils.getRegionByEndpoint(getEnvironment().getRegionEndpoint());
String endpoint = region.getServiceEndpoints().get(ServiceAbbreviations.AUTOSCALING);
AmazonAutoScaling as = AwsToolkitCore.getClientFactory(getEnvironment().getAccountId()).getAutoScalingClientByEndpoint(endpoint);
if ( !resources.getAutoScalingGroups().isEmpty() ) {
DescribeAutoScalingGroupsRequest request = new DescribeAutoScalingGroupsRequest()
.withAutoScalingGroupNames(resources.getAutoScalingGroups().get(0).getName());
List<AutoScalingGroup> autoScalingGroups = as.describeAutoScalingGroups(request).getAutoScalingGroups();
if ( autoScalingGroups.size() > 0 ) {
final AutoScalingGroup group = autoScalingGroups.get(0);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
nameLabel.setText(group.getAutoScalingGroupName());
availabilityZonesLabel.setText(group.getAvailabilityZones().toString());
createdLabel.setText("" + group.getCreatedTime());
healthCheckTypeLabel.setText(group.getHealthCheckType());
desiredCapacityLabel.setText("" + group.getDesiredCapacity());
launchConfigurationLabel.setText(group.getLaunchConfigurationName());
minSizeLabel.setText("" + group.getMinSize());
maxSizeLabel.setText("" + group.getMaxSize());
}
});
}
}
}
}
private class EnvironmentElasticLoadBalancingEditorSection extends AbstractEnvironmentResourcesEditorSection {
private Label nameLabel;
private Label dnsLabel;
private Label createdLabel;
private Label availabilityZonesLabel;
@Override
public void createSection(Composite parent) {
super.createSection(parent);
Composite composite = createSection(parent, "Amazon Elastic Load Balancer",
"Your Elastic Load Balancer provides a single access point for the fleet of EC2 instances running your application.");
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, false);
gridData.widthHint = 300;
section.setLayoutData(gridData);
composite.setLayout(new GridLayout(2, false));
GridDataFactory gdf = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false);
new Label(composite, SWT.NONE).setText("Name:");
nameLabel = new Label(composite, SWT.NONE);
gdf.applyTo(nameLabel);
new Label(composite, SWT.NONE).setText("DNS:");
dnsLabel = new Label(composite, SWT.WRAP);
gdf.applyTo(dnsLabel);
new Label(composite, SWT.NONE).setText("Created:");
createdLabel = new Label(composite, SWT.NONE);
gdf.applyTo(createdLabel);
new Label(composite, SWT.NONE).setText("Availability Zones:");
availabilityZonesLabel = new Label(composite, SWT.NONE);
gdf.applyTo(availabilityZonesLabel);
}
@Override
public void update(EnvironmentResourceDescription resources) {
Region region = RegionUtils.getRegionByEndpoint(getEnvironment().getRegionEndpoint());
String endpoint = region.getServiceEndpoints().get(ServiceAbbreviations.ELB);
AmazonElasticLoadBalancing elb = AwsToolkitCore.getClientFactory(getEnvironment().getAccountId()).getElasticLoadBalancingClientByEndpoint(endpoint);
if (resources.getLoadBalancers() == null || resources.getLoadBalancers().size() == 0) {
return;
}
String loadBalancerName = resources.getLoadBalancers().get(0).getName();
DescribeLoadBalancersRequest request = new DescribeLoadBalancersRequest().withLoadBalancerNames(loadBalancerName);
List<LoadBalancerDescription> loadBalancers = elb.describeLoadBalancers(request).getLoadBalancerDescriptions();
if (loadBalancers.size() == 0) {
return;
}
final LoadBalancerDescription lb = loadBalancers.get(0);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
nameLabel.setText(lb.getLoadBalancerName());
dnsLabel.setText(lb.getDNSName());
createdLabel.setText(lb.getCreatedTime().toString());
availabilityZonesLabel.setText(lb.getAvailabilityZones().toString());
Composite parent = nameLabel.getParent();
parent.setSize(parent.computeSize(parent.getSize().x, SWT.DEFAULT, true));
parent.getParent().layout(true, true);
}
});
}
}
private class EnvironmentInstancesEditorSection extends AbstractEnvironmentResourcesEditorSection {
private InstanceSelectionTable instanceSelectionTable;
@Override
public void createSection(Composite parent) {
super.createSection(parent);
Composite composite = createSection(parent, "Amazon EC2 Instances",
"These instances make up the fleet in your environment");
GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
section.setLayoutData(gridData);
instanceSelectionTable = new InstanceSelectionTable(composite);
instanceSelectionTable.setAccountIdOverride(getEnvironment().getAccountId());
Region region = RegionUtils.getRegionByEndpoint(getEnvironment().getRegionEndpoint());
String ec2Endpoint = region.getServiceEndpoints().get(ServiceAbbreviations.EC2);
instanceSelectionTable.setEc2RegionOverride(region);
}
@Override
public void update(EnvironmentResourceDescription resources) {
List<String> instanceIds = new ArrayList<>();
for (Instance instance : resources.getInstances()) {
instanceIds.add(instance.getId());
}
instanceSelectionTable.setInstancesToList(instanceIds);
}
}
@Override
public void setFocus() {}
private AWSElasticBeanstalk getClient() {
Environment environment = getEnvironment();
return AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
}
private Environment getEnvironment() {
return (Environment)server.loadAdapter(Environment.class, null);
}
}
| 7,408 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/RefreshListener.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.elasticbeanstalk.server.ui.configEditor;
/**
* Listener for model refresh events.
*/
public interface RefreshListener {
public void refreshStarted();
public void refreshFinished();
public void refreshError(Throwable e);
}
| 7,409 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/HealthCheckConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Environment config editor section for setting "Server" properties, roughly
* corresponding to the aws:autoscaling:launchconfiguration" namespace.
*/
public class HealthCheckConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("HealthyThreshold", "Healthy Check Count Threshold");
humanReadableNames.put("Interval", "Health Check Interval (seconds)");
humanReadableNames.put("Timeout", "Health Check Timeout (seconds)");
humanReadableNames.put("UnhealthyThreshold", "Unhealthy Check Count Threshold");
humanReadableNames.put("Application Healthcheck URL", "Application Health Check URL");
}
private static final String[] fieldOrder = new String[] {
"Application Healthcheck URL", "Interval", "Timeout", "HealthyThreshold", "UnhealthyThreshold",
};
public HealthCheckConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "EC2 Instance Health Check";
}
@Override
protected String getSectionDescription() {
return "These settings allow you to configure how AWS Elastic Beanstalk determines whether an EC2 instance is healthy or not.";
}
}
| 7,410 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/LoadBalancingConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Load Balancing section of the human-readable environment config editor.
*/
public class LoadBalancingConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("LoadBalancerHTTPPort", "HTTP Port");
humanReadableNames.put("LoadBalancerHTTPSPort", "HTTPS Port");
humanReadableNames.put("SSLCertificateId", "SSL Certificate Id");
}
private static final String[] fieldOrder = new String[] { "LoadBalancerHTTPPort", "LoadBalancerHTTPSPort",
"SSLCertificateId" };
public LoadBalancingConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Load Balancing";
}
@Override
protected String getSectionDescription() {
return "These settings allow you to control the behavior of your environment's load balancer.";
}
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION | Section.NO_TITLE);
}
}
| 7,411 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/RollingDeploymentsConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Human readable editor section to configure rolling deployment parameters.
*/
public class RollingDeploymentsConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("BatchSizeType", "Batch size type");
humanReadableNames.put("BatchSize", "Batch size");
}
private static final String[] fieldOrder = new String[] { "BatchSizeType", "BatchSize" };
public RollingDeploymentsConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Rolling Deployments";
}
@Override
protected String getSectionDescription() {
return "The following settings control how application versions " +
"are deployed to instances in batches.";
}
@Override
protected Section getSection(Composite parent) {
Section section = toolkit.createSection(parent, Section.DESCRIPTION | Section.NO_TITLE);
return section;
}
}
| 7,412 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/AdvancedEnvironmentTypeConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.List;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
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.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.AbstractEnvironmentConfigEditorPart;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigEditorSection;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Environment config editor section in advanced config editor for setting.
* "Environment Type" property, corresponding to the "aws:elasticbeanstalk:environment" namespace.
*/
public class AdvancedEnvironmentTypeConfigEditorSection extends EnvironmentConfigEditorSection {
public AdvancedEnvironmentTypeConfigEditorSection(AbstractEnvironmentConfigEditorPart parentEditor, EnvironmentConfigDataModel model,
Environment environment, DataBindingContext bindingContext, String namespace, List<ConfigurationOptionDescription> options) {
super(parentEditor, model, environment, bindingContext, namespace, options);
}
/**
* Create a read only label instead of combo
*/
@Override
protected void createCombo(Composite parent, ConfigurationOptionDescription option) {
Label label = createLabel(toolkit, parent, option);
label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
final Label typeLabel = new Label(parent, SWT.READ_ONLY);
IObservableValue modelv = model.observeEntry(option);
ISWTObservableValue widget = SWTObservables.observeText(typeLabel);
parentEditor.getDataBindingContext().bindValue(widget, modelv,
new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE),
new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE));
}
}
| 7,413 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/ContainerConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.conversion.IConverter;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.observable.value.IValueChangeListener;
import org.eclipse.core.databinding.observable.value.ValueChangeEvent;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Human readable editor for container / jvm options
*/
public class ContainerConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("Xms", "Initial JVM Heap Size (-Xms argument)");
humanReadableNames.put("Xmx", "Maximum JVM Heap Size (-Xmx argument)");
humanReadableNames.put("XX:MaxPermSize", "Maximum JVM PermGen Size (-XX:MaxPermSize argument)");
humanReadableNames.put("JVM Options", "Additional Tomcat JVM command line options");
humanReadableNames.put("LogPublicationControl", "Enable log file rotation to Amazon S3");
}
private static final String[] fieldOrder = new String[] { "Xms", "Xmx", "XX:MaxPermSize", "JVM Options", "LogPublicationControl"};
public ContainerConfigEditorSection(BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Container / JVM Options";
}
@Override
protected String getSectionDescription() {
return "These settings control command-line options for " + "your container and the underlying JVM.";
}
@Override
protected void createSectionControls(Composite composite) {
super.createSectionControls(composite);
createDebugEnablementControl(composite);
}
private void createDebugEnablementControl(Composite composite) {
final Button enablement = toolkit.createButton(composite, "Enable remote debugging", SWT.CHECK);
GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false);
layoutData.horizontalSpan = 2;
enablement.setLayoutData(layoutData);
final Label portLabel = toolkit.createLabel(composite, "Remote debugging port:");
portLabel.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
final Text portText = toolkit.createText(composite, "");
layoutTextField(portText);
ConfigurationOptionDescription jvmOptions = null;
for ( ConfigurationOptionDescription opt : options ) {
if ( "JVM Options".equals(opt.getName()) ) {
jvmOptions = opt;
break;
}
}
if ( jvmOptions == null )
throw new RuntimeException("Couldn't determine JVM options");
/*
* These bindings are complicated because we don't copy the value across
* directly. Instead, we modify the JVM options string (or respond to
* modification of it).
*/
final IObservableValue jvmOptionsObservable = model.observeEntry(jvmOptions);
final IObservableValue textObservable = SWTObservables.observeText(portText, SWT.Modify);
final IObservableValue enablementObservable = SWTObservables.observeSelection(enablement);
IValueChangeListener listener = new IValueChangeListener() {
@Override
public void handleValueChange(ValueChangeEvent event) {
portText.setEnabled((Boolean) enablementObservable.getValue());
portLabel.setEnabled((Boolean) enablementObservable.getValue());
}
};
enablementObservable.addValueChangeListener(listener);
setupBindingsForDebugPort(jvmOptionsObservable, textObservable);
setupBindingsForDebugEnablement(jvmOptionsObservable, enablementObservable);
listener.handleValueChange(null);
}
protected void setupBindingsForDebugEnablement(final IObservableValue jvmOptionsObservable,
final IObservableValue enablementObservable) {
UpdateValueStrategy debugEnabledModelToTarget = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
UpdateValueStrategy debugEnabledTargetToModel = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
debugEnabledModelToTarget.setConverter(new IConverter() {
@Override
public Object getToType() {
return Boolean.class;
}
@Override
public Object getFromType() {
return String.class;
}
@Override
public Object convert(Object fromObject) {
return ((String)fromObject).contains("-Xdebug");
}
});
debugEnabledTargetToModel.setConverter(new IConverter() {
@Override
public Object getToType() {
return String.class;
}
@Override
public Object getFromType() {
return Boolean.class;
}
@Override
public Object convert(Object fromObject) {
String currentOptions = (String) jvmOptionsObservable.getValue();
if ( (Boolean) fromObject ) {
if ( !currentOptions.contains("-Xdebug") ) {
currentOptions += " " + "-Xdebug";
}
} else {
Matcher matcher = Pattern.compile("-Xdebug").matcher(currentOptions);
if ( matcher.find() )
currentOptions = matcher.replaceFirst("");
matcher = Pattern.compile("-Xrunjdwp:\\S+").matcher(currentOptions);
if ( matcher.find() )
currentOptions = matcher.replaceFirst("");
}
return currentOptions;
}
});
bindingContext.bindValue(enablementObservable, jvmOptionsObservable, debugEnabledTargetToModel,
debugEnabledModelToTarget).updateModelToTarget();
}
protected void setupBindingsForDebugPort(final IObservableValue jvmOptionsObservable,
final IObservableValue textObservable) {
UpdateValueStrategy portTargetToModel = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
portTargetToModel.setConverter(new IConverter() {
@Override
public Object getToType() {
return String.class;
}
@Override
public Object getFromType() {
return String.class;
}
@Override
public Object convert(Object fromObject) {
String debugPort = (String) fromObject;
String currentOptions = (String) jvmOptionsObservable.getValue();
if ( debugPort != null && debugPort.length() > 0 ) {
if ( !currentOptions.contains("-Xrunjdwp:") ) {
currentOptions += " " + "-Xrunjdwp:transport=dt_socket,address=" + debugPort
+ ",server=y,suspend=n";
} else {
Matcher matcher = Pattern.compile("(-Xrunjdwp:\\S*address=)\\d+").matcher(currentOptions);
if ( matcher.find() )
currentOptions = matcher.replaceFirst(matcher.group(1) + debugPort);
}
} else {
Matcher matcher = Pattern.compile("-Xrunjdwp:\\S+").matcher(currentOptions);
if ( matcher.find() )
currentOptions = matcher.replaceFirst("");
}
return currentOptions;
}
});
UpdateValueStrategy portModelToTarget = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
portModelToTarget.setConverter(new IConverter() {
@Override
public Object getToType() {
return String.class;
}
@Override
public Object getFromType() {
return String.class;
}
@Override
public Object convert(Object fromObject) {
String debugPort = Environment.getDebugPort((String) fromObject);
if (debugPort != null)
return debugPort;
return "";
}
});
bindingContext.bindValue(textObservable, jvmOptionsObservable, portTargetToModel, portModelToTarget)
.updateModelToTarget();
}
}
| 7,414 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/NotificationsConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Human-readable config editor section for SNS notifications.
*/
public class NotificationsConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("Notification Endpoint", "E-mail Address");
}
private static final String[] fieldOrder = new String[] { "Notification Endpoint", };
public NotificationsConfigEditorSection(BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Notifications";
}
@Override
protected String getSectionDescription() {
return "Enter an e-mail address which will be sent notifications "
+ "regarding important events using the Amazon Simple Notification Service. "
+ "If you wish to stop receiving notifications, simply remove your e-mail " + "address.";
}
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION | Section.NO_TITLE);
}
}
| 7,415 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/HumanReadableConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.AbstractEnvironmentConfigEditorPart;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigEditorSection;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Base class for human-readable config editor sections that perform a simple
* string translation.
*/
public abstract class HumanReadableConfigEditorSection extends EnvironmentConfigEditorSection {
protected Composite parentComposite;
public Composite getParentComposite() {
return parentComposite;
}
public void setParentComposite(Composite parentComposite) {
this.parentComposite = parentComposite;
}
public HumanReadableConfigEditorSection(AbstractEnvironmentConfigEditorPart parentEditor,
EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(parentEditor, model, environment, bindingContext, null, null);
}
@Override
protected String getName(ConfigurationOptionDescription option) {
if ( getHumanReadableNames().containsKey(option.getName()) )
return getHumanReadableNames().get(option.getName());
return super.getName(option);
}
@Override
protected void createSectionControls(Composite composite) {
for ( String field : getFieldOrder() ) {
for ( ConfigurationOptionDescription o : options ) {
if ( field.equals(o.getName()) ) {
createOptionControl(composite, o);
}
}
}
}
/**
* Creates a section in the given composite.
*/
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION);
}
/**
* Returns a map of ConfigurationOptionDescription name to human-readable
* name.
*/
protected abstract Map<String, String> getHumanReadableNames();
/**
* Returns the display order of the fields, as given by their
* ConfigurationOptionDescription names.
*/
protected abstract String[] getFieldOrder();
}
| 7,416 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/EnvironmentPropertiesConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Human readable config editor section for environment variables.
*/
public class EnvironmentPropertiesConfigEditorSection extends HumanReadableConfigEditorSection {
public EnvironmentPropertiesConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return new HashMap<>();
}
@Override
protected String[] getFieldOrder() {
List<String> optionNames = new ArrayList<>();
for (ConfigurationOptionDescription o : options) {
optionNames.add(o.getName());
}
return optionNames.toArray(new String[optionNames.size()]);
}
@Override
protected String getSectionName() {
return "Environment Properties";
}
@Override
protected String getSectionDescription() {
return "These properties are passed to your application as Java system properties.";
}
}
| 7,417 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/EnvironmentTypeConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.observable.value.IObservableValue;
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.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.UpdateEnvironmentRequest;
/**
* Environment config editor section in basic config editor for setting
* "Environment Type" property, corresponding to the "aws:elasticbeanstalk:environment" namespace.
*/
public class EnvironmentTypeConfigEditorSection extends HumanReadableConfigEditorSection {
private final String CHANGE_ENVIRONMENT_TYPE_WARNING = "Are you sure to change the environment type? "
+ "This change will cause your environment to restart. "
+ "and could be unavailable for several minutes.";
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("EnvironmentType", "Environment Type");
}
private static final String[] fieldOrder = new String[] { "EnvironmentType", };
public EnvironmentTypeConfigEditorSection(BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model,
Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected void createCombo(Composite parent, ConfigurationOptionDescription option) {
Label label = createLabel(toolkit, parent, option);
label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
final Combo combo = new Combo(parent, SWT.READ_ONLY);
combo.setItems(option.getValueOptions().toArray(new String[option.getValueOptions().size()]));
IObservableValue modelv = model.observeEntry(option);
ISWTObservableValue widget = SWTObservables.observeSelection(combo);
parentEditor.getDataBindingContext().bindValue(widget, modelv, new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE),
new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE));
final String oldEnvironmentType = (String)modelv.getValue();
// After you do the confirmation, we will update the environment and refresh the layout.
combo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Change Environment Type",
CHANGE_ENVIRONMENT_TYPE_WARNING);
if (confirmation == true) {
parentEditor.destroyOldLayouts();
UpdateEnvironmentRequest rq = generateUpdateEnvironmentTypeRequest();
if (rq != null) {
UpdateEnvironmentAndRefreshLayoutJob job = new UpdateEnvironmentAndRefreshLayoutJob(environment, rq);
job.schedule();
}
} else {
combo.setText(oldEnvironmentType);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Environment Type";
}
@Override
protected String getSectionDescription() {
return "Select an environment type, either load balanced and auto scaled or single instance. "
+ "A load-balanced, auto-scaled environment automatically distributes traffic across "
+ "multiple Amazon EC2 instances and can stop and start instances based on demand. "
+ "A single-instance environment includes just a single Amazon EC2 instance, which costs less.";
}
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION | Section.NO_TITLE);
}
private UpdateEnvironmentRequest generateUpdateEnvironmentTypeRequest() {
UpdateEnvironmentRequest rq = null;
Collection<ConfigurationOptionSetting> settings = model.createConfigurationOptions();
for (ConfigurationOptionSetting setting : settings) {
if (setting.getNamespace().equals(ConfigurationOptionConstants.ENVIRONMENT_TYPE) && setting.getOptionName().equals("EnvironmentType")) {
rq = new UpdateEnvironmentRequest();
rq.setEnvironmentName(environment.getEnvironmentName());
rq.setOptionSettings(Arrays.asList(setting));
return rq;
}
}
return null;
}
public class UpdateEnvironmentAndRefreshLayoutJob extends Job {
private Environment environment;
private UpdateEnvironmentRequest request;
/**
* @param name
*/
public UpdateEnvironmentAndRefreshLayoutJob(Environment environment, UpdateEnvironmentRequest request) {
super("Updating environment " + request.getEnvironmentName());
this.environment = environment;
this.request = request;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()).getElasticBeanstalkClientByEndpoint(
environment.getRegionEndpoint());
client.updateEnvironment(request);
} catch (Exception e) {
return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage(), e);
} finally {
// Guarantee the layout get redrawn.
parentEditor.refresh(null);
}
return Status.OK_STATUS;
}
}
}
| 7,418 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/ScalingTriggerConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Human readable editor section for scaling trigger configuration
*/
public class ScalingTriggerConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("MeasureName", "Trigger Measurement");
humanReadableNames.put("Statistic", "Trigger Statistic");
humanReadableNames.put("Unit", "Unit of Measurement");
humanReadableNames.put("Period", "Measurement Period (minutes)");
humanReadableNames.put("BreachDuration", "Breach Duration (minutes)");
humanReadableNames.put("UpperThreshold", "Upper Threshold");
humanReadableNames.put("UpperBreachScaleIncrement", "Scale-up Increment");
humanReadableNames.put("LowerThreshold", "Lower Threshold");
humanReadableNames.put("LowerBreachScaleIncrement", "Scale-down Increment");
}
private static final String[] fieldOrder = new String[] { "MeasureName", "Statistic", "Unit", "Period",
"BreachDuration", "UpperThreshold", "UpperBreachScaleIncrement", "LowerThreshold",
"LowerBreachScaleIncrement" };
public ScalingTriggerConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Section getSection(Composite parent) {
Section section = toolkit.createSection(parent, SWT.NONE);
return section;
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Scaling Trigger";
}
@Override
protected String getSectionDescription() {
return "";
}
} | 7,419 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/BasicEnvironmentConfigEditorPart.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.forms.ManagedForm;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.wst.server.ui.internal.ImageResource;
import com.amazonaws.eclipse.core.telemetry.AwsToolkitMetricType;
import com.amazonaws.eclipse.ec2.Ec2Plugin;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.AbstractEnvironmentConfigEditorPart;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.RefreshListener;
import com.amazonaws.eclipse.explorer.AwsAction;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Basic environment configuration editor with reduced options and
* human-readable names.
*/
@SuppressWarnings({ "unchecked", "restriction" })
public class BasicEnvironmentConfigEditorPart extends AbstractEnvironmentConfigEditorPart implements
RefreshListener {
/*
* Map of which namespace controls need to be grouped into which editor.
*/
private final Map<Collection<String>, HumanReadableConfigEditorSection> editorSectionsByNamespace = new HashMap<>();
private static final Collection<String> serverNamespaces = new HashSet<>();
private static final Collection<String> loadBalancingNamespaces = new HashSet<>();
private static final Collection<String> healthCheckNamespaces = new HashSet<>();
private static final Collection<String> sessionsNamespaces = new HashSet<>();
private static final Collection<String> autoscalingNamespaces = new HashSet<>();
private static final Collection<String> triggerNamespaces = new HashSet<>();
private static final Collection<String> notificationsNamespaces = new HashSet<>();
private static final Collection<String> containerNamespaces = new HashSet<>();
private static final Collection<String> applicationEnvironmentNamespaces = new HashSet<>();
private static final Collection<String> environmentNamespaces = new HashSet<>();
private static final Collection<String> rollingDeploymentsNamespaces = new HashSet<>();
static {
serverNamespaces.add(ConfigurationOptionConstants.LAUNCHCONFIGURATION);
loadBalancingNamespaces.add(ConfigurationOptionConstants.LOADBALANCER);
healthCheckNamespaces.add(ConfigurationOptionConstants.HEALTHCHECK);
healthCheckNamespaces.add(ConfigurationOptionConstants.APPLICATION);
sessionsNamespaces.add(ConfigurationOptionConstants.POLICIES);
autoscalingNamespaces.add(ConfigurationOptionConstants.ASG);
triggerNamespaces.add(ConfigurationOptionConstants.TRIGGER);
notificationsNamespaces.add(ConfigurationOptionConstants.SNS_TOPICS);
containerNamespaces.add(ConfigurationOptionConstants.JVMOPTIONS);
containerNamespaces.add(ConfigurationOptionConstants.HOSTMANAGER);
applicationEnvironmentNamespaces.add(ConfigurationOptionConstants.ENVIRONMENT);
environmentNamespaces.add(ConfigurationOptionConstants.ENVIRONMENT_TYPE);
rollingDeploymentsNamespaces.add(ConfigurationOptionConstants.COMMAND);
}
private static final Collection<NamespaceGroup> sectionGroups = new ArrayList<>();
static {
sectionGroups.add(new NamespaceGroup("Server", Position.LEFT, serverNamespaces));
sectionGroups.add(new NamespaceGroup("Load Balancing", Position.LEFT, loadBalancingNamespaces, healthCheckNamespaces, sessionsNamespaces));
sectionGroups.add(new NamespaceGroup("Environment Type", Position.RIGHT, environmentNamespaces));
sectionGroups.add(new NamespaceGroup("Rolling Deployments", Position.RIGHT, rollingDeploymentsNamespaces));
sectionGroups.add(new NamespaceGroup("Auto Scaling", Position.RIGHT, autoscalingNamespaces, triggerNamespaces));
sectionGroups.add(new NamespaceGroup("Notifications", Position.RIGHT, notificationsNamespaces));
sectionGroups.add(new NamespaceGroup("Container", Position.CENTER, containerNamespaces, applicationEnvironmentNamespaces));
}
private static final Collection<String>[] sectionOrder = new Collection[] {
serverNamespaces,
loadBalancingNamespaces,healthCheckNamespaces, sessionsNamespaces,
environmentNamespaces,
rollingDeploymentsNamespaces,
autoscalingNamespaces, triggerNamespaces,
notificationsNamespaces,
containerNamespaces, applicationEnvironmentNamespaces, };
/**
* Each time we create our control section, we create one composite for each
* group of namespaces.
*/
private Map<String, Composite> compositesByNamespace;
public BasicEnvironmentConfigEditorPart() {
super();
}
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
editorSectionsByNamespace.put(serverNamespaces, new ServerConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(loadBalancingNamespaces, new LoadBalancingConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(healthCheckNamespaces, new HealthCheckConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(sessionsNamespaces, new SessionConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(autoscalingNamespaces, new AutoScalingConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(triggerNamespaces, new ScalingTriggerConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(notificationsNamespaces, new NotificationsConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(containerNamespaces, new ContainerConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(applicationEnvironmentNamespaces, new EnvironmentPropertiesConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(environmentNamespaces, new EnvironmentTypeConfigEditorSection(this, model, environment, bindingContext));
editorSectionsByNamespace.put(rollingDeploymentsNamespaces, new RollingDeploymentsConfigEditorSection(this, model, environment, bindingContext));
model.addRefreshListener(this);
}
@Override
public void createPartControl(Composite parent) {
managedForm = new ManagedForm(parent);
setManagedForm(managedForm);
ScrolledForm form = managedForm.getForm();
FormToolkit toolkit = managedForm.getToolkit();
toolkit.decorateFormHeading(form.getForm());
form.setText("Environment Configuration");
form.setImage(ImageResource.getImage(ImageResource.IMG_SERVER));
form.getBody().setLayout(new GridLayout());
Composite columnComp = toolkit.createComposite(form.getBody());
GridLayout layout = new GridLayout();
layout.numColumns = 2;
layout.horizontalSpacing = 10;
columnComp.setLayout(layout);
columnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Label restartNotice = toolkit.createLabel(columnComp, RESTART_NOTICE, SWT.WRAP);
GridData layoutData = new GridData(SWT.FILL, SWT.TOP, false, false);
layoutData.horizontalSpan = 2;
layoutData.widthHint = 600; // required for wrapping
restartNotice.setLayoutData(layoutData);
// left column
Composite leftColumnComp = toolkit.createComposite(columnComp);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 0;
leftColumnComp.setLayout(layout);
leftColumnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
// right column
Composite rightColumnComp = toolkit.createComposite(columnComp);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 0;
rightColumnComp.setLayout(layout);
rightColumnComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
// "center" column -- composite below the two above, spanning both columns
Composite centerColumnComp = toolkit.createComposite(columnComp);
layout = new GridLayout();
layout.marginHeight = 0;
layout.marginWidth = 0;
layout.verticalSpacing = 10;
layout.horizontalSpacing = 0;
centerColumnComp.setLayout(layout);
layoutData = new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL);
layoutData.horizontalSpan = 2;
centerColumnComp.setLayoutData(layoutData);
compositesByNamespace = new HashMap<>();
for ( NamespaceGroup namespaceGroup : sectionGroups ) {
Composite parentComp = null;
switch (namespaceGroup.getPosition()) {
case LEFT:
parentComp = leftColumnComp;
break;
case RIGHT:
parentComp = rightColumnComp;
break;
case CENTER:
parentComp = centerColumnComp;
break;
}
Section section = toolkit.createSection(parentComp, ExpandableComposite.TWISTIE | ExpandableComposite.EXPANDED
| ExpandableComposite.TITLE_BAR | ExpandableComposite.FOCUS_TITLE);
section.setText(namespaceGroup.getName());
layout = new GridLayout();
layout.numColumns = 1;
layout.verticalSpacing = 0;
section.setLayout(layout);
section.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
Composite comp = toolkit.createComposite(section);
layout = new GridLayout();
int numColumns = 0;
switch (namespaceGroup.getPosition()) {
case LEFT:
case RIGHT:
numColumns = 1;
break;
case CENTER:
numColumns = 2;
break;
}
layout.numColumns = numColumns;
layout.verticalSpacing = 0;
comp.setLayout(layout);
comp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL));
section.setClient(comp);
for (String namespace : namespaceGroup.getIncludedNamespaces()) {
compositesByNamespace.put(namespace, comp);
}
}
refreshAction = new AwsAction(
AwsToolkitMetricType.EXPLORER_BEANSTALK_REFRESH_ENVIRONMENT_EDITOR,
"Refresh", SWT.None) {
@Override
public ImageDescriptor getImageDescriptor() {
return Ec2Plugin.getDefault().getImageRegistry().getDescriptor("refresh");
}
@Override
protected void doRun() {
refresh(null);
actionFinished();
}
};
managedForm.getForm().getToolBarManager().add(refreshAction);
managedForm.getForm().getToolBarManager().update(true);
managedForm.reflow(true);
}
/**
* Refreshes the editor with the latest values
*/
@Override
public void refresh(String templateName) {
model.refresh(templateName);
}
@Override
public void destroyOldLayouts() {
// Not allow refresh action during the destroying of controls
refreshAction.setEnabled(false);
for (Composite composite : compositesByNamespace.values()) {
for (Control control : composite.getChildren()) {
control.dispose();
}
}
refreshAction.setEnabled(true);
}
private List<HumanReadableConfigEditorSection> createEditorSections(List<ConfigurationOptionDescription> options) {
List<HumanReadableConfigEditorSection> editorSections = new ArrayList<>();
for ( Collection<String> namespaces : sectionOrder ) {
ArrayList<ConfigurationOptionDescription> optionsInEditorSection = new ArrayList<>();
for ( ConfigurationOptionDescription o : options ) {
if ( namespaces.contains(o.getNamespace()) && editorSectionsByNamespace.containsKey(namespaces) ) {
if ( optionsInEditorSection.isEmpty() ) {
HumanReadableConfigEditorSection editor = editorSectionsByNamespace.get(namespaces);
editor.setOptions(optionsInEditorSection);
editorSections.add(editor);
editor.setParentComposite(compositesByNamespace.get(o.getNamespace()));
}
optionsInEditorSection.add(o);
}
}
}
return editorSections;
}
@Override
public void refreshStarted() {
getEditorSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
managedForm.getForm().setText(getTitle() + " (loading...)");
}
});
}
@Override
public void refreshFinished() {
getEditorSite().getShell().getDisplay().syncExec(new Runnable() {
@Override
public void run() {
if ( compositesByNamespace.values().iterator().next().getChildren().length == 0 ) {
final List<HumanReadableConfigEditorSection> editorSections = createEditorSections(model
.getOptions());
for ( HumanReadableConfigEditorSection section : editorSections ) {
// Skip creating "Auto Scaling" and "Rolling Deployments" sections if the
// environment is deployed to single-instance
if (section instanceof RollingDeploymentsConfigEditorSection ||
section instanceof AutoScalingConfigEditorSection) {
Object envTypeValue = model.getEntry(
new ConfigurationOptionDescription()
.withNamespace(ConfigurationOptionConstants.ENVIRONMENT_TYPE)
.withName("EnvironmentType"));
if ("SingleInstance".equals(envTypeValue)) {
continue;
}
}
section.setServerEditorPart(BasicEnvironmentConfigEditorPart.this);
section.init(getEditorSite(), getEditorInput());
section.createSection(section.getParentComposite());
managedForm.reflow(true);
}
}
dirty = false;
BasicEnvironmentConfigEditorPart.this.doSaveAs();
managedForm.getForm().setText(getTitle());
}
});
}
@Override
public void refreshError(Throwable e) {
ElasticBeanstalkPlugin.getDefault().getLog().log(new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, "Error creating editor", e));
}
private static enum Position {
LEFT, RIGHT, CENTER
};
/**
* Simple data class to avoid too many levels of collection nesting.
*/
private static final class NamespaceGroup {
private final Collection<String> includedNamespaces;
final String name;
final Position position;
public NamespaceGroup(String name, Position pos, Collection<String>... namespaces) {
this.name = name;
includedNamespaces = new HashSet<>();
for ( Collection<String> namespace : namespaces ) {
includedNamespaces.addAll(namespace);
}
position = pos;
}
public String getName() {
return name;
}
public Collection<String> getIncludedNamespaces() {
return includedNamespaces;
}
public Position getPosition() {
return position;
}
}
}
| 7,420 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/ServerConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
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.databinding.observable.value.WritableValue;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairComposite;
import com.amazonaws.eclipse.ec2.ui.keypair.KeyPairRefreshListener;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
import com.amazonaws.services.ec2.model.KeyPairInfo;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionDescription;
/**
* Environment config editor section for setting "Server" properties, roughly
* corresponding to the aws:autoscaling:launchconfiguration namespace.
*/
public class ServerConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("EC2KeyName", "Existing Key Pair");
humanReadableNames.put("SecurityGroups", "EC2 Security Groups");
humanReadableNames.put("InstanceType", "EC2 Instance Type");
humanReadableNames.put("MonitoringInterval", "Monitoring Interval");
humanReadableNames.put("ImageId", "Custom AMI ID");
}
private static final String[] fieldOrder = new String[] { "InstanceType", "SecurityGroups", "EC2KeyName",
"MonitoringInterval", "ImageId" };
public ServerConfigEditorSection(BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart,
EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Server";
}
@Override
protected String getSectionDescription() {
return "These settings allow you to control your environment's servers and enable login.";
}
@Override
protected Section getSection(Composite parent) {
return toolkit.createSection(parent, Section.EXPANDED | Section.DESCRIPTION | Section.NO_TITLE);
}
@Override
protected void createSectionControls(Composite composite) {
for ( String field : getFieldOrder() ) {
for ( ConfigurationOptionDescription o : options ) {
if ( field.equals(o.getName()) ) {
if ( field.equals("EC2KeyName") ) {
createKeyPairControl(composite, o);
} else {
createOptionControl(composite, o);
}
}
}
}
}
/**
* Creates the controls to allow the user to select a key pair with a gui.
*/
private void createKeyPairControl(Composite parent, ConfigurationOptionDescription option) {
Label label = createLabel(toolkit, parent, option);
label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false));
final KeyPairComposite keyPairWidget = new KeyPairComposite(parent, this.environment.getAccountId());
GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, false);
layoutData.widthHint = 200;
layoutData.heightHint = 200;
keyPairWidget.setLayoutData(layoutData);
final IObservableValue modelv = model.observeEntry(option);
final IChangeListener listener = new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
for ( int i = 0; i < keyPairWidget.getViewer().getTree().getItemCount(); i++ ) {
KeyPairInfo keyPair = (KeyPairInfo) keyPairWidget.getViewer().getTree().getItem(i).getData();
if ( keyPair.getKeyName().equals(modelv.getValue()) ) {
keyPairWidget.getViewer().getTree().select(keyPairWidget.getViewer().getTree().getItem(i));
// Selection listeners aren't notified when we
// select like this, so fire an event.
keyPairWidget.getViewer().getTree().notifyListeners(SWT.Selection, null);
return;
}
}
keyPairWidget.getViewer().getTree().deselectAll();
}
};
modelv.addChangeListener(listener);
/*
* The table is initially empty, so we need to add a hook to fire our
* change listener when it gets refreshed in order to correctly select
* the current key pair.
*/
keyPairWidget.getKeyPairSelectionTable().addRefreshListener(new KeyPairRefreshListener() {
@Override
public void keyPairsRefreshed() {
listener.handleChange(null);
}
});
final IObservableValue keyPairSelection = new WritableValue();
keyPairWidget.getKeyPairSelectionTable().addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (keyPairWidget.getKeyPairSelectionTable().getSelectedKeyPair() == null)
keyPairSelection.setValue("");
else
keyPairSelection.setValue(keyPairWidget.getKeyPairSelectionTable().getSelectedKeyPair().getKeyName());
}
});
bindingContext.bindValue(keyPairSelection, modelv,
new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE),
new UpdateValueStrategy(UpdateValueStrategy.POLICY_UPDATE));
}
}
| 7,421 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/SessionConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Human readable editor section for editing loadbalancer session properties.
*/
public class SessionConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("Stickiness Cookie Expiration", "Cookie Expiration Period (seconds)");
humanReadableNames.put("Stickiness Policy", "Enable Session Stickiness");
}
private static final String[] fieldOrder = new String[] {
"Stickiness Policy", "Stickiness Cookie Expiration"
};
public SessionConfigEditorSection(BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Sessions";
}
@Override
protected String getSectionDescription() {
return "These settings allow you to control how your load balancer handles session cookies.";
}
}
| 7,422 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/server/ui/configEditor/basic/AutoScalingConfigEditorSection.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.elasticbeanstalk.server.ui.configEditor.basic;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.server.ui.configEditor.EnvironmentConfigDataModel;
/**
* Human readable editor section to configure autoscaling parameters.
*/
public class AutoScalingConfigEditorSection extends HumanReadableConfigEditorSection {
private static final Map<String, String> humanReadableNames = new HashMap<>();
static {
humanReadableNames.put("MinSize", "Minimum Instance Count");
humanReadableNames.put("MaxSize", "Maximum Instance Count");
humanReadableNames.put("Availability Zones", "Availability Zones");
humanReadableNames.put("Cooldown", "Scaling Cooldown Time (seconds)");
}
private static final String[] fieldOrder = new String[] { "MinSize", "MaxSize", "Availability Zones", "Cooldown", };
public AutoScalingConfigEditorSection(
BasicEnvironmentConfigEditorPart basicEnvironmentConfigurationEditorPart, EnvironmentConfigDataModel model, Environment environment, DataBindingContext bindingContext) {
super(basicEnvironmentConfigurationEditorPart, model, environment, bindingContext);
}
@Override
protected Map<String, String> getHumanReadableNames() {
return humanReadableNames;
}
@Override
protected String[] getFieldOrder() {
return fieldOrder;
}
@Override
protected String getSectionName() {
return "Auto Scaling";
}
@Override
protected String getSectionDescription() {
return "Auto-scaling automatically launches or terminates EC2 "
+ "instances based on defined metrics and thresholds called triggers. "
+ "Auto-scaling will also launch a new EC2 instance in the event of a "
+ "failure. These settings allow you to control auto-scaling behavior.";
}
@Override
protected Section getSection(Composite parent) {
Section section = toolkit.createSection(parent, Section.DESCRIPTION | Section.NO_TITLE);
return section;
}
}
| 7,423 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/ExportConfigurationJob.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.elasticbeanstalk.jobs;
import java.util.Collection;
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 com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationOptionSetting;
import com.amazonaws.services.elasticbeanstalk.model.CreateConfigurationTemplateRequest;
import com.amazonaws.services.elasticbeanstalk.model.UpdateConfigurationTemplateRequest;
/**
* Job to export an environment configuration to a template
*/
public final class ExportConfigurationJob extends Job {
private final Environment environment;
private final String templateDescription;
private final Collection<ConfigurationOptionSetting> createConfigurationOptions;
private final String templateName;
private final boolean isCreatingNew;
/**
* @param environment
* The server environment
* @param templateName
* The name of the template
* @param templateDescription
* An optional description of the template
* @param createConfigurationOptions
* The full set of options that define the template
* @param isCreatingNew
* Whether to create a new template or update an existing one
*/
public ExportConfigurationJob(Environment environment, String templateName, String templateDescription,
Collection<ConfigurationOptionSetting> createConfigurationOptions, boolean isCreatingNew) {
super("Exporting configuration template");
this.environment = environment;
this.templateDescription = templateDescription;
this.createConfigurationOptions = createConfigurationOptions;
this.templateName = templateName;
this.isCreatingNew = isCreatingNew;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId())
.getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
if ( isCreatingNew ) {
client.createConfigurationTemplate(new CreateConfigurationTemplateRequest()
.withApplicationName(environment.getApplicationName()).withDescription(templateDescription)
.withTemplateName(templateName).withOptionSettings(createConfigurationOptions));
} else {
client.updateConfigurationTemplate(new UpdateConfigurationTemplateRequest()
.withApplicationName(environment.getApplicationName()).withDescription(templateDescription)
.withTemplateName(templateName).withOptionSettings(createConfigurationOptions));
}
} catch ( Exception e ) {
return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage(), e);
}
return Status.OK_STATUS;
}
}
| 7,424 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/TerminateEnvironmentJob.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.jobs;
import java.util.List;
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.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.IProgressConstants;
import org.eclipse.wst.server.core.IServer;
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.EnvironmentBehavior;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.services.elasticbeanstalk.model.TerminateEnvironmentRequest;
public class TerminateEnvironmentJob extends Job {
private final Environment environment;
public TerminateEnvironmentJob(Environment environment) {
super("Stopping AWS Elastic Beanstalk environment " + environment.getEnvironmentName());
this.environment = environment;
setProperty(IProgressConstants.ICON_PROPERTY,
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON));
setUser(true);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()).getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
EnvironmentBehavior behavior = (EnvironmentBehavior)environment.getServer().loadAdapter(EnvironmentBehavior.class, monitor);
final DialogHolder dialogHolder = new DialogHolder();
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(),
"Confirm environment termination", AwsToolkitCore.getDefault().getImageRegistry()
.get(AwsToolkitCore.IMAGE_AWS_ICON), "Are you sure you want to terminate the environment "
+ environment.getEnvironmentName()
+ "? All EC2 instances in the environment will be terminated and you will be unable to use "
+ "this environment again until you have recreated it.", MessageDialog.QUESTION_WITH_CANCEL,
new String[] { "OK", "Cancel" }, 1);
dialogHolder.dialog = dialog;
dialog.open();
}
});
if ( dialogHolder.dialog.getReturnCode() != 0 ) {
behavior.updateServerState(IServer.STATE_STOPPED);
return Status.OK_STATUS;
}
try {
if (doesEnvironmentExist()) {
client.terminateEnvironment(new TerminateEnvironmentRequest().withEnvironmentName(environment.getEnvironmentName()));
}
// It's more correct to set the state to stopping, rather than stopped immediately,
// but if we set it to stopping, WTP will block workspace actions waiting for the
// environment's state to get updated to stopped. To prevent this, we stop immediately.
behavior.updateServerState(IServer.STATE_STOPPED);
return Status.OK_STATUS;
} catch (AmazonClientException ace) {
return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unable to terminate environment " + environment.getEnvironmentName() + " : " + ace.getMessage(), ace);
}
}
private boolean doesEnvironmentExist() throws AmazonClientException, AmazonServiceException {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()).getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
List<EnvironmentDescription> environments = client.describeEnvironments().getEnvironments();
for (EnvironmentDescription env : environments) {
if (env.getEnvironmentName().equals(environment.getEnvironmentName())) {
return true;
}
}
return false;
}
private static final class DialogHolder {
private MessageDialog dialog;
}
}
| 7,425 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/LoadVpcsJob.java | /*
* Copyright 2016 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.elasticbeanstalk.jobs;
import java.util.List;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.model.Vpc;
public final class LoadVpcsJob extends LoadResourcesJob<Vpc> {
private final AmazonEC2 ec2;
public LoadVpcsJob(Region region, LoadResourcesCallback<Vpc> callback) {
super("Load Vpcs", callback);
ec2 = AwsToolkitCore.getClientFactory().getEC2ClientByEndpoint(
region.getServiceEndpoint(ServiceAbbreviations.EC2));
}
@Override
protected List<Vpc> getAllResources() {
return ec2.describeVpcs().getVpcs();
}
@Override
protected boolean isInsufficientPermissions(Exception e) {
// TODO we don't tell apart InsufficientPermissionException and other Exceptions for now.
return false;
}
@Override
protected String getOnFailureMessage() {
return "Unable to query AWS EC2 for the VPCs";
}
}
| 7,426 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/UpdateEnvironmentConfigurationJob.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.elasticbeanstalk.jobs;
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 com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.UpdateEnvironmentRequest;
public class UpdateEnvironmentConfigurationJob extends Job {
private Environment environment;
private UpdateEnvironmentRequest request;
/**
* @param name
*/
public UpdateEnvironmentConfigurationJob(Environment environment, UpdateEnvironmentRequest request) {
super("Updating environment " + request.getEnvironmentName());
this.environment = environment;
this.request = request;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.
* IProgressMonitor)
*/
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()).getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
client.updateEnvironment(request);
} catch ( Exception e ) {
return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, e.getMessage(), e);
}
return Status.OK_STATUS;
}
}
| 7,427 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/LoadResourcesCallback.java | /*
* Copyright 2016 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.elasticbeanstalk.jobs;
import java.util.List;
/**
* This interface is used as a callback when loading a list of
* resources such as IAM Roles, or VPCs (Virtual Private Cloud).
*/
public interface LoadResourcesCallback<Resource> {
/**
* Called when resources are successfully loaded from service
*
* @param resources
* List of resources in user's account
*/
void onSuccess(List<Resource> resources);
/**
* Called when we are unable to get the list of resources in the user's account for reasons
* other then a permissions issue.
*/
void onFailure();
/**
* Called when the currently configured user does not have permissions to list IAM roles.
*/
void onInsufficientPermissions();
}
| 7,428 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/LoadResourcesJob.java | /*
* Copyright 2016 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.elasticbeanstalk.jobs;
import java.util.List;
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 com.amazonaws.eclipse.core.util.ValidationUtils;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
/**
* A Job that load specified resources such as IAM Roles, VPCs, Subnets etc, and use
* corresponding callback to handle different situations.
*/
public abstract class LoadResourcesJob<Resource> extends Job {
protected final LoadResourcesCallback<Resource> callback;
public LoadResourcesJob(String name, LoadResourcesCallback<Resource> callback) {
super(name);
this.callback = ValidationUtils.validateNonNull(callback, "Callback");
}
@Override
protected IStatus run(IProgressMonitor monitor) {
List<Resource> resources;
try {
resources = getAllResources();
} catch (Exception e) {
return handleException(e);
}
// Callback is invoked outside the try block so that any exception it throws will fail the job.
callback.onSuccess(resources);
return Status.OK_STATUS;
}
private IStatus handleException(Exception e) {
if (isInsufficientPermissions(e)) {
callback.onInsufficientPermissions();
return Status.OK_STATUS;
} else {
callback.onFailure();
Status status = new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
getOnFailureMessage(), e);
ElasticBeanstalkPlugin.getDefault().getLog().log(status);
return status;
}
}
// Load all the resources
protected abstract List<Resource> getAllResources();
// Whether this exception is due to lack of permission
protected abstract boolean isInsufficientPermissions(Exception e);
// The error message that will be shown in the log when failed to load the resources.
protected abstract String getOnFailureMessage();
}
| 7,429 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/UpdateEnvironmentJob.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.jobs;
import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
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.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.jdt.launching.IVMConnector;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.IProgressConstants;
import org.eclipse.wst.server.core.IModule;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.ui.internal.LaunchClientJob;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ConfigurationOptionConstants;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkHttpLaunchable;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkLaunchableAdapter;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPublishingUtils;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.EnvironmentBehavior;
import com.amazonaws.eclipse.elasticbeanstalk.git.AWSGitPushCommand;
import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions;
import com.amazonaws.eclipse.elasticbeanstalk.util.PollForEvent;
import com.amazonaws.eclipse.elasticbeanstalk.util.PollForEvent.Event;
import com.amazonaws.eclipse.elasticbeanstalk.util.PollForEvent.Interval;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.util.StringUtils;
public class UpdateEnvironmentJob extends Job {
private IPath exportedWar;
private IModule moduleToPublish;
private final Environment environment;
private Job launchClientJob;
private String versionLabel;
private String debugInstanceId;
private final IServer server;
public UpdateEnvironmentJob(Environment environment, IServer server) {
super("Updating AWS Elastic Beanstalk environment: " + environment.getEnvironmentName());
this.environment = environment;
this.server = server;
ImageDescriptor imageDescriptor = AwsToolkitCore.getDefault().getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON);
setProperty(IProgressConstants.ICON_PROPERTY, imageDescriptor);
setUser(true);
}
public void setModuleToPublish(IModule moduleToPublish, IPath exportedWar) {
this.moduleToPublish = moduleToPublish;
this.exportedWar = exportedWar;
}
public IModule getModuleToPublish() {
return this.moduleToPublish;
}
public boolean needsToDeployNewVersion() {
return (exportedWar != null);
}
/**
* Ensure the launch client job has been canceled so that the internal browser isn't opened with
* the user's application
*/
private void forceCancelLaunchClientJob(EnvironmentBehavior behavior) {
long startTime = System.currentTimeMillis();
while (launchClientJob == null && (System.currentTimeMillis() - startTime) < 1000 * 60) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
cancelLaunchClientJob();
}
behavior.updateServerState(IServer.STATE_UNKNOWN);
behavior.updateModuleState(moduleToPublish, IServer.STATE_UNKNOWN, IServer.PUBLISH_STATE_UNKNOWN);
}
// Try to delay the scheduling of the LaunchClientJob
// since use a scheduling rule to lock the server, which
// locks up if we try to save files deployed to that server.
private void cancelLaunchClientJob() {
if (launchClientJob != null) {
return;
}
launchClientJob = findLaunchClientJob();
if (launchClientJob != null) {
launchClientJob.cancel();
}
}
private Job findLaunchClientJob() {
// Try to delay the scheduling of the LaunchClientJob
// since use a scheduling rule to lock the server, which
// locks up if we try to save files deployed to that server.
Job[] jobs = Job.getJobManager().find(null);
for (Job job : jobs) {
if (job instanceof LaunchClientJob) {
if (((LaunchClientJob) job).getServer().getId().equals(environment.getServer().getId())) {
trace("Identified LaunchClientJob: " + job);
return job;
}
}
}
trace("Unable to find LaunchClientJob!");
return null;
}
@Override
protected IStatus run(IProgressMonitor monitor) {
cancelLaunchClientJob();
monitor.beginTask("Publishing to AWS Elastic Beanstalk", IProgressMonitor.UNKNOWN);
EnvironmentBehavior behavior = (EnvironmentBehavior) environment.getServer().loadAdapter(
EnvironmentBehavior.class, null);
if (needsToDeployNewVersion()) {
try {
behavior.updateServerState(IServer.STATE_STARTING);
ElasticBeanstalkPublishingUtils utils = new ElasticBeanstalkPublishingUtils(environment);
boolean doesEnvironmentExist = environment.doesEnvironmentExistInBeanstalk();
if (environment.getIncrementalDeployment()) {
doIncrementalDeployment(utils, doesEnvironmentExist);
} else {
doFullDeployment(monitor, utils);
}
waitForEnvironmentToBecomeAvailable(monitor, utils);
behavior.updateServerState(IServer.STATE_STARTED);
if (moduleToPublish != null) {
behavior.updateModuleState(moduleToPublish, IServer.STATE_STARTED, IServer.PUBLISH_STATE_NONE);
}
if (server.getMode().equals(ILaunchManager.DEBUG_MODE)) {
connectDebugger(monitor);
}
} catch (CoreException e) {
forceCancelLaunchClientJob(behavior);
return e.getStatus();
}
}
updateLaunchableHost(monitor);
IsCnameAvailable.waitForCnameToBeAvailable(environment, monitor);
if (!monitor.isCanceled() && launchClientJob != null
&& ConfigurationOptionConstants.WEB_SERVER.equals(environment.getEnvironmentTier())) {
launchClientJob.schedule();
}
return Status.OK_STATUS;
}
/**
* Update the URL of the client launch job (in a roundabout manner) to point to the correct
* endpoint, depending on whether we intend to connect to the environment CNAME or a particular
* instance
*/
private void updateLaunchableHost(IProgressMonitor monitor) {
ElasticBeanstalkHttpLaunchable launchable = ElasticBeanstalkLaunchableAdapter.getLaunchable(server);
if (launchable != null) {
if (debugInstanceId != null && debugInstanceId.length() > 0) {
try {
launchable.setHost(getEc2InstanceHostname());
} catch (Exception e) {
ElasticBeanstalkPlugin.getDefault().logError("Failed to set hostname", e);
}
} else {
launchable.clearHost();
}
}
}
private void waitForEnvironmentToBecomeAvailable(IProgressMonitor monitor, ElasticBeanstalkPublishingUtils utils)
throws CoreException {
Runnable runnable = new Runnable() {
@Override
public void run() {
cancelLaunchClientJob();
}
};
utils.waitForEnvironmentToBecomeAvailable(moduleToPublish, new SubProgressMonitor(monitor, 20), runnable);
}
private void doIncrementalDeployment(ElasticBeanstalkPublishingUtils utils, boolean doesEnvironmentExist)
throws CoreException {
AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountManager()
.getAccountInfo(environment.getAccountId());
AWSGitPushCommand pushCommand = new AWSGitPushCommand(getPrivateGitRepoLocation(environment),
exportedWar.toFile(), environment, new BasicAWSCredentials(accountInfo.getAccessKey(),
accountInfo.getSecretKey()));
if (doesEnvironmentExist) {
/*
* If the environment already exists, then all we have to do is push through Git and
* it'll automatically create a new application version and kick off a deployment to the
* environment.
*/
pushCommand.execute();
} else {
/*
* If the environment doesn't exist yet, then we need to create the application and push
* a new version with Git, then grab the ID of that new version and call the Beanstalk
* CreateEnvironment API.
*/
utils.createNewApplication(environment.getApplicationName(), environment.getApplicationDescription());
pushCommand.skipEnvironmentDeployment(true);
pushCommand.execute();
try {
versionLabel = utils.getLatestApplicationVersion(environment.getApplicationName());
utils.createNewEnvironment(versionLabel);
} catch (AmazonClientException ace) {
throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unable to create new environment: " + ace.getMessage(), ace));
}
}
}
private void doFullDeployment(IProgressMonitor monitor, ElasticBeanstalkPublishingUtils utils) throws CoreException {
if (versionLabel == null) {
versionLabel = UUID.randomUUID().toString();
}
utils.publishApplicationToElasticBeanstalk(exportedWar, versionLabel, new SubProgressMonitor(monitor, 20));
}
public void setVersionLabel(String versionLabel) {
this.versionLabel = versionLabel;
}
public void setDebugInstanceId(String debugInstanceId) {
this.debugInstanceId = debugInstanceId;
}
private File getPrivateGitRepoLocation(Environment environment) {
String accountId = environment.getAccountId();
String environmentName = environment.getEnvironmentName();
IPath stateLocation = Platform.getStateLocation(ElasticBeanstalkPlugin.getDefault().getBundle());
File gitReposDir = new File(stateLocation.toFile(), "git");
return new File(gitReposDir, accountId + "-" + environmentName);
}
/**
* Opens up a remote debugger connection based on the specified launch, host, and port and
* optionally reports progress through a specified progress monitor.
*
* @param monitor
* An optional progress monitor if progress reporting is desired.
* @throws CoreException
* If any problems were encountered setting up the remote debugger connection to the
* specified host.
*/
private void connectDebugger(IProgressMonitor monitor) throws CoreException {
ILaunch launch = findLaunch();
if (launch == null) {
return;
}
try {
List<ConfigurationSettingsDescription> settings = environment.getCurrentSettings();
String debugPort = Environment.getDebugPort(settings);
if (!confirmSecurityGroupIngress(debugPort, settings)) {
return;
}
IVMConnector debuggerConnector = JavaRuntime.getDefaultVMConnector();
Map<String, String> arguments = new HashMap<>();
arguments.put("timeout", "60000");
arguments.put("hostname", getEc2InstanceHostname());
arguments.put("port", debugPort);
debuggerConnector.connect(arguments, monitor, launch);
} catch (Exception e) {
ElasticBeanstalkPlugin.getDefault().logError("Unable to connect debugger: " + e.getMessage(), e);
}
}
/**
* Confirms that the security group of the environment allows ingress on the debug port given,
* prompting the user for permission to open it if not.
*/
private boolean confirmSecurityGroupIngress(String debugPort, List<ConfigurationSettingsDescription> settings) {
int debugPortInt = Integer.parseInt(debugPort);
String securityGroup = Environment.getSecurityGroup(settings);
if (environment.isIngressAllowed(debugPortInt, settings)) {
return true;
}
// Prompt the user for security group ingress -- this is an edge case to
// cover races only. In almost all cases, the user should have been
// prompted for this information much earlier.
final DebugPortDialog dialog = new DebugPortDialog(securityGroup, debugPort);
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
dialog.openDialog();
}
});
if (dialog.result == 0) {
environment.openSecurityGroupPort(debugPortInt, securityGroup);
return true;
} else {
return false;
}
}
/**
* Simple dialog to confirm the opening of a port on a security group.
*/
private static class DebugPortDialog {
private int result;
private final String debugPort;
private final String securityGroup;
public DebugPortDialog(String securityGroup, String debugPort) {
super();
this.securityGroup = securityGroup;
this.debugPort = debugPort;
}
private void openDialog() {
MessageDialog dialog = new MessageDialog(Display.getDefault().getActiveShell(),
"Authorize security group ingress?", AwsToolkitCore.getDefault().getImageRegistry()
.get(AwsToolkitCore.IMAGE_AWS_ICON),
"To connect the remote debugger, you will need to allow TCP ingress on port " + debugPort
+ " for your EC2 security group " + securityGroup + ". Continue?", MessageDialog.WARNING,
new String[] { "Continue", "Abort" }, 0);
result = dialog.open();
}
}
/**
* Returns the public dns name of the instance in the environment to connect the remote debugger
* to.
*/
private String getEc2InstanceHostname() {
String instanceId = debugInstanceId;
// For some launches, we won't know the EC2 instance ID until this point.
if (instanceId == null || instanceId.length() == 0) {
instanceId = environment.getEC2InstanceIds().iterator().next();
}
DescribeInstancesResult describeInstances = environment.getEc2Client().describeInstances(
new DescribeInstancesRequest().withInstanceIds(instanceId));
if (describeInstances.getReservations().isEmpty()
|| describeInstances.getReservations().get(0).getInstances().isEmpty()) {
return null;
}
return describeInstances.getReservations().get(0).getInstances().get(0).getPublicDnsName();
}
/**
* Returns the debug launch object corresponding to this update operation, or null if no such
* launch exists.
*/
private ILaunch findLaunch() throws CoreException {
ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
for (ILaunch launch : manager.getLaunches()) {
// TODO: figure out a more correct way of doing this
if (launch.getLaunchMode().equals(ILaunchManager.DEBUG_MODE)
&& launch.getLaunchConfiguration() != null
&& launch.getLaunchConfiguration().getAttribute("launchable-adapter-id", "")
.equals("com.amazonaws.eclipse.wtp.elasticbeanstalk.launchableAdapter")
&& launch.getLaunchConfiguration().getAttribute("module-artifact", "")
.contains(moduleToPublish.getName())) {
return launch;
}
}
return null;
}
private static class IsCnameAvailable implements Event {
private static final int MAX_NUMBER_OF_INTERVALS_TO_POLL = 10;
private static final Interval DEFAULT_POLLING_INTERVAL = new Interval(10, TimeUnit.SECONDS);
private final String cname;
public IsCnameAvailable(String cname) {
this.cname = cname;
}
@Override
public boolean hasEventOccurred() {
try {
InetAddress address = InetAddress.getByName(cname);
return !(address == null || StringUtils.isNullOrEmpty(address.getHostAddress()));
} catch (UnknownHostException e) {
return false;
}
}
public static void waitForCnameToBeAvailable(Environment environment, IProgressMonitor monitor) {
ElasticBeanstalkClientExtensions clientExt = new ElasticBeanstalkClientExtensions(environment.getClient());
EnvironmentDescription environmentDesc = clientExt.getEnvironmentDescription(environment
.getEnvironmentName());
IProgressMonitor cnameMonitor = startCnameMonitor(monitor);
new PollForEvent(getPollInterval(), MAX_NUMBER_OF_INTERVALS_TO_POLL).poll(new IsCnameAvailable(
environmentDesc.getCNAME()));
cnameMonitor.done();
}
private static IProgressMonitor startCnameMonitor(IProgressMonitor monitor) {
final String taskName = "Waiting for environment's domain name to become available";
final IProgressMonitor cnameMonitor = new SubProgressMonitor(monitor, 1);
cnameMonitor.beginTask(taskName, 1);
cnameMonitor.setTaskName(taskName);
return cnameMonitor;
}
/**
* Try and use networkaddress.cache.negative.ttl if it's set, otherwise return default
* interval
*/
private static Interval getPollInterval() {
try {
final int dnsNegativeTtl = Integer.valueOf(System.getProperty("networkaddress.cache.negative.ttl"));
if (dnsNegativeTtl > 0) {
return new Interval(dnsNegativeTtl, TimeUnit.SECONDS);
} else {
return DEFAULT_POLLING_INTERVAL;
}
} catch (Exception e) {
return DEFAULT_POLLING_INTERVAL;
}
}
}
}
| 7,430 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/LoadIamRolesJob.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.elasticbeanstalk.jobs;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.diagnostic.utils.ServiceExceptionParser;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.ListRolesRequest;
import com.amazonaws.services.identitymanagement.model.ListRolesResult;
import com.amazonaws.services.identitymanagement.model.Role;
public final class LoadIamRolesJob extends LoadResourcesJob<Role> {
private final AmazonIdentityManagement iam = AwsToolkitCore.getClientFactory().getIAMClient();
public LoadIamRolesJob(LoadResourcesCallback<Role> callback) {
super("Load IAM Roles", callback);
}
@Override
protected List<Role> getAllResources() {
List<Role> roles = new ArrayList<>();
ListRolesResult result = null;
do {
ListRolesRequest request = new ListRolesRequest();
result = iam.listRoles(request);
roles.addAll(result.getRoles());
if (result.isTruncated()) {
request.setMarker(result.getMarker());
}
} while (result.isTruncated());
return roles;
}
@Override
protected boolean isInsufficientPermissions(Exception e) {
return ServiceExceptionParser.isOperationNotAllowedException(e);
}
@Override
protected String getOnFailureMessage() {
return "Unable to query AWS Identity and Access Management for available instance profiles";
}
} | 7,431 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/SyncEnvironmentsJob.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.jobs;
import static com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin.trace;
import java.util.List;
import java.util.Random;
import org.eclipse.core.runtime.CoreException;
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.ui.progress.IProgressConstants;
import org.eclipse.ui.statushandlers.StatusManager;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.IServerWorkingCopy;
import org.eclipse.wst.server.core.ServerCore;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.EnvironmentBehavior;
import com.amazonaws.eclipse.elasticbeanstalk.util.ElasticBeanstalkClientExtensions;
import com.amazonaws.services.elasticbeanstalk.model.ConfigurationSettingsDescription;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentDescription;
import com.amazonaws.services.elasticbeanstalk.model.EnvironmentStatus;
public class SyncEnvironmentsJob extends Job {
private static final int SHORT_DELAY = 1000 * 30;
private static final int LONG_DELAY = 1000 * 60 * 4;
private static final Random RANDOM = new Random();
private String previousErrorMessage;
public SyncEnvironmentsJob() {
super("Synchronizing AWS Elastic Beanstalk environments");
setProperty(IProgressConstants.ICON_PROPERTY,
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON));
setSystem(true);
setPriority(LONG);
setUser(false);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Syncing", IProgressMonitor.UNKNOWN);
trace("Syncing environment statuses");
boolean transitioningEnvironment = false;
Exception syncingError = null;
for (IServer server : ServerCore.getServers()) {
if (server.getServerType() == null) continue;
String id = server.getServerType().getId();
if (ElasticBeanstalkPlugin.SERVER_TYPE_IDS.contains(id)) {
convertLegacyServer(server, monitor);
Environment environment = (Environment)server.loadAdapter(Environment.class, monitor);
EnvironmentBehavior behavior = (EnvironmentBehavior)server.loadAdapter(EnvironmentBehavior.class, monitor);
monitor.setTaskName("Syncing environment " + environment.getEnvironmentName());
try {
trace("Syncing server: " + server.getName() + ", " + "environment: " + environment.getEnvironmentName());
transitioningEnvironment |= syncEnvironment(environment, behavior);
previousErrorMessage = null;
} catch (AmazonClientException ace) {
syncingError = ace;
}
}
}
if ( syncingError != null ) {
schedule(LONG_DELAY);
// Don't keep complaining about being unable to synchronize
if ( previousErrorMessage != null &&
previousErrorMessage.equals(syncingError.getMessage()) ) {
return Status.OK_STATUS;
}
previousErrorMessage = syncingError.getMessage();
return new Status(Status.WARNING, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unable to synchronize an environment", syncingError);
}
if (transitioningEnvironment) schedule(SHORT_DELAY + RANDOM.nextInt(5 * 1000));
else schedule(LONG_DELAY + RANDOM.nextInt(5 * 1000));
return Status.OK_STATUS;
}
/**
* Synchronizes the environment given with its AWS Elastic Beanstalk state and returns whether
* it should be considered in a "transitioning" state.
*/
private boolean syncEnvironment(Environment environment, EnvironmentBehavior behavior) {
ElasticBeanstalkClientExtensions clientExt = new ElasticBeanstalkClientExtensions(environment);
EnvironmentDescription environmentDescription = clientExt.getEnvironmentDescription(environment.getEnvironmentName());
List<ConfigurationSettingsDescription> settings = environment.getCurrentSettings();
behavior.updateServer(environmentDescription, settings);
if (environmentDescription == null) return false;
EnvironmentStatus environmentStatus = null;
try {
environmentStatus = EnvironmentStatus.fromValue(environmentDescription.getStatus());
} catch (IllegalArgumentException e) {
Status status = new Status(Status.INFO, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unknown environment status: " + environmentDescription.getStatus());
StatusManager.getManager().handle(status, StatusManager.LOG);
}
return (environmentStatus == EnvironmentStatus.Launching ||
environmentStatus == EnvironmentStatus.Updating ||
environmentStatus == EnvironmentStatus.Terminating);
}
/**
* We change the data model to save the server environment information. This
* function is used to convert the old data format to the new one.
*/
private void convertLegacyServer(IServer server, IProgressMonitor monitor) {
IServerWorkingCopy serverWorkingCopy = server.createWorkingCopy();
Environment env = (Environment) serverWorkingCopy.loadAdapter(Environment.class, monitor);
env.convertLegacyServer();
try {
serverWorkingCopy.save(true, monitor);
} catch (CoreException e) {
throw new AmazonClientException("Unable to synchronize with the beanstalk", e);
}
}
}
| 7,432 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/jobs/RestartEnvironmentJob.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.jobs;
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.ui.progress.IProgressConstants;
import org.eclipse.wst.server.core.IServer;
import com.amazonaws.AmazonClientException;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
import com.amazonaws.eclipse.elasticbeanstalk.EnvironmentBehavior;
import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk;
import com.amazonaws.services.elasticbeanstalk.model.RestartAppServerRequest;
public class RestartEnvironmentJob extends Job {
private final Environment environment;
public RestartEnvironmentJob(Environment environment) {
super("Restarting environment " + environment.getEnvironmentName());
this.environment = environment;
// TODO: Should we use a Job family so that we can easily give them all the same Job image?
setProperty(IProgressConstants.ICON_PROPERTY,
AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_ICON));
setUser(true);
}
@Override
protected IStatus run(IProgressMonitor monitor) {
AWSElasticBeanstalk client = AwsToolkitCore.getClientFactory(environment.getAccountId()).getElasticBeanstalkClientByEndpoint(environment.getRegionEndpoint());
EnvironmentBehavior behavior = (EnvironmentBehavior)environment.getServer().loadAdapter(EnvironmentBehavior.class, monitor);
try {
client.restartAppServer(new RestartAppServerRequest().withEnvironmentName(environment.getEnvironmentName()));
behavior.updateServerState(IServer.STATE_STARTED);
return Status.OK_STATUS;
} catch (AmazonClientException ace) {
return new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unable to terminate environment " + environment.getEnvironmentName() + " : " + ace.getMessage(), ace);
}
}
}
| 7,433 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/CreateNewAwsJavaWebProjectRunnable.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.webproject;
import static com.amazonaws.eclipse.core.util.JavaProjectUtils.setDefaultJreToProjectClasspath;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWebBrowser;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualFolder;
import org.osgi.framework.Bundle;
import com.amazonaws.eclipse.core.AccountInfo;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.core.util.BundleUtils;
import com.amazonaws.eclipse.core.validator.JavaPackageName;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
/**
* Runnable (with progress) that creates a new AWS Java web project, based on
* the configured data model. This class is responsible for creating the WTP
* dynamic web project, adding and configuring the AWS SDK for Java, creating
* the security credential configuration file and eventually configuring the WTP
* runtime targeted by the new project.
*/
final class CreateNewAwsJavaWebProjectRunnable implements IRunnableWithProgress {
private final NewAwsJavaWebProjectDataModel dataModel;
private static final IWorkbenchBrowserSupport BROWSER_SUPPORT =
PlatformUI.getWorkbench().getBrowserSupport();
public CreateNewAwsJavaWebProjectRunnable(NewAwsJavaWebProjectDataModel dataModel) {
this.dataModel = dataModel;
}
/* (non-Javadoc)
* @see org.eclipse.jface.operation.IRunnableWithProgress#run(org.eclipse.core.runtime.IProgressMonitor)
*/
@Override
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
SubMonitor monitor = SubMonitor.convert(progressMonitor, "Creating new AWS Java web project", 100);
try {
IProject project = createBeanstalkProject(
dataModel.getMavenConfigurationDataModel(), monitor);
IJavaProject javaProject = JavaCore.create(project);
setDefaultJreToProjectClasspath(javaProject, monitor);
monitor.worked(20);
addTemplateFiles(project);
monitor.worked(10);
// Configure the Tomcat session manager
if (dataModel.getUseDynamoDBSessionManagement()) {
addSessionManagerConfigurationFiles(project);
}
monitor.worked(10);
if (dataModel.getProjectTemplate() == JavaWebProjectTemplate.DEFAULT) {
// Open the readme.html in an editor browser window.
File root = project.getLocation().toFile();
final File indexHtml = new File(root, "src/main/webapp/index.html");
// Internal browser must be opened within UI thread
Display.getDefault().syncExec(new Runnable() {
@Override
public void run() {
try {
IWebBrowser browser = BROWSER_SUPPORT.createBrowser(
IWorkbenchBrowserSupport.AS_EDITOR,
null,
null,
null);
browser.openURL(indexHtml.toURI().toURL());
} catch (Exception e) {
ElasticBeanstalkPlugin
.getDefault()
.logError(
"Failed to open project index page in Eclipse editor.",
e);
}
}
});
}
} catch (Exception e) {
throw new InvocationTargetException(e);
} finally {
progressMonitor.done();
}
}
private void addSessionManagerConfigurationFiles(IProject project) throws IOException, CoreException {
Bundle bundle = ElasticBeanstalkPlugin.getDefault().getBundle();
URL url = FileLocator.resolve(bundle.getEntry("/"));
IPath templateRoot = new Path(url.getFile(), "templates");
FileUtils.copyDirectory(
templateRoot.append("dynamodb-session-manager").toFile(),
project.getLocation().toFile());
// Add the user's credentials to context.xml
File localContextXml = project.getLocation()
.append(".ebextensions")
.append("context.xml").toFile();
AccountInfo accountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(dataModel.getAccountId());
String contextContents = FileUtils.readFileToString(localContextXml);
contextContents = contextContents.replace("{ACCESS_KEY}", accountInfo.getAccessKey());
contextContents = contextContents.replace("{SECRET_KEY}", accountInfo.getSecretKey());
FileUtils.writeStringToFile(localContextXml, contextContents);
project.refreshLocal(IResource.DEPTH_INFINITE, null);
// Update the J2EE Deployment Assembly by creating a link from the '/.ebextensions'
// folder to the '/WEB-INF/.ebextensions' folder in the web assembly mapping for WTP
IVirtualComponent rootComponent = ComponentCore.createComponent(project);
IVirtualFolder rootFolder = rootComponent.getRootFolder();
try {
Path source = new Path("/.ebextensions");
Path target = new Path("/WEB-INF/.ebextensions");
IVirtualFolder subFolder = rootFolder.getFolder(target);
subFolder.createLink(source, 0, null);
} catch( CoreException ce ) {
String message = "Unable to configure deployment assembly to map .ebextension directory";
ElasticBeanstalkPlugin.getDefault().logError(message, ce);
}
}
private IProject createBeanstalkProject(MavenConfigurationDataModel mavenConfig, IProgressMonitor monitor) throws CoreException, IOException {
List<IProject> projects = MavenFactory.createArchetypeProject(
"org.apache.maven.archetypes", "maven-archetype-webapp", "1.0",
mavenConfig.getGroupId(), mavenConfig.getArtifactId(), mavenConfig.getVersion(), mavenConfig.getPackageName(), monitor);
// This archetype only has one project
return projects.get(0);
}
private void addTemplateFiles(IProject project) throws IOException, CoreException {
final String CREDENTIAL_PROFILE_PLACEHOLDER = "{CREDENTIAL_PROFILE}";
final String PACKAGE_NAME_PLACEHOLDER = "{PACKAGE_NAME}";
Bundle bundle = ElasticBeanstalkPlugin.getDefault().getBundle();
File templateRoot = null;
try {
templateRoot = BundleUtils.getFileFromBundle(bundle, "templates");
} catch (URISyntaxException e) {
throw new RuntimeException("Failed to load templates from ElasticBeanstalk bundle.", e);
}
AccountInfo currentAccountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(dataModel.getAccountId());
File pomFile = project.getFile("pom.xml").getLocation().toFile();
MavenConfigurationDataModel mavenConfig = dataModel.getMavenConfigurationDataModel();
switch (dataModel.getProjectTemplate()) {
case WORKER:
replacePomFile(new File(templateRoot, "worker/pom.xml"),
mavenConfig.getGroupId(), mavenConfig.getArtifactId(), mavenConfig.getVersion(), pomFile);
String packageName = dataModel.getMavenConfigurationDataModel().getPackageName();
JavaPackageName javaPackageName = JavaPackageName.parse(packageName);
IPath location = project.getFile(MavenFactory.getMavenSourceFolder()).getLocation();
for (String component : javaPackageName.getComponents()) {
location = location.append(component);
}
FileUtils.copyDirectory(new File(templateRoot, "worker/src"),
location.toFile());
File workerServlet = location.append("WorkerServlet.java").toFile();
replaceStringInFile(workerServlet, CREDENTIAL_PROFILE_PLACEHOLDER, currentAccountInfo.getAccountName());
replaceStringInFile(workerServlet, PACKAGE_NAME_PLACEHOLDER, packageName);
File workerRequest = location.append("WorkRequest.java").toFile();
replaceStringInFile(workerRequest, PACKAGE_NAME_PLACEHOLDER, packageName);
location = project.getFile("src/main/webapp").getLocation();
FileUtils.copyDirectory(
new File(templateRoot, "worker/WebContent/"),
location.toFile());
File webXml = location.append("WEB-INF/web.xml").toFile();
replaceStringInFile(webXml, PACKAGE_NAME_PLACEHOLDER, packageName);
break;
case DEFAULT:
replacePomFile(new File(templateRoot, "basic/pom.xml"),
mavenConfig.getGroupId(), mavenConfig.getArtifactId(), mavenConfig.getVersion(), pomFile);
location = project.getFile("src/main/webapp").getLocation();
FileUtils.copyDirectory(
new File(templateRoot, "basic/WebContent"),
location.toFile());
File indexJsp = location.append("index.jsp").toFile();
replaceStringInFile(indexJsp, CREDENTIAL_PROFILE_PLACEHOLDER, currentAccountInfo.getAccountName());
break;
default:
throw new IllegalStateException("Unknown project template: " +
dataModel.getProjectTemplate());
}
project.refreshLocal(IResource.DEPTH_INFINITE, null);
}
private String replacePomFile(File pomTemplate, String groupId, String artifactId, String version, File targetFile) throws IOException {
final String GROUP_ID_PLACEHOLDER = "{GROUP_ID}";
final String ARTIFACT_ID_PLACEHOLDER = "{ARTIFACT_ID}";
final String VERSION_PLACEHOLDER = "{VERSION}";
String content = FileUtils.readFileToString(pomTemplate);
content = content.replace(GROUP_ID_PLACEHOLDER, groupId)
.replace(ARTIFACT_ID_PLACEHOLDER, artifactId)
.replace(VERSION_PLACEHOLDER, version);
FileUtils.writeStringToFile(targetFile, content);
return content;
}
/** Replace source strings with target string and return the original content of the file. */
private String replaceStringInFile(File file, String source, String target) throws IOException {
String originalContent = FileUtils.readFileToString(file);
String replacedContent = originalContent.replace(source, target);
FileUtils.writeStringToFile(file, replacedContent);
return originalContent;
}
}
| 7,434 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/NewAwsJavaWebProjectDataModel.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.webproject;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.core.regions.Region;
/**
* Data model containing all the options for creating a new AWS Java web
* project. Used by the New AWS Java Web Project Wizard to collect information
* from users, bind UI controls to values, and pass the data to the runnable
* objects to actually perform the project creation.
*/
class NewAwsJavaWebProjectDataModel {
private String accountId;
private MavenConfigurationDataModel mavenConfigurationDataModel = new MavenConfigurationDataModel();
private JavaWebProjectTemplate projectTemplate;
private String language;
private Region region;
private boolean useDynamoDBSessionManagement;
public static final String ACCOUNT_ID = "accountId";
public static final String PROJECT_NAME = "projectName";
public static final String PROJECT_TEMPLATE = "projectTemplate";
public static final String REGION = "region";
public static final String LANGUAGE = "language";
public static final String USE_DYNAMODB_SESSION_MANAGEMENT = "useDynamoDBSessionManagement";
/*
* Supported languages and map of languages to directories and overrides
*/
public static final String ENGLISH = "English";
public static final String JAPANESE = "Japanese";
public static final String[] LANGUAGES = new String[] { ENGLISH, JAPANESE };
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public MavenConfigurationDataModel getMavenConfigurationDataModel() {
return this.mavenConfigurationDataModel;
}
public JavaWebProjectTemplate getProjectTemplate() {
return projectTemplate;
}
public void setProjectTemplate(JavaWebProjectTemplate projectTemplate) {
this.projectTemplate = projectTemplate;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public boolean getUseDynamoDBSessionManagement() {
return useDynamoDBSessionManagement;
}
public void setUseDynamoDBSessionManagement(boolean useDynamoDBSessionManagement) {
this.useDynamoDBSessionManagement = useDynamoDBSessionManagement;
}
}
| 7,435 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/JavaWebProjectTemplate.java | /*
* Copyright 2013 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.
*/
/*
* Copyright 2010-2012 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.elasticbeanstalk.webproject;
enum JavaWebProjectTemplate {
/**
* A new web project that comes with a simple JSP that illustrates making
* some calls to AWS services. Meant as a starting point for an Elastic
* Beanstalk web tier application.
*/
DEFAULT,
/**
* A new web project that comes with a simple servlet that treats all
* POST requests as requests to dump some data into an S3 bucket. Meant
* as a starting point for an Elastic Beanstalk worker tier application.
*/
WORKER
}
| 7,436 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/NewAwsJavaWebProjectWizard.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.webproject;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.maven.MavenFactory;
import com.amazonaws.eclipse.core.model.MavenConfigurationDataModel;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkAnalytics;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
/**
* Wizard for creating a new WTP Dynamic Web project, pre-configured for use
* with AWS (Java SDK configuration, security credentials, etc).
*/
public class NewAwsJavaWebProjectWizard extends Wizard implements INewWizard {
private static final String DEFAULT_GROUP_ID = "com.amazonaws.beanstalk";
private static final String DEFAULT_ARTIFACT_ID = "webproject";
private static final String DEFAULT_VERSION = "1.0.0";
private static final String DEFAULT_PACKAGE_NAME = MavenFactory.assumePackageName(DEFAULT_GROUP_ID, DEFAULT_ARTIFACT_ID);
private NewAwsJavaWebProjectDataModel dataModel = new NewAwsJavaWebProjectDataModel();
public NewAwsJavaWebProjectWizard() {
this.addPage(new JavaWebProjectWizardPage(dataModel));
setWindowTitle("New AWS Java Web Project");
setDefaultPageImageDescriptor(AwsToolkitCore.getDefault()
.getImageRegistry()
.getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
setNeedsProgressMonitor(true);
initDataModel();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.Wizard#performFinish()
*/
@Override
public boolean performFinish() {
trackCustomerMetrics();
try {
getContainer().run(true, false, new CreateNewAwsJavaWebProjectRunnable(dataModel));
return true;
} catch (InvocationTargetException e) {
Status status = new Status(Status.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID,
"Unable to create new AWS Java web project.", e.getCause());
StatusManager.getManager().handle(status, StatusManager.BLOCK | StatusManager.LOG);
} catch (InterruptedException e) {}
return false;
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {}
public void initDataModel() {
MavenConfigurationDataModel mavenConfig = dataModel.getMavenConfigurationDataModel();
mavenConfig.setGroupId(DEFAULT_GROUP_ID);
mavenConfig.setArtifactId(DEFAULT_ARTIFACT_ID);
mavenConfig.setVersion(DEFAULT_VERSION);
mavenConfig.setPackageName(DEFAULT_PACKAGE_NAME);
}
/*
* Track user behavior from DataModel to the metrics system.
*/
public void trackCustomerMetrics() {
if (dataModel.getProjectTemplate() == JavaWebProjectTemplate.WORKER) {
ElasticBeanstalkAnalytics.trackCreateNewWorkerApplication();
} else if (dataModel.getProjectTemplate() == JavaWebProjectTemplate.DEFAULT) {
if (dataModel.getUseDynamoDBSessionManagement()) {
ElasticBeanstalkAnalytics.trackCreateNewWebApplication_DDB();
} else {
ElasticBeanstalkAnalytics.trackCreateNewWebApplication_NDDB();
}
}
}
}
| 7,437 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/webproject/JavaWebProjectWizardPage.java | /*
* Copyright 2010-2012 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.elasticbeanstalk.webproject;
import static com.amazonaws.eclipse.core.ui.wizards.WizardWidgetFactory.newGroup;
import org.eclipse.core.databinding.AggregateValidationStatus;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.conversion.Converter;
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.databinding.observable.value.WritableValue;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
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 com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.AccountSelectionComposite;
import com.amazonaws.eclipse.core.ui.MavenConfigurationComposite;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
final class JavaWebProjectWizardPage extends WizardPage {
private static final String TOMCAT_SESSION_MANAGER_DOCUMENTATION =
"http://docs.aws.amazon.com/AWSSdkDocsJava/latest/DeveloperGuide/java-dg-tomcat-session-manager.html";
private MavenConfigurationComposite mavenConfigurationComposite;
private Button basicTemplateRadioButton;
private Button workerTemplateRadioButton;
private AccountSelectionComposite accountSelectionComposite;
private final NewAwsJavaWebProjectDataModel dataModel;
private DataBindingContext bindingContext = new DataBindingContext();
/** Collective status of all validators in our binding context */
protected AggregateValidationStatus aggregateValidationStatus =
new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY);
private Group sessionManagerGroup;
private Button useDynamoDBSessionManagerCheckBox;
JavaWebProjectWizardPage(NewAwsJavaWebProjectDataModel dataModel) {
super("New AWS Java Web Project Wizard Page");
this.dataModel = dataModel;
this.setTitle("New AWS Java Web Project");
this.setDescription("Configure the options for creating a new AWS Java web project.");
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false) {
return;
}
IStatus status = (IStatus)value;
if (status.getSeverity() == IStatus.OK) {
setMessage(null);
setErrorMessage(null);
setPageComplete(true);
} else {
if (status.getSeverity() == IStatus.ERROR) {
setErrorMessage(status.getMessage());
} else {
setMessage(status.getMessage());
}
setPageComplete(false);
}
}
});
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 10;
composite.setLayout(layout);
this.setControl(composite);
createMavenConfigurationComposite(composite);
GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
layoutData.widthHint = getContainerWidth() - 50;
Group group = new Group(composite, SWT.NONE);
group.setLayoutData(layoutData);
group.setLayout(new GridLayout());
accountSelectionComposite = new AccountSelectionComposite(group, SWT.None);
dataModel.setAccountId(AwsToolkitCore.getDefault().getCurrentAccountId());
accountSelectionComposite.selectAccountId(dataModel.getAccountId());
dataModel.setProjectTemplate(JavaWebProjectTemplate.DEFAULT);
createSamplesGroup(composite);
createSessionManagerGroup(composite);
bindControls();
composite.pack();
}
private void createMavenConfigurationComposite(Composite composite) {
Group group = newGroup(composite, "Maven configuration");
this.mavenConfigurationComposite = new MavenConfigurationComposite(
group, bindingContext, dataModel.getMavenConfigurationDataModel());
}
private void createSessionManagerGroup(Composite composite) {
sessionManagerGroup = new Group(composite, SWT.NONE);
sessionManagerGroup.setText("Amazon DynamoDB Session Management:");
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 3;
sessionManagerGroup.setLayout(layout);
GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
sessionManagerGroup.setLayoutData(layoutData);
useDynamoDBSessionManagerCheckBox = new Button(sessionManagerGroup, SWT.CHECK);
useDynamoDBSessionManagerCheckBox.setText("Store session data in Amazon DynamoDB");
newLabel(sessionManagerGroup, "This option configures your project with a custom session manager that persists sessions using Amazon DynamoDB when running in an AWS Elastic Beanstalk environment. ");
newLabel(sessionManagerGroup, "This option requires running in a Tomcat 7 environment and is not currently supported for Tomcat 6.");
newLink(sessionManagerGroup, "<a href=\"" + TOMCAT_SESSION_MANAGER_DOCUMENTATION + "\">More information on the Amazon DynamoDB Session Manager for Tomcat</a>");
}
private Label newLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.WRAP);
label.setText(text);
GridData data = new GridData(SWT.FILL, SWT.TOP, true, false);
data.horizontalIndent = 20;
data.widthHint = getContainerWidth() - 30;
label.setLayoutData(data);
return label;
}
private Link newLink(Composite parent, String text) {
Link link = new Link(parent, SWT.WRAP);
link.setText(text);
GridData data = new GridData(SWT.FILL, SWT.TOP, true, false);
data.horizontalIndent = 20;
data.widthHint = getContainerWidth() - 30;
link.setLayoutData(data);
link.addListener(SWT.Selection, new WebLinkListener());
return link;
}
private void createSamplesGroup(Composite composite) {
Group group = new Group(composite, SWT.NONE);
group.setText("Start from:");
GridLayout layout = new GridLayout(1, false);
layout.verticalSpacing = 3;
group.setLayout(layout);
GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false);
group.setLayoutData(layoutData);
basicTemplateRadioButton = new Button(group, SWT.RADIO);
basicTemplateRadioButton.setText("Basic Java Web Application");
basicTemplateRadioButton.setSelection(true);
Label basicTemplateDescriptionLabel = new Label(group, SWT.WRAP);
basicTemplateDescriptionLabel.setText("A simple Java web application with a single JSP.");
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.horizontalIndent = 20;
gridData.widthHint = getContainerWidth() - 30;
basicTemplateDescriptionLabel.setLayoutData(gridData);
basicTemplateRadioButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent event) {
sessionManagerGroup.setEnabled(true);
for (Control control : sessionManagerGroup.getChildren()) {
control.setEnabled(true);
}
}
});
workerTemplateRadioButton = new Button(group, SWT.RADIO);
workerTemplateRadioButton.setText("Basic Amazon Elastic Beanstalk Worker Tier Application");
gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.verticalIndent = 5;
workerTemplateRadioButton.setLayoutData(gridData);
Label workerDescriptionLabel = new Label(group, SWT.WRAP);
gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.horizontalIndent = 20;
gridData.widthHint = getContainerWidth() - 30;
workerDescriptionLabel.setLayoutData(gridData);
workerDescriptionLabel.setText(
"A simple Amazon Elastic Beanstalk Worker Tier Application that "
+ "accepts work requests via POST request.");
workerTemplateRadioButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent event) {
sessionManagerGroup.setEnabled(false);
for (Control control : sessionManagerGroup.getChildren()) {
control.setEnabled(false);
}
}
});
}
@SuppressWarnings("static-access")
private void bindControls() {
final IObservableValue accountId = new WritableValue();
accountId.setValue(dataModel.getAccountId());
accountSelectionComposite.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
accountId.setValue(accountSelectionComposite.getSelectedAccountId());
}
});
bindingContext.bindValue(accountId,
PojoObservables.observeValue(dataModel, dataModel.ACCOUNT_ID), new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE), new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER));
UpdateValueStrategy strategy = new UpdateValueStrategy();
strategy.setConverter(new Converter(Boolean.class, JavaWebProjectTemplate.class) {
@Override
public Object convert(Object fromObject) {
Boolean from = (Boolean) fromObject;
if (from == null || from == false) {
return JavaWebProjectTemplate.DEFAULT;
} else {
return JavaWebProjectTemplate.WORKER;
}
}
});
bindingContext.bindValue(
SWTObservables.observeSelection(workerTemplateRadioButton),
PojoObservables.observeValue(dataModel, dataModel.PROJECT_TEMPLATE),
strategy,
new UpdateValueStrategy(UpdateValueStrategy.POLICY_NEVER)
);
bindingContext.bindValue(SWTObservables.observeSelection(useDynamoDBSessionManagerCheckBox),
PojoObservables.observeValue(dataModel, dataModel.USE_DYNAMODB_SESSION_MANAGEMENT), null, null).updateTargetToModel();
}
private int getContainerWidth() {
return this.getContainer().getShell().getSize().x;
}
}
| 7,438 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/AWSElasticBeanstalkGitPushRequest.java | /*
* Copyright 2012 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.elasticbeanstalk.git;
import java.util.Date;
import com.amazonaws.eclipse.elasticbeanstalk.git.util.BinaryUtils;
public class AWSElasticBeanstalkGitPushRequest extends AWSGitPushRequest {
public String application;
public String environment;
public AWSElasticBeanstalkGitPushRequest() {
super();
}
public AWSElasticBeanstalkGitPushRequest(Date date) {
super(date);
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
@Override
public String derivePath() {
String hexEncodedApplication = BinaryUtils.toHex(BinaryUtils.getBytes(application));
if (environment == null || environment.length() == 0) {
return "/repos/" + hexEncodedApplication;
} else {
return "/repos/" + hexEncodedApplication + "/" + environment;
}
}
@Override
public String deriveRequest() {
String path = derivePath();
String request = AWSGitPushRequest.METHOD + "\n" +
path + "\n\n" +
"host:" + host + "\n\n" +
"host\n";
return request;
}
} | 7,439 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/AWSGitPushRequest.java | /*
* Copyright 2012 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.elasticbeanstalk.git;
import java.util.Date;
public abstract class AWSGitPushRequest {
static final String METHOD = "GIT";
private static final String SERVICE = "devtools";
protected Date date = new Date();
protected String host;
protected String region;
protected String service = SERVICE;
public AWSGitPushRequest() {}
public AWSGitPushRequest(Date dateTime) {
if (dateTime == null) throw new IllegalArgumentException("dateTime not specified");
this.date = dateTime;
}
public abstract String derivePath();
public abstract String deriveRequest();
public Date getDate() {
return date;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getService() {
return service;
}
} | 7,440 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/AWSGitPushAuth.java | /*
* Copyright 2012 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.elasticbeanstalk.git;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.amazonaws.eclipse.elasticbeanstalk.git.util.BinaryUtils;
import com.amazonaws.eclipse.elasticbeanstalk.git.util.DateUtils;
public class AWSGitPushAuth {
private static final String ALGORITHM = "HMAC-SHA256";
private static final String SCHEME = "AWS4";
private static final String TERMINATOR = "aws4_request";
private final AWSGitPushRequest request;
private static final Logger log = Logger.getLogger(AWSGitPushAuth.class.getCanonicalName());
public AWSGitPushAuth(AWSGitPushRequest request) {
this.request = request;
}
private static byte[] deriveKey(String secretKey, AWSGitPushRequest request) throws Exception {
byte[] kSecret = BinaryUtils.getBytes(AWSGitPushAuth.SCHEME + secretKey);
byte[] kDate = BinaryUtils.sign(BinaryUtils.getBytes(DateUtils.formatDateStamp(request.getDate())), kSecret);
byte[] kRegion = BinaryUtils.sign(BinaryUtils.getBytes(request.getRegion()), kDate);
byte[] kService = BinaryUtils.sign(BinaryUtils.getBytes(request.getService()), kRegion);
byte[] kSigning = BinaryUtils.sign(BinaryUtils.getBytes(AWSGitPushAuth.TERMINATOR), kService);
return kSigning;
}
public String derivePassword(String awsSecretKey) throws Exception {
String signature = signRequest(awsSecretKey, request);
String password = DateUtils.formatDateTimeStamp(request.getDate()) + "Z" + signature;
return password;
}
public URI deriveRemote(String awsAccessKey, String awsSecretKey) throws Exception {
String path = request.derivePath();
String password = derivePassword(awsSecretKey);
String username = awsAccessKey;
/*
* Example Git Push Remote URL:
* https://1TNT3D6W620GJR87HT02:20120228T212659Z4e6aa7d004b9aa8b8dae8523eaa4a2bebd74088a90ba33f606099d180bff317b@aws-git-push.amazonaws.com/repos/6170706c69636174696f6e/environment/info/refs
*/
URI uri = new URI("https://" + username + ":" + password + "@" + request.getHost() + path);
return uri;
}
static String signRequest(String awsSecretKey, AWSGitPushRequest request) throws Exception {
String scope = DateUtils.formatDateStamp(request.getDate()) + "/"
+ request.getRegion() + "/"
+ request.getService() + "/"
+ AWSGitPushAuth.TERMINATOR;
StringBuilder stringToSign = new StringBuilder();
stringToSign.append(AWSGitPushAuth.SCHEME + "-" + AWSGitPushAuth.ALGORITHM + "\n"
+ DateUtils.formatDateTimeStamp(request.getDate()) + "\n"
+ scope + "\n");
if (log.isLoggable(Level.FINE)) log.fine("Request: " + request.deriveRequest());
byte[] requestBytes = BinaryUtils.getBytes(request.deriveRequest());
byte[] requestDigest = BinaryUtils.hash(requestBytes);
stringToSign.append(BinaryUtils.toHex(requestDigest));
if (log.isLoggable(Level.FINE)) log.fine("StringToSign: " + stringToSign);
byte[] key = deriveKey(awsSecretKey, request);
byte[] digest = BinaryUtils.sign(BinaryUtils.getBytes(stringToSign.toString()), key);
String signature = BinaryUtils.toHex(digest);
if (log.isLoggable(Level.FINE)) log.fine("Signature: " + signature);
return signature;
}
}
| 7,441 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/AWSGitPushCommand.java | /*
* Copyright 2012 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.elasticbeanstalk.git;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.util.FileUtils;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.eclipse.core.regions.Region;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.elasticbeanstalk.ElasticBeanstalkPlugin;
import com.amazonaws.eclipse.elasticbeanstalk.Environment;
public class AWSGitPushCommand {
private final File repoLocation;
private final File archiveFile;
private final Environment environment;
private boolean skipEnvironmentDeployment;
private final String accessKey;
private final String secretKey;
public AWSGitPushCommand(File repoLocation, File archiveFile, Environment environment, AWSCredentials credentials) {
this.repoLocation = repoLocation;
this.archiveFile = archiveFile;
this.environment = environment;
this.accessKey = credentials.getAWSAccessKeyId();
this.secretKey = credentials.getAWSSecretKey();
}
private static final Logger log = Logger.getLogger(AWSGitPushCommand.class.getCanonicalName());
public void execute() throws CoreException {
Iterable<PushResult> pushResults = null;
try {
Repository repository = initializeRepository();
// Add the new files
clearOutRepository(repository);
extractZipFile(archiveFile, repoLocation);
commitChanges(repository, "Incremental Deployment: " + new Date().toString());
// Push to AWS
String remoteUrl = getRemoteUrl();
if (log.isLoggable(Level.FINE)) log.fine("Pushing to: " + remoteUrl);
PushCommand pushCommand = new Git(repository).push().setRemote(remoteUrl).setForce(true).add("master");
// TODO: we could use a ProgressMonitor here for reporting status back to the UI
pushResults = pushCommand.call();
} catch (Throwable t) {
throwCoreException(null, t);
}
for (PushResult pushResult : pushResults) {
String messages = pushResult.getMessages();
if (messages != null && messages.trim().length() > 0) {
throwCoreException(messages, null);
}
}
}
/**
* Use this method to configure this request to only create a new
* application version, and not automatically deploy it to the specified
* environment.
*
* @param skipEnvironmentDeployment
* True if this Git Push should only create a new application
* version, and not automatically deploy it to the specified
* environment.
*/
public void skipEnvironmentDeployment(boolean skipEnvironmentDeployment) {
this.skipEnvironmentDeployment = skipEnvironmentDeployment;
}
private void throwCoreException(String customMessage, Throwable t) throws CoreException {
if (customMessage != null) customMessage = ": " + customMessage;
else customMessage = "";
String errorMessage = "Unable to update environment with an incremental deployment" + customMessage
+ "\nIf you continue having problems with incremental deployments, try turning off incremental deployments in the server configuration editor.";
throw new CoreException(new Status(IStatus.ERROR, ElasticBeanstalkPlugin.PLUGIN_ID, errorMessage, t));
}
private String getRemoteUrl() throws Exception {
AWSElasticBeanstalkGitPushRequest request = new AWSElasticBeanstalkGitPushRequest();
request.setHost(getGitPushHost());
Region region = RegionUtils.getRegionByEndpoint(environment.getRegionEndpoint());
request.setRegion(region.getId());
request.setApplication(environment.getApplicationName());
if (!skipEnvironmentDeployment) {
request.setEnvironment(environment.getEnvironmentName());
}
AWSGitPushAuth auth = new AWSGitPushAuth(request);
URI uri = auth.deriveRemote(accessKey, secretKey);
return uri.toString();
}
private String getGitPushHost() {
// TODO: it would be better to get this from the endpoints file at some point
String regionEndpoint = environment.getRegionEndpoint();
if (regionEndpoint.startsWith("https://")) {
regionEndpoint = "git." + regionEndpoint.substring("https://".length());
} else if (regionEndpoint.startsWith("http://")) {
regionEndpoint = "git." + regionEndpoint.substring("http://".length());
} else {
regionEndpoint = "git." + regionEndpoint;
}
if (regionEndpoint.endsWith("/")) {
regionEndpoint = regionEndpoint.substring(0, regionEndpoint.length() - 1);
}
return regionEndpoint;
}
private void clearOutRepository(Repository repository) throws IOException {
// Delete all the old files before copying the new files
final File gitMetadataDirectory = repository.getIndexFile().getParentFile();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(final File file) {
if (file.equals(gitMetadataDirectory)) return false;
if (!file.getParentFile().equals(repoLocation)) return false;
return true;
}
};
for (File f : repoLocation.listFiles(fileFilter)) {
FileUtils.delete(f, FileUtils.RECURSIVE);
}
}
private Repository initializeRepository() throws IOException {
if (repoLocation == null) {
throw new RuntimeException("No repository location specified");
}
if ((!repoLocation.exists() && !repoLocation.mkdirs()) ||
!repoLocation.isDirectory()) {
throw new RuntimeException("Unable to initialize Git repository from location: " + repoLocation);
}
Repository repository = new RepositoryBuilder().setWorkTree(repoLocation).build();
if (!repository.getObjectDatabase().exists()) {
repository.create();
}
return repository;
}
// TODO: We could use a better util for this
private void extractZipFile(File zipFile, File destination) throws IOException {
int BUFFER = 2048;
FileInputStream fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
BufferedOutputStream dest = null;
try {
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
if (entry.isDirectory()) continue;
File entryFile = new File(destination, entry.getName());
if (!entryFile.getParentFile().exists()) {
entryFile.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(entryFile);
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
}
} finally {
IOUtils.closeQuietly(fis);
IOUtils.closeQuietly(zis);
IOUtils.closeQuietly(dest);
}
}
private void commitChanges(Repository repository, String message) throws GitAPIException, IOException {
Git git = new Git(repository);
// Add once (without the update flag) to add new and modified files
git.add().addFilepattern(".").call();
// Then again with the update flag to add deleted and modified files
git.add().addFilepattern(".").setUpdate(true).call();
git.commit().setMessage(message).call();
}
} | 7,442 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/util/BinaryUtils.java | /*
* Copyright 2012 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.elasticbeanstalk.git.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Locale;
import com.amazonaws.AmazonClientException;
import com.amazonaws.SignableRequest;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSSessionCredentials;
import com.amazonaws.auth.AbstractAWSSigner;
import com.amazonaws.auth.SigningAlgorithm;
public class BinaryUtils {
public static byte[] hash(String text) throws AmazonClientException {
try {
return hash(getBytes(text));
} catch (Exception e) {
throw new AmazonClientException("Unable to compute hash while signing request: " + e.getMessage(), e);
}
}
public static byte[] hash(byte[] data) throws AmazonClientException {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data);
return md.digest();
} catch (Exception e) {
throw new AmazonClientException("Unable to compute hash while signing request: " + e.getMessage(), e);
}
}
public static byte[] sign(final byte[] data, final byte[] key) throws AmazonClientException {
return new AbstractAWSSigner() {
@Override
public void sign(SignableRequest<?> arg0, AWSCredentials arg1) {}
@Override
protected void addSessionCredentials(SignableRequest<?> arg0, AWSSessionCredentials arg1) {}
public byte[] sign() {
return sign(data, key, SigningAlgorithm.HmacSHA256);
}
}.sign();
}
public static String toHex(byte[] data) {
StringBuilder sb = new StringBuilder(data.length * 2);
for (int i = 0; i < data.length; i++) {
String hex = Integer.toHexString(data[i]);
if (hex.length() == 1) {
// Append leading zero.
sb.append("0");
} else if (hex.length() == 8) {
// Remove ff prefix from negative numbers.
hex = hex.substring(6);
}
sb.append(hex);
}
return sb.toString().toLowerCase(Locale.getDefault());
}
public static byte[] getBytes(String s) {
try {
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unable to encode bytes as UTF-8");
}
}
} | 7,443 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/util/CertificateUtils.java | package com.amazonaws.eclipse.elasticbeanstalk.git.util;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class CertificateUtils {
public static void disableCertValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
}
} | 7,444 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.elasticbeanstalk/src/com/amazonaws/eclipse/elasticbeanstalk/git/util/DateUtils.java | /*
* Copyright 2012 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.elasticbeanstalk.git.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
public class DateUtils {
private static final SimpleDateFormat DATE_STAMP_FORMAT = new SimpleDateFormat("yyyyMMdd");
private static final SimpleDateFormat DATE_TIME_STAMP_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
static {
DATE_STAMP_FORMAT.setTimeZone(new SimpleTimeZone(0, "UTC"));
DATE_TIME_STAMP_FORMAT.setTimeZone(new SimpleTimeZone(0, "UTC"));
}
public static synchronized String formatDateStamp(final Date date) {
return DATE_STAMP_FORMAT.format(date);
}
public static synchronized String formatDateTimeStamp(final Date date) {
return DATE_TIME_STAMP_FORMAT.format(date);
}
} | 7,445 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/IdentityManagementPlugin.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.identitymanagement;
import org.osgi.framework.BundleContext;
import com.amazonaws.eclipse.core.plugin.AbstractAwsPlugin;
/**
* The activator class controls the plug-in life cycle
*/
public class IdentityManagementPlugin extends AbstractAwsPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.amazonaws.eclipse.identitymanagement"; //$NON-NLS-1$
// The shared instance
private static IdentityManagementPlugin plugin;
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
@Override
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static IdentityManagementPlugin getDefault() {
return plugin;
}
}
| 7,446 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/AddRolePolicyDialog.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.identitymanagement.role;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractAddPolicyDialog;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.Role;
class AddRolePolicyDialog extends AbstractAddPolicyDialog {
private final Role role;
public AddRolePolicyDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, Role role, RolePermissionTable rolePermissionTable) {
super(iam, parentShell, toolkit, rolePermissionTable);
this.iam = iam;
this.role = role;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Manage Role Permission");
}
@Override
protected void putPolicy(String policyName, String policyDoc) {
iam.putRolePolicy(new PutRolePolicyRequest().withRoleName(role.getRoleName()).withPolicyDocument(policyDoc).withPolicyName(policyName));
}
}
| 7,447 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/EditTrustRelationshipDialog.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.identitymanagement.role;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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.Dialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Role;
import com.amazonaws.services.identitymanagement.model.UpdateAssumeRolePolicyRequest;
public class EditTrustRelationshipDialog extends TitleAreaDialog {
private Text policyText;
private Role role;
private AmazonIdentityManagement iam;
public EditTrustRelationshipDialog(AmazonIdentityManagement iam, Shell parentShell, Role role) {
super(parentShell);
this.role = role;
this.iam = iam;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Edit Trust Relationship");
setMessage("You can customize trust relationships by editing the following access control policy document. ");
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
policyText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
policyText.setLayoutData(new GridData(GridData.FILL_BOTH));
try {
policyText.setText(getAssumeRolePolicy());
} catch (Exception e) {
setErrorMessage(e.getMessage());
}
Dialog.applyDialogFont(parent);
return composite;
}
@Override
protected void okPressed() {
final String policyDoc = policyText.getText();
new Job("Update assume role policy") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
updateAssumeRolePolicy(policyDoc);
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to update the assume role policies: " + e.getMessage(), e);
}
}
}.schedule();
super.okPressed();
}
private void updateAssumeRolePolicy(String policyDoc) {
iam.updateAssumeRolePolicy(new UpdateAssumeRolePolicyRequest().withRoleName(role.getRoleName()).withPolicyDocument(policyDoc));
}
private String getAssumeRolePolicy() throws UnsupportedEncodingException {
String policyDoc = role.getAssumeRolePolicyDocument();
return URLDecoder.decode(policyDoc, "UTF-8");
}
}
| 7,448 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/CreateRoleSecondPage.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.identitymanagement.role;
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.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.identitymanagement.databinding.DataBindingUtils;
public class CreateRoleSecondPage extends WizardPage {
private final String[] services = {"Amazon EC2(Allows EC2 instances to call AWS services on your behalf.)",
"AWS Data Pipeline(Allows Data Pipeline to call AWS Services on your behalf.)",
"Amazon EC2 Role for Data Pipeline(Provides access to services for EC2 instances that are launched by Data Pipeline.)",
"Amazon Elastic Transcoder(Allows Elastic Transcoder to call S3 and SNS on your behalf.)",
"AWS OpsWorks(Allows OpsWorks to create and manage AWS resources on your behalf.)"};
private final String[] IDENTITY_PROVIDERS = { "Facebook", "Google", "Login with Amazon"};
private Button serviceRolesButton;
private Button accountRolesButon;
private Button thirdPartyRolesButton;
private Button webFederationRolesButton;
private Combo servicesCombo;
private Text accountIdText;
private Text internalAccountIdText;
private Text externalAccountIdText;
private Combo IdentityProvidersCombo;
private Text applicationIdText;
private Label applicationIdLabel;
private IObservableValue service;
private IObservableValue accountId;
private IObservableValue internalAccountId;
private IObservableValue externalAccountId;
private IObservableValue serviceRoles;
private IObservableValue accountRoles;
private IObservableValue thirdPartyRoles;
private IObservableValue webProviderRoles;
private IObservableValue webProvider;
private IObservableValue applicationId;
private final String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html";
private final String webIdentityRoleHelpMessage = "Select the identity provider to trust and then enter your Application "
+ "ID or Audience as supplied by your identity provider. "
+ "Users logged into your application from this provider will be able to access resources from this AWS account.";
CreateRoleWizard wizard;
private final DataBindingContext bindingContext = new DataBindingContext();
public CreateRoleSecondPage(CreateRoleWizard wizard) {
super("");
service = PojoObservables.observeValue(wizard.getDataModel(), "service");
accountId = PojoObservables.observeValue(wizard.getDataModel(), "accountId");
internalAccountId = PojoObservables.observeValue(wizard.getDataModel(), "internalAccountId");
externalAccountId = PojoObservables.observeValue(wizard.getDataModel(), "externalAccountId");
serviceRoles = PojoObservables.observeValue(wizard.getDataModel(), "serviceRoles");
accountRoles = PojoObservables.observeValue(wizard.getDataModel(), "accountRoles");
thirdPartyRoles = PojoObservables.observeValue(wizard.getDataModel(), "thirdPartyRoles");
webProviderRoles = PojoObservables.observeValue(wizard.getDataModel(), "webProviderRoles");
applicationId = PojoObservables.observeValue(wizard.getDataModel(), "applicationId");
webProvider = PojoObservables.observeValue(wizard.getDataModel(), "webProvider");
this.wizard = wizard;
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
GridLayout layout = new GridLayout(1, false);
layout.marginLeft = 5;
composite.setLayout(layout);
createServiceRoleControl(composite);
createAccountRoleControl(composite);
createThirdPartyControl(composite);
createWebIdentityProviderControl(composite);
CreateHelpLinkControl(composite);
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false)
return;
IStatus status = (IStatus) value;
if (status.isOK()) {
setErrorMessage(null);
} else if (status.getSeverity() == Status.WARNING) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if (status.getSeverity() == Status.ERROR) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
});
setPageComplete(false);
setControl(composite);
}
private void createServiceRoleControl(Composite comp) {
serviceRolesButton = new Button(comp, SWT.RADIO);
serviceRolesButton.setText("AWS Service Roles");
serviceRolesButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
servicesCombo.setEnabled(true);
accountIdText.setEnabled(false);
internalAccountIdText.setEnabled(false);
externalAccountIdText.setEnabled(false);
IdentityProvidersCombo.setEnabled(false);
applicationIdText.setEnabled(false);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
bindingContext.bindValue(SWTObservables.observeSelection(serviceRolesButton), serviceRoles);
servicesCombo = new Combo(comp, SWT.NONE);
for (String service : services) {
servicesCombo.add(service);
}
servicesCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
servicesCombo.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeSelection(servicesCombo), service);
ChainValidator<String> serviceRoleValidationStatusProvider = new ChainValidator<>(service,
serviceRoles, new NotEmptyValidator("Please select a service"));
bindingContext.addValidationStatusProvider(serviceRoleValidationStatusProvider);
DataBindingUtils.addStatusDecorator(servicesCombo, serviceRoleValidationStatusProvider);
}
private void createAccountRoleControl(Composite comp) {
accountRolesButon = new Button(comp, SWT.RADIO);
accountRolesButon.setText("Provide access between AWS accounts you own");
accountRolesButon.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
servicesCombo.setEnabled(false);
accountIdText.setEnabled(true);
internalAccountIdText.setEnabled(false);
externalAccountIdText.setEnabled(false);
IdentityProvidersCombo.setEnabled(false);
applicationIdText.setEnabled(false);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
bindingContext.bindValue(SWTObservables.observeSelection(accountRolesButon), accountRoles);
new Label(comp, SWT.NONE).setText("Account Id:");
accountIdText = new Text(comp, SWT.BORDER);
accountIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
accountIdText.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeText(accountIdText, SWT.Modify), accountId);
ChainValidator<String> accountIdValidationStatusProvider = new ChainValidator<>(accountId,
accountRoles, new NotEmptyValidator("Please enter your account Id"));
bindingContext.addValidationStatusProvider(accountIdValidationStatusProvider);
DataBindingUtils.addStatusDecorator(accountIdText, accountIdValidationStatusProvider);
}
private void createThirdPartyControl(Composite comp) {
thirdPartyRolesButton = new Button(comp, SWT.RADIO);
thirdPartyRolesButton.setText("Provide access to a 3rd party AWS account");
thirdPartyRolesButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
servicesCombo.setEnabled(false);
accountIdText.setEnabled(false);
IdentityProvidersCombo.setEnabled(false);
applicationIdText.setEnabled(false);
internalAccountIdText.setEnabled(true);
externalAccountIdText.setEnabled(true);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
bindingContext.bindValue(SWTObservables.observeSelection(thirdPartyRolesButton), thirdPartyRoles);
new Label(comp, SWT.NONE).setText("Account Id:");
internalAccountIdText = new Text(comp, SWT.BORDER);
internalAccountIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
internalAccountIdText.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeText(internalAccountIdText, SWT.Modify), internalAccountId);
ChainValidator<String> internalAccountIdValidationStatusProvider = new ChainValidator<>(internalAccountId,
thirdPartyRoles, new NotEmptyValidator("Please enter the internal account Id"));
bindingContext.addValidationStatusProvider(internalAccountIdValidationStatusProvider);
DataBindingUtils.addStatusDecorator(internalAccountIdText, internalAccountIdValidationStatusProvider);
new Label(comp, SWT.NONE).setText("External Id:");;
externalAccountIdText = new Text(comp, SWT.BORDER);
externalAccountIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
externalAccountIdText.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeText(externalAccountIdText, SWT.Modify), externalAccountId);
ChainValidator<String> externalAccountIdValidationStatusProvider = new ChainValidator<>(externalAccountId,
thirdPartyRoles, new NotEmptyValidator("Please enter the external account Id"));
bindingContext.addValidationStatusProvider(externalAccountIdValidationStatusProvider);
DataBindingUtils.addStatusDecorator(externalAccountIdText, externalAccountIdValidationStatusProvider);
}
private void createWebIdentityProviderControl(Composite comp) {
webFederationRolesButton = new Button(comp, SWT.RADIO);
webFederationRolesButton.setText("Provide access to web identity providers");
webFederationRolesButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
servicesCombo.setEnabled(false);
accountIdText.setEnabled(false);
internalAccountIdText.setEnabled(false);
externalAccountIdText.setEnabled(false);
IdentityProvidersCombo.setEnabled(true);
applicationIdText.setEnabled(true);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
Label label = new Label(comp, SWT.NONE | SWT.WRAP);
label.setText(webIdentityRoleHelpMessage);
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
label.setLayoutData(gridData);
bindingContext.bindValue(SWTObservables.observeSelection(webFederationRolesButton), webProviderRoles);
new Label(comp, SWT.NONE).setText("Identity Provider");
IdentityProvidersCombo = new Combo(comp, SWT.BORDER);
for (String provider : IDENTITY_PROVIDERS) {
IdentityProvidersCombo.add(provider);
}
IdentityProvidersCombo.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (IDENTITY_PROVIDERS[IdentityProvidersCombo.getSelectionIndex()].equals("Google")) {
applicationIdLabel.setText("Audience");
} else {
applicationIdLabel.setText("Application Id");
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
IdentityProvidersCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
IdentityProvidersCombo.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeSelection(IdentityProvidersCombo), webProvider);
ChainValidator<String> webProviderValidationStatusProvider = new ChainValidator<>(webProvider, webProviderRoles, new NotEmptyValidator(
"Please select an identity provider"));
bindingContext.addValidationStatusProvider(webProviderValidationStatusProvider);
IdentityProvidersCombo.setText("Facebook");
applicationIdLabel = new Label(comp, SWT.NONE);
applicationIdLabel.setText("Application Id");
applicationIdText = new Text(comp, SWT.BORDER);
applicationIdText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
applicationIdText.setEnabled(false);
bindingContext.bindValue(SWTObservables.observeText(applicationIdText, SWT.Modify), applicationId);
ChainValidator<String> applicationIdValidationStatusProvider = new ChainValidator<>(applicationId, webProviderRoles, new NotEmptyValidator(
"Please enter application Id or Audience"));
bindingContext.addValidationStatusProvider(applicationIdValidationStatusProvider);
DataBindingUtils.addStatusDecorator(applicationIdText, applicationIdValidationStatusProvider);
}
private void CreateHelpLinkControl(Composite comp) {
Link link = new Link(comp, SWT.NONE | SWT.WRAP);
link.setText("\n\nFor more information about IAM roles, see " +
"<a href=\"" +
ConceptUrl + "\">Delegating API access by using roles</a> in the using IAM guide.");
link.addListener(SWT.Selection, new WebLinkListener());
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
link.setLayoutData(gridData);
}
}
| 7,449 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/ShowRolePolicyDialog.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.identitymanagement.role;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.GetRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.Role;
class ShowRolePolicyDialog extends TitleAreaDialog {
private String policyName;
private boolean edittable;
private Text policyText;
EditorInput roleEditorInput;
private Role role;
private AmazonIdentityManagement iam;
public ShowRolePolicyDialog(AmazonIdentityManagement iam, Shell parentShell, Role role, String policyName, boolean edittable) {
super(parentShell);
this.role = role;
this.policyName = policyName;
this.edittable = edittable;
this.iam = iam;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Policy Name :");
setMessage(policyName);
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
policyText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
try {
policyText.setText(getPolicy(policyName));
} catch (Exception e) {
setErrorMessage(e.getMessage());
}
policyText.setLayoutData(new GridData(GridData.FILL_BOTH));
if (!edittable) {
policyText.setEditable(false);
}
Dialog.applyDialogFont(parent);
return composite;
}
@Override
protected void okPressed() {
try {
if (edittable) {
putPolicy(policyName, policyText.getText());
}
} catch (Exception e) {
setErrorMessage(e.getMessage());
return;
}
super.okPressed();
}
private void putPolicy(String policyName, String policyDoc) {
iam.putRolePolicy(new PutRolePolicyRequest().withRoleName(role.getRoleName()).withPolicyDocument(policyDoc).withPolicyName(policyName));
}
private String getPolicy(String policyName) throws UnsupportedEncodingException {
String policyDoc = iam.getRolePolicy(new GetRolePolicyRequest().withPolicyName(policyName).withRoleName(role.getRoleName())).getPolicyDocument();
return URLDecoder.decode(policyDoc, "UTF-8");
}
}
| 7,450 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RoleSummary.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.identitymanagement.role;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.InstanceProfile;
import com.amazonaws.services.identitymanagement.model.ListInstanceProfilesForRoleRequest;
import com.amazonaws.services.identitymanagement.model.ListInstanceProfilesForRoleResult;
import com.amazonaws.services.identitymanagement.model.Role;
public class RoleSummary extends Composite {
private Role role;
private Text roleARNLabel;
private Text instanceProfileLabel;
private Text pathLabel;
private Text creationTimeLabel;
private AmazonIdentityManagement iam;
private final String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/WorkingWithRoles.html";
public RoleSummary(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.iam = iam;
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
this.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
this.setLayout(new GridLayout(4, false));
this.setBackground(toolkit.getColors().getBackground());
toolkit.createLabel(this, "Role ARN:");
roleARNLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(roleARNLabel);
toolkit.createLabel(this, "Instance Profile ARN(s):");
instanceProfileLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(instanceProfileLabel);
toolkit.createLabel(this, "Path:");
pathLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(pathLabel);
toolkit.createLabel(this, "Creation Time:");
creationTimeLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(creationTimeLabel);
Link link = new Link(this, SWT.NONE | SWT.WRAP);
link.setBackground(toolkit.getColors().getBackground());
link.setText("\nFor more information about IAM roles, see " +
"<a href=\"" +
ConceptUrl + "\">Delegating API access by using roles</a> in the using IAM guide.");
link.addListener(SWT.Selection, new WebLinkListener());
gridDataFactory.copy().span(4, SWT.DEFAULT).applyTo(link);
}
public void setRole(Role role) {
this.role = role;
refresh();
}
public void refresh() {
new LoadUserSummaryThread().start();
}
private class LoadUserSummaryThread extends Thread {
@Override
public void run() {
try {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (role != null) {
roleARNLabel.setText(role.getArn());
pathLabel.setText(role.getPath());
creationTimeLabel.setText(role.getCreateDate().toString());
StringBuilder instanceProfiles = new StringBuilder();
ListInstanceProfilesForRoleResult listInstanceProfilesForRoleResult = iam.listInstanceProfilesForRole(
new ListInstanceProfilesForRoleRequest().withRoleName(role.getRoleName()));
for (InstanceProfile instanceProfile : listInstanceProfilesForRoleResult.getInstanceProfiles()) {
instanceProfiles.append(instanceProfile.getArn());
instanceProfiles.append("");
}
instanceProfileLabel.setText(instanceProfiles.toString());
} else {
roleARNLabel.setText("");
pathLabel.setText("");
creationTimeLabel.setText("");
instanceProfileLabel.setText("");
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe the roles: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
| 7,451 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/CreateRoleWizard.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.identitymanagement.role;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
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.wizard.Wizard;
import com.amazonaws.auth.policy.Action;
import com.amazonaws.auth.policy.Condition;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.auth.policy.Principal.Services;
import com.amazonaws.auth.policy.Principal.WebIdentityProviders;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.auth.policy.Statement.Effect;
import com.amazonaws.auth.policy.actions.SecurityTokenServiceActions;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AddRoleToInstanceProfileRequest;
import com.amazonaws.services.identitymanagement.model.CreateInstanceProfileRequest;
import com.amazonaws.services.identitymanagement.model.CreateRoleRequest;
import com.amazonaws.services.identitymanagement.model.GetInstanceProfileRequest;
import com.amazonaws.services.identitymanagement.model.PutRolePolicyRequest;
public class CreateRoleWizard extends Wizard {
private CreateRoleFirstPage firstPage;
private CreateRoleSecondPage secondPage;
private CreateRoleThirdPage thirdPage;
private CreateRoleWizardDataModel dataModel;
private AmazonIdentityManagement iam;
private IRefreshable refreshable;
public CreateRoleWizard (AmazonIdentityManagement iam, IRefreshable refreshable) {
setNeedsProgressMonitor(false);
setWindowTitle("Create New Role");
setDefaultPageImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
dataModel = new CreateRoleWizardDataModel();
this.iam = iam;
if (iam == null) {
this.iam = AwsToolkitCore.getClientFactory().getIAMClient();
}
this.refreshable = refreshable;
}
public CreateRoleWizard() {
this(AwsToolkitCore.getClientFactory().getIAMClient(), null);
}
@Override
public boolean performFinish() {
final CreateRoleRequest createRoleRequest = new CreateRoleRequest();
createRoleRequest.setAssumeRolePolicyDocument(getAssumeRolePolicyDoc());
createRoleRequest.setRoleName(dataModel.getRoleName());
final GetInstanceProfileRequest getInstanceProfileRequest = new GetInstanceProfileRequest();
getInstanceProfileRequest.setInstanceProfileName(dataModel.getRoleName());
final CreateInstanceProfileRequest createInstanceProfileRequest = new CreateInstanceProfileRequest();
createInstanceProfileRequest.setInstanceProfileName(dataModel.getRoleName());
final AddRoleToInstanceProfileRequest addRoleToInstanceProfileRequest = new AddRoleToInstanceProfileRequest();
addRoleToInstanceProfileRequest.setInstanceProfileName(dataModel.getRoleName());
addRoleToInstanceProfileRequest.setRoleName(dataModel.getRoleName());
final PutRolePolicyRequest putRolePolicyRequest = generatePutPolicyRequest();
new Job("Creating role") {
@Override
protected IStatus run(IProgressMonitor monitor) {
boolean hasProfile = true;
try {
iam.createRole(createRoleRequest);
if (putRolePolicyRequest != null) {
iam.putRolePolicy(putRolePolicyRequest);
}
try {
iam.getInstanceProfile(getInstanceProfileRequest);
} catch (Exception e) {
hasProfile = false;
}
if (hasProfile == false) {
iam.createInstanceProfile(createInstanceProfileRequest);
iam.addRoleToInstanceProfile(addRoleToInstanceProfileRequest);
}
if (refreshable != null) {
refreshable.refreshData();
}
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to create the role: " + e.getMessage(), e);
}
}
}.schedule();
return true;
}
@Override
public void addPages() {
firstPage = new CreateRoleFirstPage(this);
secondPage = new CreateRoleSecondPage(this);
thirdPage = new CreateRoleThirdPage(this);
addPage(firstPage);
addPage(secondPage);
addPage(thirdPage);
}
private PutRolePolicyRequest generatePutPolicyRequest() {
if (!dataModel.getGrantPermission()) {
return null;
} else {
return new PutRolePolicyRequest()
.withRoleName(dataModel.getRoleName())
.withPolicyDocument(dataModel.getPolicyDoc())
.withPolicyName(dataModel.getPolicyName());
}
}
public CreateRoleWizardDataModel getDataModel() {
return dataModel;
}
private String getAssumeRolePolicyDoc() {
Policy assumeRolePolicy = new Policy();
Principal principal = null;
if (dataModel.getServiceRoles()) {
if (dataModel.getService().startsWith("Amazon EC2")) {
principal = new Principal(Services.AmazonEC2);
} else if (dataModel.getService().startsWith("AWS Data Pipeline")) {
principal = new Principal(Services.AWSDataPipeline);
} else if (dataModel.getService().startsWith("AWS OpsWorks")) {
principal = new Principal(Services.AWSOpsWorks);
} else if (dataModel.getService().startsWith("Amazon EC2 Role for Data Pipeline")) {
principal = new Principal(Services.AmazonEC2);
} else {
principal = new Principal(Services.AmazonElasticTranscoder);
}
} else if (dataModel.getAccountRoles()) {
principal = new Principal(dataModel.getAccountId());
} else if (dataModel.getWebProviderRoles()) {
if (dataModel.getWebProvider().equals("Facebook")) {
principal = new Principal(WebIdentityProviders.Facebook);
} else if (dataModel.getWebProvider().equals("Google")) {
principal = new Principal(WebIdentityProviders.Google);
} else {
principal = new Principal(WebIdentityProviders.Amazon);
}
} else {
principal = new Principal(dataModel.getInternalAccountId());
}
Statement statement = new Statement(Effect.Allow);
statement.setPrincipals(Arrays.asList(principal));
Condition condition = generateCondition();
if (condition != null) {
statement.setConditions(Arrays.asList(condition));
}
Action action = generateAction();
statement.setActions(Arrays.asList(action));
assumeRolePolicy.setStatements(Arrays.asList(statement));
return assumeRolePolicy.toJson();
}
private Condition generateCondition() {
Condition condition = null;
if (dataModel.getWebProviderRoles()) {
condition = new Condition();
condition.setType("StringEquals");
if (dataModel.getWebProvider().equals("Facebook")) {
condition.setConditionKey("graph.facebook.com:app_id");
} else if (dataModel.getWebProvider().equals("Google")) {
condition.setConditionKey("accounts.google.com:aud");
} else {
condition.setConditionKey("www.amazon.com:app_id");
}
List<String> value = new LinkedList<>();
value.add(dataModel.getApplicationId());
condition.setValues(value);
} else if (dataModel.getThirdPartyRoles()) {
if (dataModel.getThirdPartyRoles()) {
condition = new Condition();
condition.setType("StringEquals");
condition.setConditionKey("sts:ExternalId");
List<String> value = new LinkedList<>();
value.add(dataModel.getExternalAccountId());
condition.setValues(value);
}
}
return condition;
}
private Action generateAction() {
Action action = null;
if (dataModel.getWebProviderRoles()) {
action = SecurityTokenServiceActions.AssumeRoleWithWebIdentity;
} else {
action = SecurityTokenServiceActions.AssumeRole;
}
return action;
}
}
| 7,452 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/TrustedEntityTable.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.identitymanagement.role;
import java.util.Collection;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
public class TrustedEntityTable extends Composite {
private TableViewer viewer;
private Collection<Principal> principals;
public TrustedEntityTable(Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
TableColumnLayout tableColumnLayout = new TableColumnLayout();
this.setLayout(tableColumnLayout);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
final RoleTableContentProvider contentProvider = new RoleTableContentProvider();
RoleTableLabelProvider labelProvider = new RoleTableLabelProvider();
viewer = new TableViewer(this, SWT.MULTI);
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(false);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTable());
refresh();
}
private void createColumns(TableColumnLayout columnLayout, Table table) {
createColumn(table, columnLayout, "Trust Entities");
}
private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
private class RoleTableContentProvider extends ArrayContentProvider {
private Principal[] principals;
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Principal[])
principals = (Principal[]) newInput;
else
principals = new Principal[0];
}
@Override
public Object[] getElements(Object inputElement) {
return principals;
}
}
private class RoleTableLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
String result = null;
if (element instanceof Principal == false)
return "";
Principal principal = (Principal) element;
if (principal.getProvider().equalsIgnoreCase("AWS")) {
result = "AWS account " + principal.getId();
} else if (principal.getProvider().equalsIgnoreCase("Service")) {
result = "The service " + principal.getId();
}
return result;
}
}
public void setPrincipals(Collection<Principal> principals) {
this.principals = principals;
refresh();
}
public void refresh() {
new LoadRoleTableThread().start();
}
private class LoadRoleTableThread extends Thread {
@Override
public void run() {
try {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (principals == null) {
viewer.setInput(null);
} else {
viewer.setInput(principals.toArray(new Principal[principals.size()]));
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe roles", e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
| 7,453 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RoleTable.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.identitymanagement.role;
import java.util.List;
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.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.DeleteRoleRequest;
import com.amazonaws.services.identitymanagement.model.InstanceProfile;
import com.amazonaws.services.identitymanagement.model.ListInstanceProfilesForRoleRequest;
import com.amazonaws.services.identitymanagement.model.ListInstanceProfilesForRoleResult;
import com.amazonaws.services.identitymanagement.model.ListRolePoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListRolePoliciesResult;
import com.amazonaws.services.identitymanagement.model.RemoveRoleFromInstanceProfileRequest;
import com.amazonaws.services.identitymanagement.model.Role;
public class RoleTable extends Composite {
private TableViewer viewer;
private RoleSummary roleSummary;
private RolePermissions rolePermissions;
private RoleTrustRelationships roleTrustRelationships;
private RoleTableContentProvider contentProvider;
private AmazonIdentityManagement iam;
private final String DELTE_ROLE_CONFIRMATION = "All selected roles and their associated permissions will be deleted. This will affect applications using these roles. Do you want to continue?";
public RoleTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.iam = iam;
TableColumnLayout tableColumnLayout = new TableColumnLayout();
this.setLayout(tableColumnLayout);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
contentProvider = new RoleTableContentProvider();
RoleTableLabelProvider labelProvider = new RoleTableLabelProvider();
viewer = new TableViewer(this, SWT.BORDER | SWT.MULTI);
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Delete Role", DELTE_ROLE_CONFIRMATION);
if (confirmation) {
roleSummary.setRole(null);
rolePermissions.setRole(null);
roleTrustRelationships.setRole(null);
deleteMultipleGroups(viewer.getTable().getSelectionIndices());
}
}
@Override
public String getText() {
if (viewer.getTable().getSelectionIndices().length > 1) {
return "Delete Roles";
}
return "Delete Role";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
viewer.getTable().addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
int index = viewer.getTable().getSelectionIndex();
if (index >= 0) {
Role role = contentProvider.getItemByIndex(index);
roleSummary.setRole(role);
rolePermissions.setRole(role);
roleTrustRelationships.setRole(role);
} else {
roleSummary.setRole(null);
rolePermissions.setRole(null);
roleTrustRelationships.setRole(null);
}
}
});
createColumns(tableColumnLayout, viewer.getTable());
refresh();
}
private void createColumns(TableColumnLayout columnLayout, Table table) {
createColumn(table, columnLayout, "Role Name");
createColumn(table, columnLayout, "Creation Time");
}
private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
private class RoleTableContentProvider extends ArrayContentProvider {
private Role[] roles;
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Role[])
roles = (Role[]) newInput;
else
roles = new Role[0];
}
@Override
public Object[] getElements(Object inputElement) {
return roles;
}
public Role getItemByIndex(int index) {
return roles[index];
}
}
private class RoleTableLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Role == false)
return "";
Role role = (Role) element;
switch (columnIndex) {
case 0:
return role.getRoleName();
case 1:
return role.getCreateDate().toString();
default:
return "";
}
}
}
public void refresh() {
new LoadRoleTableThread().start();
}
public void setRoleSummary(RoleSummary roleSummary) {
this.roleSummary = roleSummary;
}
public void setRoleTrustRelationships(RoleTrustRelationships roleTruestRelationships) {
this.roleTrustRelationships = roleTruestRelationships;
}
public void setRolePermissions(RolePermissions rolePermissions) {
this.rolePermissions = rolePermissions;
}
private void deleteRole(String roleName) {
ListRolePoliciesResult listRolePolicyResult = iam.listRolePolicies(new ListRolePoliciesRequest().withRoleName(roleName));
for (String policyName : listRolePolicyResult.getPolicyNames()) {
iam.deleteRolePolicy(new DeleteRolePolicyRequest().withPolicyName(policyName).withRoleName(roleName));
}
ListInstanceProfilesForRoleResult listInstanceProfilesForRoleResult = iam.listInstanceProfilesForRole(new ListInstanceProfilesForRoleRequest().withRoleName(roleName));
for (InstanceProfile instanceProfile : listInstanceProfilesForRoleResult.getInstanceProfiles()) {
iam.removeRoleFromInstanceProfile(new RemoveRoleFromInstanceProfileRequest().withInstanceProfileName(instanceProfile.getInstanceProfileName()).withRoleName(roleName));
}
iam.deleteRole(new DeleteRoleRequest().withRoleName(roleName));
}
private void deleteMultipleGroups(final int[] indices) {
new Job("Delete roles") {
@Override
protected IStatus run(IProgressMonitor monitor) {
for (int index : indices) {
String roleName = contentProvider.getItemByIndex(index).getRoleName();
try {
deleteRole(roleName);
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete roles: " + e.getMessage(), e);
}
}
refresh();
return Status.OK_STATUS;
}
}.schedule();
}
private class LoadRoleTableThread extends Thread {
@Override
public void run() {
try {
final List<Role> roles;
roles = iam.listRoles().getRoles();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
viewer.setInput(roles.toArray(new Role[roles.size()]));
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe roles", e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
| 7,454 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RolePermissionTable.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.identitymanagement.role;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractPolicyTable;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteRolePolicyRequest;
import com.amazonaws.services.identitymanagement.model.ListRolePoliciesRequest;
import com.amazonaws.services.identitymanagement.model.Role;
public class RolePermissionTable extends AbstractPolicyTable {
private Role role;
RolePermissionTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(iam, parent, toolkit);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new removePolicyAction());
manager.add(new ShowPolicyAction());
manager.add(new EditPolicyAction());
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
private class removePolicyAction extends Action {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
String alertMessage = "Are you sure you want to remove policy '" + policyName + "' from the role '" + role.getRoleName() + "'?";
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Remove Policy", alertMessage);
if (confirmation) {
deletePolicy(policyName);
refresh();
}
}
@Override
public String getText() {
return "Remove Policy";
}
}
private class ShowPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowRolePolicyDialog(iam, Display.getCurrent().getActiveShell(), role, policyName, false).open();
refresh();
}
@Override
public String getText() {
return "Show Policy";
}
}
private class EditPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowRolePolicyDialog(iam, Display.getCurrent().getActiveShell(), role, policyName, true).open();
refresh();
}
@Override
public String getText() {
return "Edit Policy";
}
}
private void deletePolicy(String policyName) {
iam.deleteRolePolicy(new DeleteRolePolicyRequest().withRoleName(role.getRoleName()).withPolicyName(policyName));
}
@Override
protected void getPolicyNames() {
if (role != null) {
policyNames = iam.listRolePolicies(new ListRolePoliciesRequest().withRoleName(role.getRoleName())).getPolicyNames();
} else {
policyNames = null;
}
}
public void setRole(Role role) {
this.role = role;
refresh();
}
@Override
public void refresh() {
new LoadPermissionTableThread().start();
}
}
| 7,455 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/CreateRoleWizardDataModel.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.identitymanagement.role;
public class CreateRoleWizardDataModel {
private String roleName;
// The service name for the service role
private String service;
private String accountId;
private String internalAccountId;
private String externalAccountId;
private String webProvider;
private String applicationId;
private String policyName;
private String policyDoc;
private boolean grantPermission;
// Whether to create a service role
private boolean serviceRoles;
// Whether to create a role using your own AWS account
private boolean accountRoles;
// Whether to create a role using third party AWS account
private boolean thirdPartyRoles;
// Whether to create a role using web federation
private boolean webProviderRoles;
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRoleName() {
return roleName;
}
public void setService(String service) {
this.service = service;
}
public String getService() {
return service;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountId() {
return accountId;
}
public void setInternalAccountId(String internalAccountId) {
this.internalAccountId = internalAccountId;
}
public String getInternalAccountId() {
return internalAccountId;
}
public void setExternalAccountId(String externalAccountId) {
this.externalAccountId = externalAccountId;
}
public String getExternalAccountId() {
return externalAccountId;
}
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
public String getPolicyName() {
return policyName;
}
public void setPolicyDoc(String policyDoc) {
this.policyDoc = policyDoc;
}
public String getPolicyDoc() {
return policyDoc;
}
public boolean getGrantPermission() {
return grantPermission;
}
public void setGrantPermission(boolean grantPermission) {
this.grantPermission = grantPermission;
}
public void setServiceRoles(boolean serviceRoles) {
this.serviceRoles = serviceRoles;
}
public boolean getServiceRoles() {
return serviceRoles;
}
public void setAccountRoles(boolean accountRoles) {
this.accountRoles = accountRoles;
}
public boolean getAccountRoles() {
return accountRoles;
}
public void setThirdPartyRoles(boolean thirdPartyRoles) {
this.thirdPartyRoles = thirdPartyRoles;
}
public boolean getThirdPartyRoles() {
return thirdPartyRoles;
}
public boolean getWebProviderRoles() {
return webProviderRoles;
}
public void setWebProviderRoles(boolean webProviderRoles) {
this.webProviderRoles = webProviderRoles;
}
public void setWebProvider(String webProvider) {
this.webProvider = webProvider;
}
public String getWebProvider() {
return this.webProvider;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
public String getApplicationId() {
return applicationId;
}
}
| 7,456 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/CreateRoleFirstPage.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.identitymanagement.role;
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.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
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.NotEmptyValidator;
import com.amazonaws.eclipse.identitymanagement.databinding.DataBindingUtils;
public class CreateRoleFirstPage extends WizardPage {
private Text roleNameText;
private IObservableValue roleName;
private final static String OK_MESSAGE = "Specifiy a role name.";
private final DataBindingContext bindingContext = new DataBindingContext();
protected CreateRoleFirstPage(CreateRoleWizard wizard) {
super(OK_MESSAGE);
setMessage(OK_MESSAGE);
roleName = PojoObservables.observeValue(wizard.getDataModel(), "roleName");
}
@Override
public void createControl(Composite parent) {
final Composite comp = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(comp);
comp.setLayout(new GridLayout(1, false));
new Label(comp, SWT.NONE).setText("Role Name:");;
roleNameText = new Text(comp, SWT.BORDER);
bindingContext.bindValue(SWTObservables.observeText(roleNameText, SWT.Modify), roleName);
ChainValidator<String> roleNameValidationStatusProvider = new ChainValidator<>(roleName,
new NotEmptyValidator("Please provide a valid role name"));
bindingContext.addValidationStatusProvider(roleNameValidationStatusProvider);
DataBindingUtils.addStatusDecorator(roleNameText, roleNameValidationStatusProvider);
GridDataFactory.fillDefaults().grab(true, false).applyTo(roleNameText);
// Finally provide aggregate status reporting for the entire wizard page
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false)
return;
IStatus status = (IStatus) value;
if (status.isOK()) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if (status.getSeverity() == Status.WARNING) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if (status.getSeverity() == Status.ERROR) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
});
setPageComplete(false);
setControl(comp);
}
}
| 7,457 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RoleEditor.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.identitymanagement.role;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.explorer.identitymanagement.CreateRoleAction;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
public class RoleEditor extends EditorPart implements IRefreshable {
private EditorInput roleEditorInput;
private RoleSummary roleSummary;
private RolePermissions rolePermissions;
private RoleTable roleTable;
private RoleTrustRelationships roleTrustRelationships;
private AmazonIdentityManagement iam;
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.roleEditorInput = (EditorInput)input;
iam = getClient();
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL);
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.setBackground(toolkit.getColors().getBackground());
form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
form.setFont(JFaceResources.getHeaderFont());
form.setText(getFormTitle());
toolkit.decorateFormHeading(form.getForm());
form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ROLE));
form.getBody().setLayout(new GridLayout());
SashForm sash = new SashForm(form.getBody(), SWT.VERTICAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
sash.setLayout(new GridLayout());
createTablesSection(sash, toolkit);
createTabsSection(sash, toolkit);
form.getToolBarManager().add(new RefreshAction());
form.getToolBarManager().add(new CreateRoleAction(iam, this));
form.getToolBarManager().update(true);
roleTable.setRoleSummary(roleSummary);
roleTable.setRolePermissions(rolePermissions);
roleTable.setRoleTrustRelationships(roleTrustRelationships);
}
private String getFormTitle() {
String formTitle = roleEditorInput.getName();
return formTitle;
}
private void createTabsSection(Composite parent, FormToolkit toolkit) {
Composite tabsSection = toolkit.createComposite(parent, SWT.NONE);
tabsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tabsSection.setLayout(new FillLayout());
TabFolder tabFolder = new TabFolder (tabsSection, SWT.BORDER);
Rectangle clientArea = parent.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
TabItem summaryTab = new TabItem(tabFolder, SWT.NONE);
summaryTab.setText("Summary");
roleSummary = new RoleSummary(iam, tabFolder, toolkit);
summaryTab.setControl(roleSummary);
TabItem permissionTab = new TabItem(tabFolder, SWT.NONE);
permissionTab.setText("Permissions");
rolePermissions = new RolePermissions(iam, tabFolder, toolkit);
permissionTab.setControl(rolePermissions);
TabItem trustRelationshipsTab = new TabItem(tabFolder, SWT.NONE);
trustRelationshipsTab.setText("Trust Relationships");
roleTrustRelationships = new RoleTrustRelationships(iam, tabFolder, toolkit);
trustRelationshipsTab.setControl(roleTrustRelationships);
}
private void createTablesSection(Composite parent, FormToolkit toolkit) {
roleTable = new RoleTable(iam, parent, toolkit);
}
@Override
public void setFocus() {}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
roleTable.refresh();
roleSummary.refresh();
}
}
@Override
public void refreshData() {
roleTable.refresh();
}
protected AmazonIdentityManagement getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(roleEditorInput.getAccountId());
return clientFactory.getIAMClientByEndpoint(roleEditorInput.getRegionEndpoint());
}
}
| 7,458 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RoleTrustRelationships.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.identitymanagement.role;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.auth.policy.Policy;
import com.amazonaws.auth.policy.Principal;
import com.amazonaws.auth.policy.Statement;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Role;
public class RoleTrustRelationships extends Composite {
private TrustedEntityTable trustEntitiesTable;
private Role role;
private Button editPolicyButton;
public RoleTrustRelationships(final AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
this.setLayout(new GridLayout(1, false));
this.setBackground(toolkit.getColors().getBackground());
Section trustedEntitiesSection = toolkit.createSection(this, Section.TITLE_BAR);
trustedEntitiesSection.setText("Trusted Entities");
trustedEntitiesSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(trustedEntitiesSection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
trustEntitiesTable = new TrustedEntityTable(client, toolkit);
trustEntitiesTable.setLayoutData(new GridData(GridData.FILL_BOTH));
editPolicyButton = toolkit.createButton(client, "Edit Trust Relationship", SWT.BUTTON1);
editPolicyButton.setEnabled(false);
editPolicyButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
editPolicyButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
EditTrustRelationshipDialog dialog = new EditTrustRelationshipDialog(iam, Display.getCurrent().getActiveShell(), role);
dialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
trustedEntitiesSection.setClient(client);
}
public void setRole(Role role) {
this.role = role;
String assumeRolePolicyDocument = null;
if (role != null && role.getAssumeRolePolicyDocument() != null) {
editPolicyButton.setEnabled(true);
try {
assumeRolePolicyDocument = URLDecoder.decode(role.getAssumeRolePolicyDocument(), "UTF-8");
} catch (UnsupportedEncodingException e) {
StatusManager.getManager().handle(
new Status(IStatus.ERROR, IdentityManagementPlugin.PLUGIN_ID, "Error show trust relationship for role "
+ role.getRoleName() + ": " + e.getMessage()), StatusManager.SHOW);
}
} else {
editPolicyButton.setEnabled(false);
trustEntitiesTable.setPrincipals(null);
return;
}
List<Principal> principals = new LinkedList<>();
for (Statement statement : Policy.fromJson(assumeRolePolicyDocument).getStatements()) {
principals.addAll(statement.getPrincipals());
}
trustEntitiesTable.setPrincipals(principals);
}
}
| 7,459 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/RolePermissions.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.identitymanagement.role;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Role;
public class RolePermissions extends Composite {
private Role role;
private RolePermissionTable rolePermissionTable;
private Button addPolicyButton;
public RolePermissions(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
this.setBackground(toolkit.getColors().getBackground());
this.setLayout(new GridLayout());
Section policySection = toolkit.createSection(this, Section.TITLE_BAR);
policySection.setText("Role Policies");
policySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(policySection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
rolePermissionTable = new RolePermissionTable(iam, client, toolkit);
rolePermissionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
addPolicyButton = toolkit.createButton(client, "Attach Policy", SWT.PUSH);
addPolicyButton.setEnabled(false);
addPolicyButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
addPolicyButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
addPolicyButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
AddRolePolicyDialog addRolePolicyDialog = new AddRolePolicyDialog(iam, Display.getCurrent().getActiveShell(), toolkit, role, rolePermissionTable);
addRolePolicyDialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
policySection.setClient(client);
}
public void setRole(Role role) {
this.role = role;
if (role != null) {
addPolicyButton.setEnabled(true);
} else {
addPolicyButton.setEnabled(false);
}
rolePermissionTable.setRole(role);
}
}
| 7,460 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/role/CreateRoleThirdPage.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.identitymanagement.role;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
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.FileLocator;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.eclipse.identitymanagement.databinding.DataBindingUtils;
public class CreateRoleThirdPage extends WizardPage {
private Text policyDocText;
private Text policyNameText;
private Button grantPermissionButton;
private final String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/AccessPolicyLanguage_KeyConcepts.html";
private final DataBindingContext bindingContext = new DataBindingContext();
private CreateRoleWizard wizard;
private IObservableValue policyName;
private IObservableValue policyDoc;
private IObservableValue grantPermission;
private final static String OK_MESSAGE = "You can customize permissions by editing the following policy document.";
public CreateRoleThirdPage(CreateRoleWizard wizard) {
super(OK_MESSAGE);
setMessage(OK_MESSAGE);
policyName = PojoObservables.observeValue(wizard.getDataModel(), "policyName");
policyDoc = PojoObservables.observeValue(wizard.getDataModel(), "policyDoc");
grantPermission = PojoObservables.observeValue(wizard.getDataModel(), "grantPermission");
this.wizard = wizard;
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
layout.marginLeft = 5;
composite.setLayout(layout);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
grantPermissionButton = new Button(composite, SWT.CHECK);
grantPermissionButton.setText("Grant permissions");
grantPermissionButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (grantPermissionButton.getSelection()) {
policyNameText.setEnabled(true);
policyDocText.setEnabled(true);
} else {
policyNameText.setEnabled(false);
policyDocText.setEnabled(false);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
bindingContext.bindValue(SWTObservables.observeSelection(grantPermissionButton), grantPermission);
new Label(composite, SWT.NONE).setText("Policy Name:");
policyNameText = new Text(composite, SWT.BORDER);
policyNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
bindingContext.bindValue(SWTObservables.observeText(policyNameText, SWT.Modify), policyName);
ChainValidator<String> policyNameValidationStatusProvider = new ChainValidator<>(policyName,
grantPermission, new NotEmptyValidator("Please enter policy name"));
bindingContext.addValidationStatusProvider(policyNameValidationStatusProvider);
DataBindingUtils.addStatusDecorator(policyNameText, policyNameValidationStatusProvider);
new Label(composite, SWT.NONE).setText("Policy Documentation:");
policyDocText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.minimumHeight = 250;
policyDocText.setLayoutData(gridData);
bindingContext.bindValue(SWTObservables.observeText(policyDocText, SWT.Modify), policyDoc);
ChainValidator<String> policyDocValidationStatusProvider = new ChainValidator<>(policyDoc,
grantPermission, new NotEmptyValidator("Please enter valid policy doc"));
bindingContext.addValidationStatusProvider(policyDocValidationStatusProvider);
DataBindingUtils.addStatusDecorator(policyDocText, policyDocValidationStatusProvider);
Link link = new Link(composite, SWT.NONE | SWT.WRAP);
link.setText("For more information about the access policy language, " +
"see <a href=\"" +
ConceptUrl + "\">Key Concepts</a> in Using AWS Identity and Access Management.");
link.addListener(SWT.Selection, new WebLinkListener());
gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
link.setLayoutData(gridData);
// Finally provide aggregate status reporting for the entire wizard page
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.isOK() ) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if ( status.getSeverity() == Status.WARNING ) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if ( status.getSeverity() == Status.ERROR ) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
});
setControl(composite);
}
@Override
public void setVisible(boolean visible) {
if (visible) {
if (wizard.getDataModel().getServiceRoles()) {
policyNameText.setEnabled(true);
policyDocText.setEnabled(true);
grantPermissionButton.setSelection(true);
bindingContext.updateModels();
} else {
policyNameText.setEnabled(false);
policyDocText.setEnabled(false);
setPageComplete(true);
}
setDefaultValue();
}
super.setVisible(true);
}
private void setDefaultValue() {
File templateFile = null;
CreateRoleWizardDataModel dataModel = wizard.getDataModel();
String policyContent = null;
String path = null;
String fileName = null;
if (dataModel.getServiceRoles()) {
if (dataModel.getService().startsWith("Amazon Elastic Transcoder")) {
dataModel.setPolicyName("AmazonElasticTranscoder-3123123-201303261252");
fileName = "AmazonElasticTranscoder-3123123-201303261252";
} else if (dataModel.getService().startsWith("AWS Data Pipeline")) {
dataModel.setPolicyName("AWSDataPipeline-123456-201303261249");
fileName = "AWSDataPipeline-123456-201303261249";
} else if (dataModel.getService().startsWith("AWS OpsWorks")) {
dataModel.setPolicyName("AWSOpsWorks-3123123-201303261253");
fileName = "AWSOpsWorks-3123123-201303261253";
} else if (dataModel.getService().startsWith("Amazon EC2 Role for Data Pipeline")) {
dataModel.setPolicyName("AmazonEC2RoleforDataPipeline-3123445-20");
fileName = "AmazonEC2RoleforDataPipeline-3123445-20";
} else {
fileName = null;
}
if (fileName == null) {
dataModel.setPolicyName("");
dataModel.setPolicyDoc("");
} else {
try {
path = getPolicyTemplatesPath();
templateFile = new File(path + "AmazonEC2RoleforDataPipeline-3123445-20");
policyContent = FileUtils.readFileToString(templateFile);
dataModel.setPolicyDoc(policyContent);
} catch (Exception e) {
StatusManager.getManager().handle(new Status(IStatus.ERROR, IdentityManagementPlugin.PLUGIN_ID, "Error loading the policy template" + ": " + e.getMessage()), StatusManager.SHOW);
}
}
}
bindingContext.updateTargets();
}
private String getPolicyTemplatesPath() throws IOException {
return FileLocator.toFileURL(Platform.getBundle(IdentityManagementPlugin.PLUGIN_ID).getEntry("/policyTemplates")).getPath();
}
}
| 7,461 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/ShowGroupPolicyDialog.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.identitymanagement.group;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.GetGroupPolicyRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.PutGroupPolicyRequest;
class ShowGroupPolicyDialog extends TitleAreaDialog {
private final boolean edittable;
private Text policyText;
private final Group group;
private final String policyName;
private AmazonIdentityManagement iam;
public ShowGroupPolicyDialog(AmazonIdentityManagement iam, Shell parentShell, Group group, String policyName, boolean edittable) {
super(parentShell);
this.iam = iam;
this.edittable = edittable;
this.group = group;
this.policyName = policyName;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Policy Name :");
setMessage(policyName);
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
policyText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
try {
policyText.setText(getPolicy(policyName));
} catch (Exception e) {
setErrorMessage(e.getMessage());
}
policyText.setLayoutData(new GridData(GridData.FILL_BOTH));
if (!edittable) {
policyText.setEditable(false);
}
Dialog.applyDialogFont(parent);
return composite;
}
@Override
protected void okPressed() {
try {
if (edittable) {
putPolicy(policyName, policyText.getText());
}
} catch (Exception e) {
setErrorMessage(e.getMessage());
return;
}
super.okPressed();
}
private String getPolicy(String policyName) throws UnsupportedEncodingException {
String policyDoc = iam.getGroupPolicy(new GetGroupPolicyRequest().withGroupName(group.getGroupName()).withPolicyName(policyName))
.getPolicyDocument();
return URLDecoder.decode(policyDoc, "UTF-8");
}
private void putPolicy(String policyName, String policyDoc) {
iam.putGroupPolicy(new PutGroupPolicyRequest().withGroupName(group.getGroupName()).withPolicyName(policyName).withPolicyDocument(policyDoc));
}
}
| 7,462 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/EditGroupNameDialog.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.identitymanagement.group;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
public class EditGroupNameDialog extends MessageDialog {
private String newGroupName = "";
private String oldGroupName;
public String getNewGroupName() {
return newGroupName.trim();
}
public String getOldGroupName() {
return oldGroupName.trim();
}
protected EditGroupNameDialog(String groupName) {
super(Display.getCurrent().getActiveShell(), "Enter New Group Name", null, "Enter a new group name", MessageDialog.NONE, new String[] { "OK", "Cancel" }, 0);
this.oldGroupName = groupName;
}
@Override
protected Control createCustomArea(Composite parent) {
final Text text = new Text(parent, SWT.BORDER);
text.setText(oldGroupName);
GridDataFactory.fillDefaults().grab(true, false).span(2, 1).applyTo(text);
text.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
newGroupName = text.getText();
validate();
}
});
return parent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
validate();
}
public void validate() {
if (getButton(0) == null)
return;
if (getNewGroupName().length() == 0 || getNewGroupName().equals(getOldGroupName())) {
getButton(0).setEnabled(false);
return;
}
getButton(0).setEnabled(true);
return;
}
}
| 7,463 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/GroupSummary.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.identitymanagement.group;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.GetGroupRequest;
import com.amazonaws.services.identitymanagement.model.Group;
public class GroupSummary extends Composite {
private Group group;
private final Text groupARNLable;
private final Text usersInGroupLabel;
private final Text pathLabel;
private final Text creationTimeLabel;
private AmazonIdentityManagement iam;
public GroupSummary(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.iam = iam;
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
this.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
this.setLayout(new GridLayout(4, false));
this.setBackground(toolkit.getColors().getBackground());
toolkit.createLabel(this, "Group ARN:");
groupARNLable = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(groupARNLable);
toolkit.createLabel(this, "Users:");
usersInGroupLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(usersInGroupLabel);
toolkit.createLabel(this, "Path:");
pathLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(pathLabel);
toolkit.createLabel(this, "Creation Time:");
creationTimeLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(creationTimeLabel);
}
public void setGroup(Group group) {
this.group = group;
refresh();
}
public void refresh() {
new LoadGroupSummaryThread().start();
}
private class LoadGroupSummaryThread extends Thread {
@Override
public void run() {
try {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (group != null) {
groupARNLable.setText(group.getArn());
pathLabel.setText(group.getPath());
creationTimeLabel.setText(group.getCreateDate().toString());
int usersInGroup = iam.getGroup(new GetGroupRequest().withGroupName(group.getGroupName())).getUsers().size();
usersInGroupLabel.setText(Integer.toString(usersInGroup));
} else {
groupARNLable.setText("");
pathLabel.setText("");
creationTimeLabel.setText("");
usersInGroupLabel.setText("");
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe group summary", e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
| 7,464 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/GroupPermissionTable.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.identitymanagement.group;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractPolicyTable;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteGroupPolicyRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.ListGroupPoliciesRequest;
public class GroupPermissionTable extends AbstractPolicyTable {
private Group group;
GroupPermissionTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(iam, parent, toolkit);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new removePolicyAction());
manager.add(new ShowPolicyAction());
manager.add(new EditPolicyAction());
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
private class removePolicyAction extends Action {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
String alertMessage = "Are you sure you want to remove policy '" + policyName + "' from the group '" + group.getGroupName() + "'?";
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Remove Policy", alertMessage);
if (confirmation) {
deletePolicy(policyName);
refresh();
}
}
@Override
public String getText() {
return "Remove Policy";
}
}
private class ShowPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowGroupPolicyDialog(iam, Display.getCurrent().getActiveShell(), group, policyName, false).open();
refresh();
}
@Override
public String getText() {
return "Show Policy";
}
}
private class EditPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowGroupPolicyDialog(iam, Display.getCurrent().getActiveShell(), group, policyName, true).open();
refresh();
}
@Override
public String getText() {
return "Edit Policy";
}
}
private void deletePolicy(String policyName) {
iam.deleteGroupPolicy(new DeleteGroupPolicyRequest().withGroupName(group.getGroupName()).withPolicyName(policyName));
}
@Override
protected void getPolicyNames() {
if (group != null) {
policyNames = iam.listGroupPolicies(new ListGroupPoliciesRequest().withGroupName(group.getGroupName())).getPolicyNames();
} else {
policyNames = null;
}
}
public void setGroup(Group group) {
this.group = group;
refresh();
}
@Override
public void refresh() {
new LoadPermissionTableThread().start();
}
}
| 7,465 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/CreateGroupSecondPage.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.identitymanagement.group;
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.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.identitymanagement.databinding.DataBindingUtils;
public class CreateGroupSecondPage extends WizardPage {
private Text policyDocText;
private Text policyNameText;
private Button grantPermissionButton;
private final String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/AccessPolicyLanguage_KeyConcepts.html";
private final DataBindingContext bindingContext = new DataBindingContext();
private IObservableValue policyName;
private IObservableValue policyDoc;
private IObservableValue grantPermission;
private final static String OK_MESSAGE = "You can customize permissions by editing the following policy document.";
public CreateGroupSecondPage(CreateGroupWizard wizard) {
super(OK_MESSAGE);
setMessage(OK_MESSAGE);
policyName = PojoObservables.observeValue(wizard.getDataModel(), "policyName");
policyDoc = PojoObservables.observeValue(wizard.getDataModel(), "policyDoc");
grantPermission = PojoObservables.observeValue(wizard.getDataModel(), "grantPermission");
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout(1, false);
layout.marginLeft = 5;
composite.setLayout(layout);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
grantPermissionButton = new Button(composite, SWT.CHECK);
grantPermissionButton.setText("Grant permissions");
grantPermissionButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
if (grantPermissionButton.getSelection()) {
policyNameText.setEnabled(true);
policyDocText.setEnabled(true);
} else {
policyNameText.setEnabled(false);
policyDocText.setEnabled(false);
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
bindingContext.bindValue(SWTObservables.observeSelection(grantPermissionButton), grantPermission);
new Label(composite, SWT.NONE).setText("Policy Name:");
policyNameText = new Text(composite, SWT.BORDER);
policyNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
bindingContext.bindValue(SWTObservables.observeText(policyNameText, SWT.Modify), policyName);
ChainValidator<String> policyNameValidationStatusProvider = new ChainValidator<>(policyName,
grantPermission, new NotEmptyValidator("Please enter policy name"));
bindingContext.addValidationStatusProvider(policyNameValidationStatusProvider);
DataBindingUtils.addStatusDecorator(policyNameText, policyNameValidationStatusProvider);
new Label(composite, SWT.NONE).setText("Policy Documentation:");
policyDocText = new Text(composite, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER | SWT.H_SCROLL);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.minimumHeight = 250;
policyDocText.setLayoutData(gridData);
bindingContext.bindValue(SWTObservables.observeText(policyDocText, SWT.Modify), policyDoc);
ChainValidator<String> policyDocValidationStatusProvider = new ChainValidator<>(policyDoc,
grantPermission, new NotEmptyValidator("Please enter valid policy doc"));
bindingContext.addValidationStatusProvider(policyDocValidationStatusProvider);
DataBindingUtils.addStatusDecorator(policyDocText, policyDocValidationStatusProvider);
Link link = new Link(composite, SWT.NONE | SWT.WRAP);
link.setText("For more information about the access policy language, " +
"see <a href=\"" +
ConceptUrl + "\">Key Concepts</a> in Using AWS Identity and Access Management.");
link.addListener(SWT.Selection, new WebLinkListener());
gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
link.setLayoutData(gridData);
setControl(composite);
setPageComplete(false);
// Finally provide aggregate status reporting for the entire wizard page
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext,
AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if ( value instanceof IStatus == false )
return;
IStatus status = (IStatus) value;
if ( status.isOK() ) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if ( status.getSeverity() == Status.WARNING ) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if ( status.getSeverity() == Status.ERROR ) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
});
policyNameText.setEnabled(false);
policyDocText.setEnabled(false);
setPageComplete(true);
}
}
| 7,466 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/CreateGroupFirstPage.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.identitymanagement.group;
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.core.runtime.Status;
import org.eclipse.jface.databinding.swt.SWTObservables;
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.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.databinding.ChainValidator;
import com.amazonaws.eclipse.databinding.NotEmptyValidator;
import com.amazonaws.eclipse.identitymanagement.databinding.DataBindingUtils;
public class CreateGroupFirstPage extends WizardPage {
private Text groupNameText;
private IObservableValue groupName;
private final DataBindingContext bindingContext = new DataBindingContext();
private final static String OK_MESSAGE = "Specify a group name";
protected CreateGroupFirstPage(CreateGroupWizard wizard) {
super(OK_MESSAGE);
setMessage(OK_MESSAGE);
groupName = PojoObservables.observeValue(wizard.getDataModel(), "groupName");
}
@Override
public void createControl(Composite parent) {
final Composite comp = new Composite(parent, SWT.NONE);
comp.setLayoutData(new GridData(GridData.FILL_BOTH));
comp.setLayout(new GridLayout(1, false));
new Label(comp, SWT.NONE).setText("Group Name:");
groupNameText = new Text(comp, SWT.BORDER);
groupNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
bindingContext.bindValue(SWTObservables.observeText(groupNameText, SWT.Modify), groupName);
ChainValidator<String> groupNameValidationStatusProvider = new ChainValidator<>(groupName,
new NotEmptyValidator("Please provide a group name"));
bindingContext.addValidationStatusProvider(groupNameValidationStatusProvider);
DataBindingUtils.addStatusDecorator(groupNameText, groupNameValidationStatusProvider);
// Finally provide aggregate status reporting for the entire wizard page
final AggregateValidationStatus aggregateValidationStatus = new AggregateValidationStatus(bindingContext, AggregateValidationStatus.MAX_SEVERITY);
aggregateValidationStatus.addChangeListener(new IChangeListener() {
@Override
public void handleChange(ChangeEvent event) {
Object value = aggregateValidationStatus.getValue();
if (value instanceof IStatus == false)
return;
IStatus status = (IStatus) value;
if (status.isOK()) {
setErrorMessage(null);
setMessage(OK_MESSAGE, Status.OK);
} else if (status.getSeverity() == Status.WARNING) {
setErrorMessage(null);
setMessage(status.getMessage(), Status.WARNING);
} else if (status.getSeverity() == Status.ERROR) {
setErrorMessage(status.getMessage());
}
setPageComplete(status.isOK());
}
});
setControl(comp);
setPageComplete(false);
}
}
| 7,467 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/GroupEditor.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.identitymanagement.group;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.explorer.identitymanagement.CreateGroupAction;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
public class GroupEditor extends EditorPart implements IRefreshable {
private EditorInput groupEditorInput;
private GroupSummary groupSummary;
private UsersInGroup usersInGroup;
private GroupTable groupTable;
private GroupPermissions groupPermissions;
private AmazonIdentityManagement iam;
@Override
public void doSave(IProgressMonitor monitor) {}
@Override
public void doSaveAs() {}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.groupEditorInput = (EditorInput)input;
iam = getClient();
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL);
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.setBackground(toolkit.getColors().getBackground());
form.setForeground(toolkit.getColors().getColor(IFormColors.TITLE));
form.setFont(JFaceResources.getHeaderFont());
form.setText(getFormTitle());
toolkit.decorateFormHeading(form.getForm());
form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_GROUP));
form.getBody().setLayout(new GridLayout());
SashForm sash = new SashForm(form.getBody(), SWT.VERTICAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
sash.setLayout(new GridLayout());
createTableSection(sash, toolkit);
createTabsSection(sash, toolkit);
form.getToolBarManager().add(new RefreshAction());
form.getToolBarManager().add(new CreateGroupAction(iam, this));
form.getToolBarManager().update(true);
groupTable.setGroupSummary(groupSummary);
groupTable.setUsersInGroup(usersInGroup);
groupTable.setGroupPermissions(groupPermissions);
}
private String getFormTitle() {
String formTitle = groupEditorInput.getName();
return formTitle;
}
private void createTabsSection(Composite parent, FormToolkit toolkit) {
Composite tabsSection = toolkit.createComposite(parent, SWT.NONE);
tabsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tabsSection.setLayout(new FillLayout());
TabFolder tabFolder = new TabFolder (tabsSection, SWT.BORDER);
Rectangle clientArea = parent.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
TabItem summaryTab = new TabItem(tabFolder, SWT.NONE);
summaryTab.setText("Summary");
groupSummary = new GroupSummary(iam, tabFolder, toolkit);
summaryTab.setControl(groupSummary);
TabItem usersTab = new TabItem(tabFolder, SWT.NONE);
usersTab.setText("Users");
usersInGroup = new UsersInGroup(iam, tabFolder, toolkit, groupEditorInput);
usersTab.setControl(usersInGroup);
TabItem permissionsTab = new TabItem(tabFolder, SWT.NONE);
permissionsTab.setText("Permissions");
groupPermissions = new GroupPermissions(iam, tabFolder, toolkit);
permissionsTab.setControl(groupPermissions);
}
private void createTableSection(Composite parent, FormToolkit toolkit) {
groupTable = new GroupTable(iam, parent, toolkit);
}
@Override
public void setFocus() {}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
groupSummary.refresh();
groupTable.refresh();
usersInGroup.refresh();
}
}
@Override
public void refreshData() {
groupTable.refresh();
}
protected AmazonIdentityManagement getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(groupEditorInput.getAccountId());
return clientFactory.getIAMClientByEndpoint(groupEditorInput.getRegionEndpoint());
}
}
| 7,468 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/CreateGroupWizardDataModel.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.identitymanagement.group;
public class CreateGroupWizardDataModel {
private String groupName;
// Whether grant permission to the group to create.
private boolean grantPermission;
private String policyName;
private String policyDoc;
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public boolean getGrantPermission() {
return grantPermission;
}
public void setGrantPermission(boolean grantPermission) {
this.grantPermission = grantPermission;
}
public String getPolicyName() {
return policyName;
}
public void setPolicyName(String policyName) {
this.policyName = policyName;
}
public String getPolicyDoc() {
return policyDoc;
}
public void setPolicyDoc(String policyDoc) {
this.policyDoc = policyDoc;
}
}
| 7,469 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/GroupPermissions.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.identitymanagement.group;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Group;
public class GroupPermissions extends Composite {
private Group group;
private GroupPermissionTable groupPermissionTable;
private Button addPolicyButton;
public GroupPermissions(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
this.setBackground(toolkit.getColors().getBackground());
this.setLayout(new GridLayout());
Section policySection = toolkit.createSection(this, Section.TITLE_BAR);
policySection.setText("Group Policies");
policySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(policySection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
groupPermissionTable = new GroupPermissionTable(iam, client, toolkit);
groupPermissionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
addPolicyButton = toolkit.createButton(client, "Attach Policy", SWT.PUSH);
addPolicyButton.setEnabled(false);
addPolicyButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
addPolicyButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
addPolicyButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
AddGroupPolicyDialog addGroupPolicyDialog = new AddGroupPolicyDialog(iam, Display.getCurrent().getActiveShell(), toolkit, group, groupPermissionTable);
addGroupPolicyDialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
policySection.setClient(client);
}
public void setGroup(Group group) {
this.group = group;
if (group != null) {
addPolicyButton.setEnabled(true);
} else {
addPolicyButton.setEnabled(false);
}
groupPermissionTable.setGroup(group);
}
}
| 7,470 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/GroupTable.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.identitymanagement.group;
import java.util.List;
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.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractGroupTable;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteGroupPolicyRequest;
import com.amazonaws.services.identitymanagement.model.DeleteGroupRequest;
import com.amazonaws.services.identitymanagement.model.GetGroupRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.ListGroupPoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListGroupPoliciesResult;
import com.amazonaws.services.identitymanagement.model.RemoveUserFromGroupRequest;
import com.amazonaws.services.identitymanagement.model.UpdateGroupRequest;
import com.amazonaws.services.identitymanagement.model.User;
public class GroupTable extends AbstractGroupTable {
private GroupSummary groupSummary;
private UsersInGroup usersInGroup;
private GroupPermissions groupPermissions;
private final String DELTE_GROUP_CONFIRMATION = "All users and permissions belonging to the selected groups will be removed from the group first. Do you want to continue?";
public GroupTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(iam, parent, toolkit);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Delete Group", DELTE_GROUP_CONFIRMATION);
if (confirmation) {
groupSummary.setGroup(null);
usersInGroup.setGroup(null);
groupPermissions.setGroup(null);
deleteMultipleGroups(viewer.getTable().getSelectionIndices());
}
}
@Override
public String getText() {
if (viewer.getTable().getSelectionIndices().length > 1) {
return "Delete Groups";
}
return "Delete Group";
}
});
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return null;
}
@Override
public void run() {
EditGroupNameDialog editGroupNameDialog = new EditGroupNameDialog(contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex()).getGroupName());
if (editGroupNameDialog.open() == 0) {
editGroupName(editGroupNameDialog.getOldGroupName(), editGroupNameDialog.getNewGroupName());
}
}
@Override
public String getText() {
return "Edit Group Name";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
viewer.getTable().addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
int index = viewer.getTable().getSelectionIndex();
if (index >= 0) {
Group group = contentProvider.getItemByIndex(index);
groupSummary.setGroup(group);
usersInGroup.setGroup(group);
groupPermissions.setGroup(group);
} else {
groupSummary.setGroup(null);
usersInGroup.setGroup(null);
groupPermissions.setGroup(null);
}
}
});
}
public void setGroupSummary(GroupSummary groupSummary) {
this.groupSummary = groupSummary;
}
public void setUsersInGroup(UsersInGroup usersInGroup) {
this.usersInGroup = usersInGroup;
}
public void setGroupPermissions(GroupPermissions groupPermissions) {
this.groupPermissions = groupPermissions;
}
private void deleteGroup(String groupName) {
ListGroupPoliciesResult listGroupPoliciesResult = iam.listGroupPolicies(new ListGroupPoliciesRequest().withGroupName(groupName));
for (String policyName : listGroupPoliciesResult.getPolicyNames()) {
iam.deleteGroupPolicy(new DeleteGroupPolicyRequest().withGroupName(groupName).withPolicyName(policyName));
}
List<User> usersInGroup = iam.getGroup(new GetGroupRequest().withGroupName(groupName)).getUsers();
for (User user : usersInGroup) {
iam.removeUserFromGroup(new RemoveUserFromGroupRequest().withGroupName(groupName).withUserName(user.getUserName()));
}
iam.deleteGroup(new DeleteGroupRequest().withGroupName(groupName));
}
private void editGroupName(final String oldGroupName, final String newGroupName) {
new Job("Edit group name") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
iam.updateGroup(new UpdateGroupRequest().withGroupName(oldGroupName).withNewGroupName(newGroupName));
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to edit the group name : " + e.getMessage(), e);
}
refresh();
return Status.OK_STATUS;
}
}.schedule();
}
private void deleteMultipleGroups(final int[] indices) {
new Job("Delete groups") {
@Override
protected IStatus run(IProgressMonitor monitor) {
for (int index : indices) {
String groupName = contentProvider.getItemByIndex(index).getGroupName();
try {
deleteGroup(groupName);
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete groups: " + e.getMessage(), e);
}
}
refresh();
return Status.OK_STATUS;
}
}.schedule();
}
@Override
protected void listGroups() {
groups = iam.listGroups().getGroups();
}
@Override
public void refresh() {
new LoadGroupTableThread().start();
}
}
| 7,471 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/CreateGroupWizard.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.identitymanagement.group;
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.wizard.Wizard;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.CreateGroupRequest;
import com.amazonaws.services.identitymanagement.model.PutGroupPolicyRequest;
public class CreateGroupWizard extends Wizard {
private CreateGroupFirstPage firstPage;
private CreateGroupSecondPage secondPage;
private CreateGroupWizardDataModel dataModel;
private AmazonIdentityManagement iam;
private IRefreshable refreshable;
public CreateGroupWizard(AmazonIdentityManagement iam, IRefreshable refreshable) {
setNeedsProgressMonitor(false);
setWindowTitle("Create New Group");
setDefaultPageImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
dataModel = new CreateGroupWizardDataModel();
this.iam = iam;
if (iam == null) {
this.iam = AwsToolkitCore.getClientFactory().getIAMClient();
}
this.refreshable = refreshable;
}
public CreateGroupWizard() {
this(AwsToolkitCore.getClientFactory().getIAMClient(), null);
}
@Override
public boolean performFinish() {
final PutGroupPolicyRequest putGroupPolicyRequest = generatePutGroupPolicyRequest();
new Job("Creating groups") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
iam.createGroup(new CreateGroupRequest().withGroupName(dataModel.getGroupName()));
if (putGroupPolicyRequest != null) {
iam.putGroupPolicy(putGroupPolicyRequest);
}
if (refreshable != null) {
refreshable.refreshData();
}
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to create the group: " + e.getMessage(), e);
}
return Status.OK_STATUS;
}
}.schedule();
return true;
}
@Override
public void addPages() {
firstPage = new CreateGroupFirstPage(this);
secondPage = new CreateGroupSecondPage(this);
addPage(firstPage);
addPage(secondPage);
}
private PutGroupPolicyRequest generatePutGroupPolicyRequest() {
if ( !dataModel.getGrantPermission() ) {
return null;
} else {
return new PutGroupPolicyRequest().withGroupName(dataModel.getGroupName()).withPolicyName(dataModel.getPolicyName()).withPolicyDocument(dataModel.getPolicyDoc());
}
}
public CreateGroupWizardDataModel getDataModel() {
return dataModel;
}
}
| 7,472 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/AddUsersToGroupDialog.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.identitymanagement.group;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
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.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AddUserToGroupRequest;
import com.amazonaws.services.identitymanagement.model.GetGroupRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.User;
public class AddUsersToGroupDialog extends TitleAreaDialog {
private final FormToolkit toolkit;
private final List<Button> userButtons = new ArrayList<>();
private final Group group;
private final List<User> usersInGroup;
private AmazonIdentityManagement iam;
private UsersInGroupTable usersInGroupTable;
public AddUsersToGroupDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, Group group, UsersInGroupTable usersInGroupTable) {
super(parentShell);
this.toolkit = toolkit;
this.group = group;
this.iam = iam;
usersInGroup = getUsersInGroup();
this.usersInGroupTable = usersInGroupTable;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Select the users to add to the group " + "'" + group.getGroupName() + "'");
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Add Users To Group");
shell.setMinimumSize(400, 500);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
composite.setBackground(toolkit.getColors().getBackground());
ScrolledForm form = new ScrolledForm(composite, SWT.V_SCROLL);
form.setLayoutData(new GridData(GridData.FILL_BOTH));
form.setBackground(toolkit.getColors().getBackground());
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.getBody().setLayout(new GridLayout(1, false));
Label label = toolkit.createLabel(form.getBody(), "User Name:");
label.setFont(new Font(Display.getCurrent(), "Arial", 12, SWT.BOLD));
for (User user : listUsers()) {
Button button = toolkit.createButton(form.getBody(), user.getUserName(), SWT.CHECK);
userButtons.add(button);
if (usersInGroup.contains(user)) {
button.setSelection(true);
button.setEnabled(false);
}
}
return composite;
}
private void addUserToGroup(String userName) {
iam.addUserToGroup(new AddUserToGroupRequest().withGroupName(group.getGroupName()).withUserName(userName));
}
private List<User> getUsersInGroup() {
return iam.getGroup(new GetGroupRequest().withGroupName(group.getGroupName())).getUsers();
}
private List<User> listUsers() {
return iam.listUsers().getUsers();
}
@Override
protected void okPressed() {
final List<String> users = new LinkedList<>();
for (Button button : userButtons) {
if (button.getSelection() && button.getEnabled()) {
users.add(button.getText());
}
}
new Job("Adding users to group") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
for (String user : users) {
addUserToGroup(user);
}
usersInGroupTable.refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to add user to groups: " + e.getMessage(), e);
}
}
}.schedule();
super.okPressed();
}
}
| 7,473 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/UsersInGroup.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.identitymanagement.group;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Group;
public class UsersInGroup extends Composite {
private UsersInGroupTable usersInGroupTable;
private Group group;
private Button addUserButton;
public UsersInGroup(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit, final EditorInput groupEditorInput) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
this.setBackground(toolkit.getColors().getBackground());
this.setLayout(new GridLayout());
Section policySection = toolkit.createSection(this, Section.TITLE_BAR);
policySection.setText("Users");
policySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(policySection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
usersInGroupTable = new UsersInGroupTable(iam, client, toolkit, groupEditorInput);
usersInGroupTable.setLayoutData(new GridData(GridData.FILL_BOTH));
addUserButton = toolkit.createButton(client, "Add Users", SWT.PUSH);
addUserButton.setEnabled(false);
addUserButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
addUserButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
addUserButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
AddUsersToGroupDialog addUserToGroupDialog = new AddUsersToGroupDialog(iam, Display.getCurrent().getActiveShell(), toolkit, group, usersInGroupTable);
addUserToGroupDialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
policySection.setClient(client);
}
public void setGroup(Group group) {
this.group = group;
usersInGroupTable.setGroup(group);
if (group != null) {
addUserButton.setEnabled(true);
} else {
addUserButton.setEnabled(false);
}
}
public void refresh() {
usersInGroupTable.refresh();
}
}
| 7,474 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/AddGroupPolicyDialog.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.identitymanagement.group;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractAddPolicyDialog;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.PutGroupPolicyRequest;
class AddGroupPolicyDialog extends AbstractAddPolicyDialog {
private final Group group;
public AddGroupPolicyDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, Group group, GroupPermissionTable groupPermissionTable) {
super(iam, parentShell, toolkit, groupPermissionTable);
this.group = group;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Manage Group Permission");
}
@Override
protected void putPolicy(String policyName, String policyDoc) {
iam.putGroupPolicy(new PutGroupPolicyRequest().withGroupName(group.getGroupName()).withPolicyName(policyName).withPolicyDocument(policyDoc));
}
}
| 7,475 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/group/UsersInGroupTable.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.identitymanagement.group;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractUserTable;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.GetGroupRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.RemoveUserFromGroupRequest;
public class UsersInGroupTable extends AbstractUserTable {
private Group group;
AmazonIdentityManagement iam;
public UsersInGroupTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit, EditorInput userEditorInput) {
super(iam, parent, toolkit, userEditorInput);
this.iam = iam;
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
for (int index : viewer.getTable().getSelectionIndices()) {
String userName = contentProvider.getItemByIndex(index).getUserName();
removeUser(userName);
}
refresh();
}
@Override
public String getText() {
if (viewer.getTable().getSelectionIndices().length > 1) {
return "Remove Users";
}
return "Remove User";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
private void removeUser(String userName) {
iam.removeUserFromGroup(new RemoveUserFromGroupRequest().withGroupName(group.getGroupName()).withUserName(userName));
}
public void setGroup(Group group) {
this.group = group;
refresh();
}
@Override
public void refresh() {
new LoadUserTableThread().start();
}
@Override
protected void listUsers() {
if (group != null) {
users = iam.getGroup(new GetGroupRequest(group.getGroupName())).getUsers();
} else {
users = null;
}
}
}
| 7,476 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserTable.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.identitymanagement.user;
import java.util.List;
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.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractUserTable;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata;
import com.amazonaws.services.identitymanagement.model.DeleteAccessKeyRequest;
import com.amazonaws.services.identitymanagement.model.DeleteLoginProfileRequest;
import com.amazonaws.services.identitymanagement.model.DeleteSigningCertificateRequest;
import com.amazonaws.services.identitymanagement.model.DeleteUserPolicyRequest;
import com.amazonaws.services.identitymanagement.model.DeleteUserRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.ListAccessKeysRequest;
import com.amazonaws.services.identitymanagement.model.ListAccessKeysResult;
import com.amazonaws.services.identitymanagement.model.ListGroupsForUserRequest;
import com.amazonaws.services.identitymanagement.model.ListSigningCertificatesRequest;
import com.amazonaws.services.identitymanagement.model.ListSigningCertificatesResult;
import com.amazonaws.services.identitymanagement.model.ListUserPoliciesRequest;
import com.amazonaws.services.identitymanagement.model.ListUserPoliciesResult;
import com.amazonaws.services.identitymanagement.model.RemoveUserFromGroupRequest;
import com.amazonaws.services.identitymanagement.model.SigningCertificate;
import com.amazonaws.services.identitymanagement.model.User;
public class UserTable extends AbstractUserTable {
private UserSummary userSummary = null;
private UserPermission userPermission = null;
private GroupsForUser userGroups = null;
public UserTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit, EditorInput userEditorInput) {
super(iam, parent, toolkit, userEditorInput);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
userSummary.setUser(null);
userPermission.setUser(null);
userGroups.setUser(null);
deleteMultipleUsers(viewer.getTable().getSelectionIndices());
}
@Override
public String getText() {
if (viewer.getTable().getSelectionIndices().length > 1) {
return "Delete Users";
}
return "Delete User";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
viewer.getTable().addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event event) {
int index = viewer.getTable().getSelectionIndex();
if (index >= 0) {
User user = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
userSummary.setUser(user);
userPermission.setUser(user);
userGroups.setUser(user);
} else {
userSummary.setUser(null);
userPermission.setUser(null);
userGroups.setUser(null);
}
}
});
}
public void setUserSummary(UserSummary userSummary) {
this.userSummary = userSummary;
}
public void setUserPermission(UserPermission userPermission) {
this.userPermission = userPermission;
}
public void setGroups(GroupsForUser groups) {
this.userGroups = groups;
}
private void deleteMultipleUsers(final int[] indices) {
new Job("Delete users") {
@Override
protected IStatus run(IProgressMonitor monitor) {
for (int index : indices) {
String userName = contentProvider.getItemByIndex(index).getUserName();
try {
deleteUser(userName);
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete users: " + e.getMessage(), e);
}
}
refresh();
return Status.OK_STATUS;
}
}.schedule();
}
private void deleteUser(String userName) {
deleteAccessKeysForUser(userName);
deleteUserPoliciesForUser(userName);
deleteCertificatesForUser(userName);
deleteUserFromGroups(userName);
try {
iam.deleteLoginProfile(new DeleteLoginProfileRequest().withUserName(userName));
} catch (Exception e) {
// No body cares.
}
iam.deleteUser(new DeleteUserRequest().withUserName(userName));
}
private void deleteAccessKeysForUser(String userName) {
ListAccessKeysResult response = iam.listAccessKeys(new ListAccessKeysRequest().withUserName(userName));
for (AccessKeyMetadata akm : response.getAccessKeyMetadata()) {
iam.deleteAccessKey(new DeleteAccessKeyRequest().withUserName(userName).withAccessKeyId(akm.getAccessKeyId()));
}
}
private void deleteUserPoliciesForUser(String userName) {
ListUserPoliciesResult response = iam.listUserPolicies(new ListUserPoliciesRequest().withUserName(userName));
for (String pName : response.getPolicyNames()) {
iam.deleteUserPolicy(new DeleteUserPolicyRequest().withUserName(userName).withPolicyName(pName));
}
}
private void deleteCertificatesForUser(String userName) {
ListSigningCertificatesResult response = iam.listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName));
for (SigningCertificate cert : response.getCertificates()) {
iam.deleteSigningCertificate(new DeleteSigningCertificateRequest().withUserName(userName).withCertificateId(cert.getCertificateId()));
}
}
private void deleteUserFromGroups(String userName) {
List<Group> groups = iam.listGroupsForUser(new ListGroupsForUserRequest().withUserName(userName)).getGroups();
for (Group group : groups) {
iam.removeUserFromGroup(new RemoveUserFromGroupRequest().withGroupName(group.getGroupName()).withUserName(userName));
}
}
@Override
public void refresh() {
new LoadUserTableThread().start();
}
@Override
protected void listUsers() {
users = iam.listUsers().getUsers();
}
}
| 7,477 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/GroupForUserTable.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.identitymanagement.user;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractGroupTable;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.ListGroupsForUserRequest;
import com.amazonaws.services.identitymanagement.model.RemoveUserFromGroupRequest;
import com.amazonaws.services.identitymanagement.model.User;
public class GroupForUserTable extends AbstractGroupTable {
private User user;
public GroupForUserTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(iam, parent, toolkit);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
for (int index : viewer.getTable().getSelectionIndices()) {
String groupName = contentProvider.getItemByIndex(index).getGroupName();
removeUserFromGroup(groupName);
}
refresh();
}
@Override
public String getText() {
if (viewer.getTable().getSelectionIndices().length > 1) {
return "Remove From Groups";
}
return "Remove From Group";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
private void removeUserFromGroup(String groupName) {
iam.removeUserFromGroup(new RemoveUserFromGroupRequest().withGroupName(groupName).withUserName(user.getUserName()));
}
public void setUser(User user) {
this.user = user;
refresh();
}
@Override
public void refresh() {
new LoadGroupTableThread().start();
}
@Override
protected void listGroups() {
if (user != null) {
groups = iam.listGroupsForUser(new ListGroupsForUserRequest().withUserName(user.getUserName())).getGroups();
} else {
groups = null;
}
}
}
| 7,478 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/CreateUserWizard.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.identitymanagement.user;
import java.util.ArrayList;
import java.util.List;
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.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.CreateUserRequest;
/**
* Wizard to create a new user
*/
public class CreateUserWizard extends Wizard {
private CreateUserWizardFirstPage page;
private AmazonIdentityManagement iam;
private IRefreshable refreshable;
public CreateUserWizard(AmazonIdentityManagement iam, IRefreshable refreshable) {
setNeedsProgressMonitor(false);
setWindowTitle("Create New Users");
setDefaultPageImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_AWS_LOGO));
this.iam = iam;
if (iam == null) {
this.iam = AwsToolkitCore.getClientFactory().getIAMClient();
}
this.refreshable = refreshable;
}
public CreateUserWizard() {
this(AwsToolkitCore.getClientFactory().getIAMClient(), null);
}
@Override
public boolean performFinish() {
final List<CreateUserRequest> createUserRequests = new ArrayList<>();
for (Text userName : page.userNameTexts) {
String name = userName.getText();
if (name != null) {
// Delete the leading space.
name = name.trim();
if (name.length() > 0) {
createUserRequests.add(new CreateUserRequest().withUserName(userName.getText()));
}
}
}
new Job("Creating users") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
for (CreateUserRequest request : createUserRequests)
iam.createUser(request);
if (refreshable != null) {
refreshable.refreshData();
}
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to create users: " + e.getMessage(), e);
}
}
}.schedule();
return true;
}
@Override
public void addPages() {
page = new CreateUserWizard.CreateUserWizardFirstPage(this);
addPage(page);
}
private static class CreateUserWizardFirstPage extends WizardPage {
private final List<Text> userNameTexts = new ArrayList<>();
private final int MAX_NUMBER_USERS = 5;
public CreateUserWizardFirstPage(CreateUserWizard createUserWizard) {
super("");
}
@Override
public void createControl(Composite parent) {
final Composite comp = new Composite(parent, SWT.NONE);
comp.setLayoutData(new GridData(GridData.FILL_BOTH));
comp.setLayout(new GridLayout(2,false));
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(FieldDecorationRegistry.DEC_ERROR);
int fieldDecorationWidth = fieldDecoration.getImage().getBounds().width;
createStackNameControl(comp, fieldDecorationWidth);
setControl(comp);
validate();
}
private void createStackNameControl(final Composite comp, int fieldDecorationWidth) {
for (int i = 0; i < MAX_NUMBER_USERS; i++) {
new Label(comp, SWT.READ_ONLY).setText("User Name: ");
Text userNameText = new Text(comp, SWT.BORDER);
userNameTexts.add(i, userNameText);
GridDataFactory.fillDefaults().grab(true, false).applyTo(userNameText);
userNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
validate();
}
});
}
}
private void validate() {
for (Text userName : userNameTexts) {
if (userName.getText() != null && userName.getText().length() != 0) {
setErrorMessage(null);
setPageComplete(true);
return;
}
}
setErrorMessage("Enter user names");
setPageComplete(false);
}
}
}
| 7,479 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserCredentialManagementDialog.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.identitymanagement.user;
import java.util.List;
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.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
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.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AccessKeyMetadata;
import com.amazonaws.services.identitymanagement.model.DeleteAccessKeyRequest;
import com.amazonaws.services.identitymanagement.model.ListAccessKeysRequest;
import com.amazonaws.services.identitymanagement.model.StatusType;
import com.amazonaws.services.identitymanagement.model.UpdateAccessKeyRequest;
public class UserCredentialManagementDialog extends TitleAreaDialog {
private AmazonIdentityManagement iam;
private String userName;
private AccessKeyTable accessKeyTable;
private Button createAccessKeyButton;
public UserCredentialManagementDialog(AmazonIdentityManagement iam, Shell parentShell, String userName) {
super(parentShell);
this.iam = iam;
this.userName = userName;
setShellStyle(SWT.RESIZE);
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Use access keys to make secure requests to any AWS services.");
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Manage Access Keys");
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
composite.setLayout(new GridLayout());
composite = new Composite(composite, SWT.NULL);
GridDataFactory.fillDefaults().grab(true, true).applyTo(composite);
composite.setLayout(new GridLayout(1, false));
accessKeyTable = new AccessKeyTable(composite);
createAccessKeyButton = new Button(composite, SWT.PUSH);
createAccessKeyButton.setText("Create Access Key");
createAccessKeyButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
createAccessKeyButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
new NewAccessKeyDialog(iam, userName, accessKeyTable).open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
createLinkSection(composite);
accessKeyTable.refresh();
return composite;
}
// Create the help link
public void createLinkSection(Composite parent) {
String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/ManagingCredentials.html";
Link link = new Link(parent, SWT.NONE | SWT.WRAP);
link.setText("For your protection, you should never share your secret access keys with anyone. " + "In addition, industry best practice recommends frequent key rotation. " + "<a href=\""
+ ConceptUrl + "\">Learn more about Access Keys</a>.");
link.addListener(SWT.Selection, new WebLinkListener());
GridData gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
link.setLayoutData(gridData);
}
// Table for the access keys
public class AccessKeyTable extends Composite {
private TableViewer viewer;
private ContentProvider contentProvider;
private LabelProvider labelProvider;
public AccessKeyTable(Composite parent) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
TableColumnLayout tableColumnLayout = new TableColumnLayout();
this.setLayout(tableColumnLayout);
contentProvider = new ContentProvider();
labelProvider = new LabelProvider();
viewer = new TableViewer(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTable());
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
deleteAccessKey(viewer.getTable().getSelectionIndex());
refresh();
}
@Override
public String getText() {
return "Delete Access Key";
}
});
manager.add(new Action() {
@Override
public ImageDescriptor getImageDescriptor() {
return null;
}
@Override
public void run() {
deactivateAccessKey(viewer.getTable().getSelectionIndex());
refresh();
}
@Override
public String getText() {
return "Make Inactive";
}
});
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
public void refresh() {
new LoadAccessKeyTableThread().start();
}
private void deleteAccessKey(int index) {
final String accessKeyId = contentProvider.getItemByIndex(index).getAccessKeyId();
new Job("Delete access key") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
iam.deleteAccessKey(new DeleteAccessKeyRequest().withAccessKeyId(accessKeyId).withUserName(userName));
refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete the access key: " + e.getMessage(), e);
}
}
}.schedule();
}
private void deactivateAccessKey(int index) {
final String accessKeyId = contentProvider.getItemByIndex(index).getAccessKeyId();
new Job("Deactivate cccess key") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
iam.updateAccessKey(new UpdateAccessKeyRequest().withAccessKeyId(accessKeyId).withUserName(userName).withStatus(StatusType.Inactive));
refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to make the access key inactive: " + e.getMessage(), e);
}
}
}.schedule();
}
// Load the content for access key table.
private class LoadAccessKeyTableThread extends Thread {
@Override
public void run() {
try {
final List<AccessKeyMetadata> metadatas = listAcesskeyMetadata();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (metadatas == null) {
viewer.setInput(null);
} else {
viewer.setInput(metadatas.toArray(new AccessKeyMetadata[metadatas.size()]));
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to list access keys: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
private class ContentProvider extends ArrayContentProvider {
private AccessKeyMetadata[] metadatas;
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof AccessKeyMetadata[]) {
metadatas = (AccessKeyMetadata[]) newInput;
} else {
metadatas = new AccessKeyMetadata[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return metadatas;
}
public AccessKeyMetadata getItemByIndex(int index) {
return metadatas[index];
}
}
private class LabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof AccessKeyMetadata == false)
return "";
AccessKeyMetadata metadata = (AccessKeyMetadata) element;
switch (columnIndex) {
case 0:
return metadata.getCreateDate().toString();
case 1:
return metadata.getAccessKeyId();
case 2:
return metadata.getStatus();
}
return element.toString();
}
}
}
private void createColumns(TableColumnLayout columnLayout, Table table) {
createColumn(table, columnLayout, "Created");
createColumn(table, columnLayout, "Access Key ID");
createColumn(table, columnLayout, "Status");
}
private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
private List<AccessKeyMetadata> listAcesskeyMetadata() {
return iam.listAccessKeys(new ListAccessKeysRequest().withUserName(userName)).getAccessKeyMetadata();
}
}
| 7,480 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserPermissionTable.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.identitymanagement.user;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractPolicyTable;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteUserPolicyRequest;
import com.amazonaws.services.identitymanagement.model.ListUserPoliciesRequest;
import com.amazonaws.services.identitymanagement.model.User;
public class UserPermissionTable extends AbstractPolicyTable {
private User user;
UserPermissionTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(iam, parent, toolkit);
MenuManager menuManager = new MenuManager("#PopupMenu");
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(new IMenuListener() {
@Override
public void menuAboutToShow(IMenuManager manager) {
if (viewer.getTable().getSelectionCount() > 0) {
manager.add(new removePolicyAction());
manager.add(new ShowPolicyAction());
manager.add(new EditPolicyAction());
}
}
});
viewer.getTable().setMenu(menuManager.createContextMenu(viewer.getTable()));
}
private class removePolicyAction extends Action {
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REMOVE);
}
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
String alertMessage = "Are you sure you want to remove policy '" + policyName + "' from the user '" + user.getUserName() + "'?";
boolean confirmation = MessageDialog.openConfirm(Display.getCurrent().getActiveShell(), "Remove Policy", alertMessage);
if (confirmation) {
deletePolicy(policyName);
refresh();
}
}
@Override
public String getText() {
return "Remove Policy";
}
}
private class ShowPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowUserPolicyDialog(iam, Display.getCurrent().getActiveShell(), user, policyName, false).open();
refresh();
}
@Override
public String getText() {
return "Show Policy";
}
}
private class EditPolicyAction extends Action {
@Override
public void run() {
String policyName = contentProvider.getItemByIndex(viewer.getTable().getSelectionIndex());
new ShowUserPolicyDialog(iam, Display.getCurrent().getActiveShell(), user, policyName, true).open();
refresh();
}
@Override
public String getText() {
return "Edit Policy";
}
}
private void deletePolicy(String policyName) {
iam.deleteUserPolicy(new DeleteUserPolicyRequest().withUserName(user.getUserName()).withPolicyName(policyName));
}
@Override
protected void getPolicyNames() {
if (user != null) {
policyNames = iam.listUserPolicies(new ListUserPoliciesRequest().withUserName(user.getUserName())).getPolicyNames();
} else {
policyNames = null;
}
}
public void setUser(User user) {
this.user = user;
refresh();
}
@Override
public void refresh() {
new LoadPermissionTableThread().start();
}
}
| 7,481 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/AddUserPolicyDialog.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.identitymanagement.user;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.explorer.identitymanagement.AbstractAddPolicyDialog;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.PutUserPolicyRequest;
import com.amazonaws.services.identitymanagement.model.User;
class AddUserPolicyDialog extends AbstractAddPolicyDialog {
private final User user;
public AddUserPolicyDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, User user, UserPermissionTable userPermissionTable) {
super(iam, parentShell, toolkit, userPermissionTable);
this.user = user;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Manage User Permission");
}
@Override
protected void putPolicy(String policyName, String policyDoc) {
iam.putUserPolicy(new PutUserPolicyRequest().withUserName(user.getUserName()).withPolicyDocument(policyDoc).withPolicyName(policyName));
}
}
| 7,482 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserSummary.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.identitymanagement.user;
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.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.DeleteLoginProfileRequest;
import com.amazonaws.services.identitymanagement.model.GetLoginProfileRequest;
import com.amazonaws.services.identitymanagement.model.ListGroupsForUserRequest;
import com.amazonaws.services.identitymanagement.model.ListGroupsForUserResult;
import com.amazonaws.services.identitymanagement.model.User;
public class UserSummary extends Composite {
private User user;
private final Text userARNLable;
private final Text havePasswordLabel;
private final Text groupsLabel;
private final Text pathLabel;
private final Text creationTimeLabel;
private final Button updatePassowrdButton;
private Button removePasswordButton;
private Button manageAccessKeysButton;
private boolean hasPassword;
private AmazonIdentityManagement iam;
public UserSummary(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit) {
super(parent, SWT.NONE);
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults()
.align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).hint(200, SWT.DEFAULT);
this.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
this.setLayout(new GridLayout(4, false));
this.setBackground(toolkit.getColors().getBackground());
toolkit.createLabel(this, "User ARN:");
userARNLable = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(userARNLable);
toolkit.createLabel(this, "Groups:");
groupsLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(groupsLabel);
toolkit.createLabel(this, "Path:");
pathLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(pathLabel);
toolkit.createLabel(this, "Creation Time:");
creationTimeLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(creationTimeLabel);
toolkit.createLabel(this, "Has Password:");
havePasswordLabel = toolkit.createText(this, "", SWT.READ_ONLY | SWT.NONE);
gridDataFactory.applyTo(havePasswordLabel);
removePasswordButton = toolkit.createButton(this, "Remove Password", SWT.PUSH);
removePasswordButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
new Job("Remove password") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
removePassword();
refresh();
return Status.OK_STATUS;
} catch(Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to delete the password: " + e.getMessage(), e);
}
}
}.schedule();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
removePasswordButton.setEnabled(false);
updatePassowrdButton = toolkit.createButton(this, "Update Password", SWT.PUSH);
updatePassowrdButton.setEnabled(false);
updatePassowrdButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
new UpdatePasswordDialog(iam, UserSummary.this, Display.getCurrent().getActiveShell(), toolkit, user, hasPassword).open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
manageAccessKeysButton = toolkit.createButton(this, "Manage Access Keys", SWT.PUSH);
manageAccessKeysButton.addSelectionListener((new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
new UserCredentialManagementDialog(iam, Display.getCurrent().getActiveShell(), user.getUserName()).open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
}));
manageAccessKeysButton.setEnabled(false);
this.iam = iam;
}
public void setUser(User user) {
this.user = user;
refresh();
if (user != null) {
updatePassowrdButton.setEnabled(true);
removePasswordButton.setEnabled(true);
manageAccessKeysButton.setEnabled(true);
} else {
updatePassowrdButton.setEnabled(false);
removePasswordButton.setEnabled(false);
manageAccessKeysButton.setEnabled(false);
}
}
public void refresh() {
new LoadUserSummaryThread().start();
}
private class LoadUserSummaryThread extends Thread {
@Override
public void run() {
try {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (user != null) {
userARNLable.setText(user.getArn());
pathLabel.setText(user.getPath());
creationTimeLabel.setText(user.getCreateDate().toString());
try {
iam.getLoginProfile(new GetLoginProfileRequest().withUserName(user.getUserName()));
havePasswordLabel.setText("yes");
removePasswordButton.setEnabled(true);
hasPassword = true;
} catch (Exception e) {
havePasswordLabel.setText("no");
removePasswordButton.setEnabled(false);
hasPassword = false;
}
try {
ListGroupsForUserResult listGroupsForUserResult = iam.listGroupsForUser(new ListGroupsForUserRequest().withUserName(user.getUserName()));
groupsLabel.setText(Integer.toString(listGroupsForUserResult.getGroups().size()));
} catch (Exception e) {
groupsLabel.setText("0");
}
} else {
userARNLable.setText("");
pathLabel.setText("");
creationTimeLabel.setText("");
havePasswordLabel.setText("");
groupsLabel.setText("");
}
}});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe user summary", e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
private void removePassword() {
iam.deleteLoginProfile(new DeleteLoginProfileRequest().withUserName(user.getUserName()));
}
}
| 7,483 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/ShowUserPolicyDialog.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.identitymanagement.user;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.GetUserPolicyRequest;
import com.amazonaws.services.identitymanagement.model.PutUserPolicyRequest;
import com.amazonaws.services.identitymanagement.model.User;
class ShowUserPolicyDialog extends TitleAreaDialog {
private boolean edittable;
private Text policyText;
private User user;
private String policyName;
protected AmazonIdentityManagement iam;
public ShowUserPolicyDialog(AmazonIdentityManagement iam, Shell parentShell, User user, String policyName, boolean edittable) {
super(parentShell);
this.edittable = edittable;
this.user = user;
this.policyName = policyName;
this.iam = iam;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Policy Name :");
setMessage(policyName);
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
policyText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
try {
policyText.setText(getPolicy(policyName));
} catch (Exception e) {
setErrorMessage(e.getMessage());
}
policyText.setLayoutData(new GridData(GridData.FILL_BOTH));
if (!edittable) {
policyText.setEditable(false);
}
Dialog.applyDialogFont(parent);
return composite;
}
@Override
protected void okPressed() {
try {
if (edittable) {
putPolicy(policyName, policyText.getText());
}
} catch (Exception e) {
setErrorMessage(e.getMessage());
return;
}
super.okPressed();
}
private String getPolicy(String policyName) throws UnsupportedEncodingException {
String policyDoc = iam.getUserPolicy(new GetUserPolicyRequest().withUserName(user.getUserName()).withPolicyName(policyName))
.getPolicyDocument();
return URLDecoder.decode(policyDoc, "UTF-8");
}
private void putPolicy(String policyName, String policyDoc) {
iam.putUserPolicy(new PutUserPolicyRequest().withUserName(user.getUserName()).withPolicyDocument(policyDoc).withPolicyName(policyName));
}
}
| 7,484 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/NewAccessKeyDialog.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.identitymanagement.user;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.eclipse.identitymanagement.user.UserCredentialManagementDialog.AccessKeyTable;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.CreateAccessKeyRequest;
import com.amazonaws.services.identitymanagement.model.CreateAccessKeyResult;
public class NewAccessKeyDialog extends MessageDialog {
private String accessKeyIdLabelContent = "Access Key Id: ";
private String secretAccessKeyContent = "Secret Access Key: ";
private AmazonIdentityManagement iam;
private String userName;
private Text accessKeyIdText;
private Text secretKeyText;
private AccessKeyTable accessKeyTable;
private Button downloadButton;
private CreateAccessKeyResult createAccessKeyResult;
public NewAccessKeyDialog(AmazonIdentityManagement iam, String userName, AccessKeyTable accessKeyTable) {
super(Display.getCurrent().getActiveShell(), "Manage Access Key", null, null, MessageDialog.NONE, new String[] { "OK", "Cancel" }, 0);
this.iam = iam;
this.userName = userName;
this.accessKeyTable = accessKeyTable;
}
@Override
protected Control createCustomArea(Composite parent) {
new Label(parent, SWT.NONE).setText("This is the last time these user security credentials will be available for download. You can manage \n and recreate these credentials any time.\n");
accessKeyIdText = new Text(parent, SWT.READ_ONLY);
accessKeyIdText.setText(accessKeyIdLabelContent);
accessKeyIdText.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
GridDataFactory.fillDefaults().grab(true, false).applyTo(accessKeyIdText);
secretKeyText = new Text(parent, SWT.READ_ONLY);
secretKeyText.setText(secretAccessKeyContent);
secretKeyText.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
GridDataFactory.fillDefaults().grab(true, false).applyTo(secretKeyText);
downloadButton = new Button(parent, SWT.PUSH);
downloadButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_DOWNLOAD));
downloadButton.setText("Download");
// The button will be enabled after the new key has been created
downloadButton.setEnabled(false);
downloadButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
FileDialog fd = new FileDialog(Display.getCurrent().getActiveShell(), SWT.SAVE);
fd.setText("Save As");
fd.setFileName("credentials.csv");
String[] filterExt = { "*.csv" };
fd.setFilterExtensions(filterExt);
String path = fd.open();
if (path != null) {
try {
saveFile(path);
} catch (Exception exception) {
Status status = new Status(IStatus.ERROR, IdentityManagementPlugin.PLUGIN_ID, "Unable to download the file: " + exception.getMessage(), exception);
StatusManager.getManager().handle(status, StatusManager.SHOW);
}
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
new CreateAccessKeyThread().start();
return parent;
}
// Save the file
private void saveFile(String fileName) throws IOException {
File f = new File(fileName);
// Check whether the file already exists.
if (f.createNewFile() == false) {
throw new IOException("File already exists " + fileName);
}
String content = "";
FileWriter fstream = new FileWriter(f.getAbsoluteFile());
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write("\"User Name\",\"Access Key Id\",\"Secret Access Key\"\n");
content += "\"" + userName + "\",";
content += "\"" + createAccessKeyResult.getAccessKey().getAccessKeyId() + "\",";
content += "\"" + createAccessKeyResult.getAccessKey().getSecretAccessKey() + "\"";
out.write(content);
}
}
// Create the new access key and update the UI
private class CreateAccessKeyThread extends Thread {
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
createAccessKeyResult = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(userName));
accessKeyIdLabelContent += createAccessKeyResult.getAccessKey().getAccessKeyId();
secretAccessKeyContent += createAccessKeyResult.getAccessKey().getSecretAccessKey();
accessKeyIdText.setText(accessKeyIdLabelContent);
secretKeyText.setText(secretAccessKeyContent);
downloadButton.setEnabled(true);
accessKeyTable.refresh();
} catch (Exception e) {
NewAccessKeyDialog.this.close();
Status status = new Status(IStatus.ERROR, IdentityManagementPlugin.PLUGIN_ID, "Unable to create access key: " + e.getMessage(), e);
StatusManager.getManager().handle(status, StatusManager.SHOW);
}
}
});
}
}
}
| 7,485 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/GroupsForUser.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.identitymanagement.user;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.User;
public class GroupsForUser extends Composite {
private GroupForUserTable groupForUserTable;
private User user;
private Button addGroupButton;
public GroupsForUser(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
this.setBackground(toolkit.getColors().getBackground());
this.setLayout(new GridLayout());
Section policySection = toolkit.createSection(this, Section.TITLE_BAR);
policySection.setText("Groups");
policySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(policySection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
groupForUserTable = new GroupForUserTable(iam, client, toolkit);
groupForUserTable.setLayoutData(new GridData(GridData.FILL_BOTH));
addGroupButton = toolkit.createButton(client, "Add To Groups", SWT.PUSH);
addGroupButton.setEnabled(false);
addGroupButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
addGroupButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
addGroupButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
AddUserToGroupsDialog addUserToGroupsDialog = new AddUserToGroupsDialog(iam, Display.getCurrent().getActiveShell(), toolkit, user, groupForUserTable);
addUserToGroupsDialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
policySection.setClient(client);
}
public void setUser(User user) {
this.user = user;
groupForUserTable.setUser(user);
if (user != null) {
addGroupButton.setEnabled(true);
} else {
addGroupButton.setEnabled(false);
}
}
public void refresh() {
groupForUserTable.refresh();
}
}
| 7,486 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/AddUserToGroupsDialog.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.identitymanagement.user;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
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.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
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.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.AddUserToGroupRequest;
import com.amazonaws.services.identitymanagement.model.Group;
import com.amazonaws.services.identitymanagement.model.ListGroupsForUserRequest;
import com.amazonaws.services.identitymanagement.model.User;
public class AddUserToGroupsDialog extends TitleAreaDialog {
private FormToolkit toolkit;
private List<Button> groupButtons = new ArrayList<>();
private User user;
private List<Group> groupsForUser;
private AmazonIdentityManagement iam;
private GroupForUserTable groupForUserTable;
public AddUserToGroupsDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, User user, GroupForUserTable groupForUserTable) {
super(parentShell);
this.toolkit = toolkit;
this.user = user;
this.iam = iam;
groupsForUser = getGroupsForUser();
this.groupForUserTable = groupForUserTable;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("Select the groups to add the user " + "'" + user.getUserName() + "'");
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
return contents;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText("Add User To Groups");
shell.setMinimumSize(400, 500);
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout());
composite.setBackground(toolkit.getColors().getBackground());
ScrolledForm form = new ScrolledForm(composite, SWT.V_SCROLL);
form.setLayoutData(new GridData(GridData.FILL_BOTH));
form.setBackground(toolkit.getColors().getBackground());
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.getBody().setLayout(new GridLayout(1, false));
Label label = toolkit.createLabel(form.getBody(), "Group Name:");
label.setFont(new Font(Display.getCurrent(), "Arial", 12, SWT.BOLD));
for (Group group : listGroups()) {
Button button = toolkit.createButton(form.getBody(), group.getGroupName(), SWT.CHECK);
groupButtons.add(button);
if (groupsForUser.contains(group)) {
button.setSelection(true);
button.setEnabled(false);
}
}
return composite;
}
private void addUserToGroup(String groupName) {
iam.addUserToGroup(new AddUserToGroupRequest().withGroupName(groupName).withUserName(user.getUserName()));
}
private List<Group> getGroupsForUser() {
return iam.listGroupsForUser(new ListGroupsForUserRequest().withUserName(user.getUserName())).getGroups();
}
private List<Group> listGroups() {
return iam.listGroups().getGroups();
}
@Override
protected void okPressed() {
final List<String> groups = new LinkedList<>();
for (Button button : groupButtons) {
if (button.getSelection() && button.getEnabled()) {
groups.add(button.getText());
}
}
new Job("Adding user to groups") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
for (String group : groups) {
addUserToGroup(group);
}
groupForUserTable.refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to adding user to groups: " + e.getMessage(), e);
}
}
}.schedule();
super.okPressed();
}
}
| 7,487 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UpdatePasswordDialog.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.identitymanagement.user;
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.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.CreateLoginProfileRequest;
import com.amazonaws.services.identitymanagement.model.UpdateLoginProfileRequest;
import com.amazonaws.services.identitymanagement.model.User;
public class UpdatePasswordDialog extends TitleAreaDialog {
private FormToolkit toolkit;
private Text passwordText;
private Text confirmPasswordText;
private User user;
private boolean hasPassword;
private AmazonIdentityManagement iam;
private UserSummary userSummary;
protected Button okButton;
public UpdatePasswordDialog(AmazonIdentityManagement iam, UserSummary userSummary, Shell parentShell, FormToolkit toolkit, User user, boolean hasPassword) {
super(parentShell);
this.toolkit = toolkit;
this.user = user;
this.hasPassword = hasPassword;
this.iam = iam;
this.userSummary = userSummary;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
if (hasPassword) {
setTitle("Update User Password");
} else {
setTitle("Create User Password");
}
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
okButton = getButton(IDialogConstants.OK_ID);
validate();
return contents;
}
@Override
protected void configureShell(Shell shell) {
super.configureShell(shell);
if (hasPassword) {
shell.setText("Update User Password");
} else {
shell.setText("Create User Password");
}
shell.setMinimumSize(600, 400);
}
@Override
protected Control createDialogArea(Composite parent) {
Control control;
control = createContentPasswordLayout(parent);
return control;
}
private Composite createContentPasswordLayout(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout(1, false));
composite.setBackground(toolkit.getColors().getBackground());
GridDataFactory gridDataFactory = GridDataFactory.swtDefaults().align(SWT.FILL, SWT.TOP).grab(true, false).minSize(200, SWT.DEFAULT).span(2, SWT.DEFAULT).hint(200, SWT.DEFAULT);
toolkit.createLabel(composite, "Password:");
passwordText = toolkit.createText(composite, "", SWT.BORDER);
gridDataFactory.copy().span(2, SWT.DEFAULT).applyTo(passwordText);
toolkit.createLabel(composite, "Confirm Password:");
passwordText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
validate();
}
});
confirmPasswordText = toolkit.createText(composite, "", SWT.BORDER);
gridDataFactory.copy().span(2, SWT.DEFAULT).applyTo(confirmPasswordText);
confirmPasswordText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
validate();
}
});
return composite;
}
private void createPassword(String password) {
iam.createLoginProfile(new CreateLoginProfileRequest().withPassword(password).withUserName(user.getUserName()));
}
private void updatePassword(String password) {
iam.updateLoginProfile(new UpdateLoginProfileRequest().withPassword(password).withUserName(user.getUserName()));
}
@Override
protected void okPressed() {
final String password = passwordText.getText();
if (hasPassword) {
new Job("Update password") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
updatePassword(password);
userSummary.refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to create the password: " + e.getMessage(), e);
}
}
}.schedule();
} else {
new Job("Create password") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
createPassword(password);
userSummary.refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to update the password: " + e.getMessage(), e);
}
}
}.schedule();
}
super.okPressed();
}
private void validate() {
if (passwordText.getText() == null || passwordText.getText().length() <= 0) {
setErrorMessage("Please input a valid password.");
okButton.setEnabled(false);
return;
}
if (confirmPasswordText.getText() == null || confirmPasswordText.getText().length() <= 0 || (!confirmPasswordText.getText().equals(passwordText.getText()))) {
setErrorMessage("Password fields do not match.");
okButton.setEnabled(false);
return;
}
okButton.setEnabled(true);
setErrorMessage(null);
}
}
| 7,488 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserPermission.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.identitymanagement.user;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.User;
public class UserPermission extends Composite {
private User user;
private UserPermissionTable userPermissionTable;
private Button addPolicyButton;
public UserPermission(final AmazonIdentityManagement iam, Composite parent, final FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
this.setBackground(toolkit.getColors().getBackground());
this.setLayout(new GridLayout());
Section policySection = toolkit.createSection(this, Section.TITLE_BAR);
policySection.setText("User Policies");
policySection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
Composite client = toolkit.createComposite(policySection, SWT.WRAP);
client.setLayoutData(new GridData(GridData.FILL_BOTH));
client.setLayout(new GridLayout(2, false));
userPermissionTable = new UserPermissionTable(iam, client, toolkit);
userPermissionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
addPolicyButton = toolkit.createButton(client, "Attach Policy", SWT.PUSH);
addPolicyButton.setEnabled(false);
addPolicyButton.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
addPolicyButton.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_ADD));
addPolicyButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
AddUserPolicyDialog addUserPolicyDialog = new AddUserPolicyDialog(iam, Display.getCurrent().getActiveShell(), toolkit, user, userPermissionTable);
addUserPolicyDialog.open();
userPermissionTable.refresh();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
policySection.setClient(client);
}
public void setUser(User user) {
this.user = user;
if (user != null) {
addPolicyButton.setEnabled(true);
} else {
addPolicyButton.setEnabled(false);
}
userPermissionTable.setUser(user);
}
}
| 7,489 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/user/UserEditor.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.identitymanagement.user;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.part.EditorPart;
import com.amazonaws.eclipse.core.AWSClientFactory;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.explorer.identitymanagement.CreateUserAction;
import com.amazonaws.eclipse.explorer.identitymanagement.EditorInput;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
public class UserEditor extends EditorPart implements IRefreshable {
private EditorInput userEditorInput;
private UserTable userTable;
private UserSummary userSummary;
private UserPermission userPermission;
private GroupsForUser groups;
private AmazonIdentityManagement iam;
@Override
public void doSave(IProgressMonitor monitor) {
}
@Override
public void doSaveAs() {
}
@Override
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
setSite(site);
setInput(input);
setPartName(input.getName());
this.userEditorInput = (EditorInput) input;
iam = getClient();
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void createPartControl(Composite parent) {
FormToolkit toolkit = new FormToolkit(Display.getDefault());
ScrolledForm form = new ScrolledForm(parent, SWT.V_SCROLL);
form.setExpandHorizontal(true);
form.setExpandVertical(true);
form.setText(getFormTitle());
toolkit.decorateFormHeading(form.getForm());
form.setImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_USER));
form.getBody().setLayout(new GridLayout());
form.getToolBarManager().add(new RefreshAction());
form.getToolBarManager().add(new CreateUserAction(iam, this));
form.getToolBarManager().update(true);
SashForm sash = new SashForm(form.getBody(), SWT.VERTICAL);
sash.setLayoutData(new GridData(GridData.FILL_BOTH));
sash.setLayout(new GridLayout());
createTableSection(sash, toolkit);
createTabsSection(sash, toolkit);
userTable.setUserSummary(userSummary);
userTable.setUserPermission(userPermission);
userTable.setGroups(groups);
}
private String getFormTitle() {
String formTitle = userEditorInput.getName();
return formTitle;
}
private void createTabsSection(Composite parent, FormToolkit toolkit) {
Composite tabsSection = toolkit.createComposite(parent, SWT.NONE);
tabsSection.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
tabsSection.setLayout(new FillLayout());
TabFolder tabFolder = new TabFolder(tabsSection, SWT.BORDER);
Rectangle clientArea = parent.getClientArea();
tabFolder.setLocation(clientArea.x, clientArea.y);
TabItem summaryTab = new TabItem(tabFolder, SWT.NONE);
summaryTab.setText("Summary");
userSummary = new UserSummary(iam, tabFolder, toolkit);
summaryTab.setControl(userSummary);
TabItem permissionTab = new TabItem(tabFolder, SWT.NONE);
permissionTab.setText("Permissions");
userPermission = new UserPermission(iam, tabFolder, toolkit);
permissionTab.setControl(userPermission);
TabItem groupTab = new TabItem(tabFolder, SWT.NONE);
groupTab.setText("Groups");
groups = new GroupsForUser(iam, tabFolder, toolkit);
groupTab.setControl(groups);
}
private void createTableSection(Composite parent, FormToolkit toolkit) {
userTable = new UserTable(iam, parent, toolkit, userEditorInput);
}
@Override
public void setFocus() {
}
private class RefreshAction extends Action {
public RefreshAction() {
this.setText("Refresh");
this.setToolTipText("Refresh");
this.setImageDescriptor(AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_REFRESH));
}
@Override
public void run() {
userTable.refresh();
userSummary.refresh();
groups.refresh();
}
}
@Override
public void refreshData() {
userTable.refresh();
}
protected AmazonIdentityManagement getClient() {
AWSClientFactory clientFactory = AwsToolkitCore.getClientFactory(userEditorInput.getAccountId());
return clientFactory.getIAMClientByEndpoint(userEditorInput.getRegionEndpoint());
}
}
| 7,490 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/identitymanagement/databinding/DataBindingUtils.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.identitymanagement.databinding;
import org.eclipse.core.databinding.ValidationStatusProvider;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import com.amazonaws.eclipse.databinding.DecorationChangeListener;
public class DataBindingUtils {
/**
* Adds a control status decorator for the control given.
*/
public static void addStatusDecorator(final Control control, ValidationStatusProvider validationStatusProvider) {
ControlDecoration decoration = new ControlDecoration(control, SWT.TOP | SWT.LEFT);
decoration.setDescriptionText("Invalid value");
FieldDecoration fieldDecoration = FieldDecorationRegistry.getDefault().getFieldDecoration(
FieldDecorationRegistry.DEC_ERROR);
decoration.setImage(fieldDecoration.getImage());
new DecorationChangeListener(decoration, validationStatusProvider.getValidationStatus());
}
}
| 7,491 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/EditorInput.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.explorer.identitymanagement;
import org.eclipse.jface.resource.ImageDescriptor;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.AbstractAwsResourceEditorInput;
public class EditorInput extends AbstractAwsResourceEditorInput {
private final String titleName;
public EditorInput(String titleName, String endpoint, String accountId) {
super(endpoint, accountId);
this.titleName = titleName;
}
@Override
public String getName() {
return titleName;
}
@Override
public String getToolTipText() {
return "Amazon Identity Management Editor - " + getName();
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_STACK);
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode());
hashCode = prime * hashCode + ((getRegionEndpoint() == null) ? 0 : getRegionEndpoint().hashCode());
hashCode = prime * hashCode + ((getRegionEndpoint() == null) ? 0 : getAccountId().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof EditorInput == false) return false;
EditorInput other = (EditorInput)obj;
if (other.getName() == null ^ this.getName() == null) return false;
if (other.getName() != null && other.getName().equals(this.getName()) == false) return false;
if (other.getAccountId() == null ^ this.getAccountId() == null) return false;
if (other.getAccountId() != null && other.getAccountId().equals(this.getAccountId()) == false) return false;
if (other.getRegionEndpoint() == null ^ this.getRegionEndpoint() == null) return false;
if (other.getRegionEndpoint() != null && other.getRegionEndpoint().equals(this.getRegionEndpoint()) == false) return false;
return true;
}
}
| 7,492 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/AbstractGroupTable.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.explorer.identitymanagement;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
import com.amazonaws.services.identitymanagement.model.Group;
public abstract class AbstractGroupTable extends Composite {
protected TableViewer viewer;
protected List<Group> groups;
protected GroupTableContentProvider contentProvider;
protected AmazonIdentityManagement iam;
public AbstractGroupTable(AmazonIdentityManagement iam, Composite parent, FormToolkit toolkit) {
super(parent, SWT.NONE);
this.setLayoutData(new GridData(GridData.FILL_BOTH));
TableColumnLayout tableColumnLayout = new TableColumnLayout();
this.setLayout(tableColumnLayout);
contentProvider = new GroupTableContentProvider();
GroupTableLabelProvider labelProvider = new GroupTableLabelProvider();
viewer = new TableViewer(this, SWT.BORDER | SWT.MULTI);
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTable());
this.iam = iam;
refresh();
}
private void createColumns(TableColumnLayout columnLayout, Table table) {
createColumn(table, columnLayout, "Group Name");
createColumn(table, columnLayout, "Creation Time");
}
private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnWeightData(30));
return column;
}
protected class GroupTableContentProvider extends ArrayContentProvider {
private Group[] groups;
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if (newInput instanceof Group[]) {
groups = (Group[]) newInput;
} else {
groups = new Group[0];
}
}
@Override
public Object[] getElements(Object inputElement) {
return groups;
}
public Group getItemByIndex(int index) {
return groups[index];
}
}
private class GroupTableLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof Group == false)
return "";
Group group = (Group) element;
switch (columnIndex) {
case 0:
return group.getGroupName();
case 1:
return group.getCreateDate().toString();
default:
return "";
}
}
}
abstract public void refresh();
abstract protected void listGroups();
protected class LoadGroupTableThread extends Thread {
public LoadGroupTableThread() {
// TODO Auto-generated constructor stub
}
@Override
public void run() {
try {
listGroups();
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (groups != null) {
viewer.setInput(groups.toArray(new Group[groups.size()]));
} else {
viewer.setInput(null);
}
}
});
} catch (Exception e) {
Status status = new Status(IStatus.WARNING, IdentityManagementPlugin.PLUGIN_ID, "Unable to describe groups", e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
}
}
| 7,493 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/CreateUserAction.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.explorer.identitymanagement;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.identitymanagement.user.CreateUserWizard;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
public class CreateUserAction extends Action {
private final IRefreshable refreshable;
private AmazonIdentityManagement iam;
public CreateUserAction(AmazonIdentityManagement iam, IRefreshable refreshable) {
this.refreshable = refreshable;
setToolTipText("Create New Users");
this.iam = iam;
}
public CreateUserAction(IRefreshable refreshable) {
this(null, refreshable);
}
public CreateUserAction() {
this(null, null);
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD);
}
@Override
public String getText() {
return "Create New Users";
}
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateUserWizard(iam, refreshable));
dialog.open();
}
}
| 7,494 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/AbstractOpenEditorAction.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.explorer.identitymanagement;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
public class AbstractOpenEditorAction extends Action {
protected String titleName;
protected String editorId;
public AbstractOpenEditorAction(String titleName, String editorId) {
this.setText("Open " + titleName + " Editor");
this.titleName = titleName;
this.editorId = editorId;
}
@Override
public void run() {
String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints().get(ServiceAbbreviations.IAM);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new EditorInput(titleName, endpoint, accountId);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, editorId);
} catch (PartInitException e) {
String errorMessage = "Unable to open the Amazon Identity Management " + titleName.toLowerCase() + "editor: " + e.getMessage();
Status status = new Status(Status.ERROR, IdentityManagementPlugin.PLUGIN_ID, errorMessage, e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
});
}
}
| 7,495 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/OpenPasswordPolicyEditorAction.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.explorer.identitymanagement;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.statushandlers.StatusManager;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.regions.RegionUtils;
import com.amazonaws.eclipse.core.regions.ServiceAbbreviations;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
public class OpenPasswordPolicyEditorAction extends Action {
private final String titleName;
public OpenPasswordPolicyEditorAction(String titleName) {
this.setText("Open Password Policy Editor");
this.titleName = titleName;
}
@Override
public void run() {
String endpoint = RegionUtils.getCurrentRegion().getServiceEndpoints().get(ServiceAbbreviations.IAM);
String accountId = AwsToolkitCore.getDefault().getCurrentAccountId();
final IEditorInput input = new EditorInput(titleName, endpoint, accountId);
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
try {
IWorkbenchWindow activeWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
activeWindow.getActivePage().openEditor(input, "com.amazonaws.eclipse.explorer.identitymanagement.passwordPolicyEditor");
} catch (PartInitException e) {
String errorMessage = "Unable to open the Amazon Identity Management password policy editor: " + e.getMessage();
Status status = new Status(Status.ERROR, IdentityManagementPlugin.PLUGIN_ID, errorMessage, e);
StatusManager.getManager().handle(status, StatusManager.LOG);
}
}
});
}
}
| 7,496 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/CreateRoleAction.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.explorer.identitymanagement;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Display;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.IRefreshable;
import com.amazonaws.eclipse.identitymanagement.role.CreateRoleWizard;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
public class CreateRoleAction extends Action {
private final IRefreshable refreshable;
private AmazonIdentityManagement iam;
public CreateRoleAction(AmazonIdentityManagement iam, IRefreshable refreshable) {
this.refreshable = refreshable;
setToolTipText("Create New Role");
this.iam = iam;
}
public CreateRoleAction(IRefreshable refreshable) {
this(null, refreshable);
}
public CreateRoleAction() {
this(null, null);
}
@Override
public ImageDescriptor getImageDescriptor() {
return AwsToolkitCore.getDefault().getImageRegistry().getDescriptor(AwsToolkitCore.IMAGE_ADD);
}
@Override
public String getText() {
return "Create New Role";
}
@Override
public void run() {
WizardDialog dialog = new WizardDialog(Display.getCurrent().getActiveShell(), new CreateRoleWizard(iam, refreshable));
dialog.open();
}
}
| 7,497 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/AbstractAddPolicyDialog.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.explorer.identitymanagement;
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.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.core.ui.WebLinkListener;
import com.amazonaws.eclipse.identitymanagement.IdentityManagementPlugin;
import com.amazonaws.services.identitymanagement.AmazonIdentityManagement;
/**
* Adding JSON policy dialog base class for user, group and role.
*/
public abstract class AbstractAddPolicyDialog extends TitleAreaDialog {
protected Text policyDocText;
protected Text policyNameText;
protected final FormToolkit toolkit;
protected final String ConceptUrl = "http://docs.aws.amazon.com/IAM/latest/UserGuide/AccessPolicyLanguage_KeyConcepts.html";
protected AmazonIdentityManagement iam;
protected AbstractPolicyTable policyTable;
// The OK button for the dialog.
protected Button okButton;
public AbstractAddPolicyDialog(AmazonIdentityManagement iam, Shell parentShell, FormToolkit toolkit, AbstractPolicyTable policyTable) {
super(parentShell);
this.toolkit = toolkit;
this.iam = iam;
this.policyTable = policyTable;
}
@Override
protected Control createContents(Composite parent) {
Control contents = super.createContents(parent);
setTitle("You can customize permissions by editing the following policy document.");
setTitleImage(AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_AWS_LOGO));
okButton = getButton(IDialogConstants.OK_ID);
validate();
return contents;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
composite.setLayout(new GridLayout(1, false));
composite.setBackground(toolkit.getColors().getBackground());
toolkit.createLabel(composite, "Policy Name:");
policyNameText = toolkit.createText(composite, "", SWT.BORDER);
policyNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
policyNameText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
validate();
}
});
toolkit.createLabel(composite, "Policy Documentation:");
policyDocText = new Text(composite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.minimumHeight = 250;
policyDocText.setLayoutData(gridData);
policyDocText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
validate();
}
});
Link link = new Link(composite, SWT.NONE | SWT.WRAP);
link.setText("For more information about the access policy language, " +
"see <a href=\"" +
ConceptUrl + "\">Key Concepts</a> in Using AWS Identity and Access Management.");
link.addListener(SWT.Selection, new WebLinkListener());
gridData = new GridData(SWT.FILL, SWT.TOP, true, false);
gridData.widthHint = 200;
link.setLayoutData(gridData);
link.setBackground(toolkit.getColors().getBackground());
return composite;
}
@Override
protected void okPressed() {
final String policyName = policyNameText.getText();
final String policyDoc = policyDocText.getText();
new Job("Adding policy") {
@Override
protected IStatus run(IProgressMonitor monitor) {
try {
putPolicy(policyName, policyDoc);
policyTable.refresh();
return Status.OK_STATUS;
} catch (Exception e) {
return new Status(Status.ERROR, IdentityManagementPlugin.getDefault().getPluginId(), "Unable to add the policy: " + e.getMessage(), e);
}
}
}.schedule();
super.okPressed();
}
private void validate() {
boolean hasPolicyName = policyNameText.getText() != null && policyNameText.getText().length() > 0;
boolean hasPolicyDoc = policyDocText.getText() != null && policyDocText.getText().length() > 0;
if (hasPolicyName && hasPolicyDoc) {
setErrorMessage(null);
// Enable the OK button
okButton.setEnabled(true);
} else {
setErrorMessage("Please input a valid policy name and policy documentation.");
// Disable the OK Button
okButton.setEnabled(false);
}
}
protected abstract void putPolicy(String policyName, String policyDoc);
}
| 7,498 |
0 | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer | Create_ds/aws-toolkit-eclipse/bundles/com.amazonaws.eclipse.identitymanagement/src/com/amazonaws/eclipse/explorer/identitymanagement/IdentityManagementLabelProvider.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.explorer.identitymanagement;
import org.eclipse.swt.graphics.Image;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.eclipse.explorer.ExplorerNodeLabelProvider;
import com.amazonaws.eclipse.explorer.identitymanagement.IdentityManagementContentProvider.IdentityManagementRootElement;
public class IdentityManagementLabelProvider extends ExplorerNodeLabelProvider {
@Override
public String getText(Object element) {
if (element instanceof IdentityManagementRootElement) {
return "Amazon Identity Management";
}
return getExplorerNodeText(element);
}
@Override
public Image getDefaultImage(Object element) {
return AwsToolkitCore.getDefault().getImageRegistry().get(AwsToolkitCore.IMAGE_IAM_SERVICE);
}
}
| 7,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.